summaryrefslogtreecommitdiff
path: root/src/logreqres.c
diff options
context:
space:
mode:
authorguybe7 <guy.benoish@redislabs.com>2023-03-11 09:14:16 +0100
committerGitHub <noreply@github.com>2023-03-11 10:14:16 +0200
commit4ba47d2d2163ea77aacc9f719db91af2d7298905 (patch)
tree1290c23d28b91fbd237506faf31878918826a40c /src/logreqres.c
parentc46d68d6d273e7c86fd1f1d10caca4e47a3294f8 (diff)
downloadredis-4ba47d2d2163ea77aacc9f719db91af2d7298905.tar.gz
Add reply_schema to command json files (internal for now) (#10273)
Work in progress towards implementing a reply schema as part of COMMAND DOCS, see #9845 Since ironing the details of the reply schema of each and every command can take a long time, we would like to merge this PR when the infrastructure is ready, and let this mature in the unstable branch. Meanwhile the changes of this PR are internal, they are part of the repo, but do not affect the produced build. ### Background In #9656 we add a lot of information about Redis commands, but we are missing information about the replies ### Motivation 1. Documentation. This is the primary goal. 2. It should be possible, based on the output of COMMAND, to be able to generate client code in typed languages. In order to do that, we need Redis to tell us, in detail, what each reply looks like. 3. We would like to build a fuzzer that verifies the reply structure (for now we use the existing testsuite, see the "Testing" section) ### Schema The idea is to supply some sort of schema for the various replies of each command. The schema will describe the conceptual structure of the reply (for generated clients), as defined in RESP3. Note that the reply structure itself may change, depending on the arguments (e.g. `XINFO STREAM`, with and without the `FULL` modifier) We decided to use the standard json-schema (see https://json-schema.org/) as the reply-schema. Example for `BZPOPMIN`: ``` "reply_schema": { "oneOf": [ { "description": "Timeout reached and no elements were popped.", "type": "null" }, { "description": "The keyname, popped member, and its score.", "type": "array", "minItems": 3, "maxItems": 3, "items": [ { "description": "Keyname", "type": "string" }, { "description": "Member", "type": "string" }, { "description": "Score", "type": "number" } ] } ] } ``` #### Notes 1. It is ok that some commands' reply structure depends on the arguments and it's the caller's responsibility to know which is the relevant one. this comes after looking at other request-reply systems like OpenAPI, where the reply schema can also be oneOf and the caller is responsible to know which schema is the relevant one. 2. The reply schemas will describe RESP3 replies only. even though RESP3 is structured, we want to use reply schema for documentation (and possibly to create a fuzzer that validates the replies) 3. For documentation, the description field will include an explanation of the scenario in which the reply is sent, including any relation to arguments. for example, for `ZRANGE`'s two schemas we will need to state that one is with `WITHSCORES` and the other is without. 4. For documentation, there will be another optional field "notes" in which we will add a short description of the representation in RESP2, in case it's not trivial (RESP3's `ZRANGE`'s nested array vs. RESP2's flat array, for example) Given the above: 1. We can generate the "return" section of all commands in [redis-doc](https://redis.io/commands/) (given that "description" and "notes" are comprehensive enough) 2. We can generate a client in a strongly typed language (but the return type could be a conceptual `union` and the caller needs to know which schema is relevant). see the section below for RESP2 support. 3. We can create a fuzzer for RESP3. ### Limitations (because we are using the standard json-schema) The problem is that Redis' replies are more diverse than what the json format allows. This means that, when we convert the reply to a json (in order to validate the schema against it), we lose information (see the "Testing" section below). The other option would have been to extend the standard json-schema (and json format) to include stuff like sets, bulk-strings, error-string, etc. but that would mean also extending the schema-validator - and that seemed like too much work, so we decided to compromise. Examples: 1. We cannot tell the difference between an "array" and a "set" 2. We cannot tell the difference between simple-string and bulk-string 3. we cannot verify true uniqueness of items in commands like ZRANGE: json-schema doesn't cover the case of two identical members with different scores (e.g. `[["m1",6],["m1",7]]`) because `uniqueItems` compares (member,score) tuples and not just the member name. ### Testing This commit includes some changes inside Redis in order to verify the schemas (existing and future ones) are indeed correct (i.e. describe the actual response of Redis). To do that, we added a debugging feature to Redis that causes it to produce a log of all the commands it executed and their replies. For that, Redis needs to be compiled with `-DLOG_REQ_RES` and run with `--reg-res-logfile <file> --client-default-resp 3` (the testsuite already does that if you run it with `--log-req-res --force-resp3`) You should run the testsuite with the above args (and `--dont-clean`) in order to make Redis generate `.reqres` files (same dir as the `stdout` files) which contain request-response pairs. These files are later on processed by `./utils/req-res-log-validator.py` which does: 1. Goes over req-res files, generated by redis-servers, spawned by the testsuite (see logreqres.c) 2. For each request-response pair, it validates the response against the request's reply_schema (obtained from the extended COMMAND DOCS) 5. In order to get good coverage of the Redis commands, and all their different replies, we chose to use the existing redis test suite, rather than attempt to write a fuzzer. #### Notes about RESP2 1. We will not be able to use the testing tool to verify RESP2 replies (we are ok with that, it's time to accept RESP3 as the future RESP) 2. Since the majority of the test suite is using RESP2, and we want the server to reply with RESP3 so that we can validate it, we will need to know how to convert the actual reply to the one expected. - number and boolean are always strings in RESP2 so the conversion is easy - objects (maps) are always a flat array in RESP2 - others (nested array in RESP3's `ZRANGE` and others) will need some special per-command handling (so the client will not be totally auto-generated) Example for ZRANGE: ``` "reply_schema": { "anyOf": [ { "description": "A list of member elements", "type": "array", "uniqueItems": true, "items": { "type": "string" } }, { "description": "Members and their scores. Returned in case `WITHSCORES` was used.", "notes": "In RESP2 this is returned as a flat array", "type": "array", "uniqueItems": true, "items": { "type": "array", "minItems": 2, "maxItems": 2, "items": [ { "description": "Member", "type": "string" }, { "description": "Score", "type": "number" } ] } } ] } ``` ### Other changes 1. Some tests that behave differently depending on the RESP are now being tested for both RESP, regardless of the special log-req-res mode ("Pub/Sub PING" for example) 2. Update the history field of CLIENT LIST 3. Added basic tests for commands that were not covered at all by the testsuite ### TODO - [x] (maybe a different PR) add a "condition" field to anyOf/oneOf schemas that refers to args. e.g. when `SET` return NULL, the condition is `arguments.get||arguments.condition`, for `OK` the condition is `!arguments.get`, and for `string` the condition is `arguments.get` - https://github.com/redis/redis/issues/11896 - [x] (maybe a different PR) also run `runtest-cluster` in the req-res logging mode - [x] add the new tests to GH actions (i.e. compile with `-DLOG_REQ_RES`, run the tests, and run the validator) - [x] (maybe a different PR) figure out a way to warn about (sub)schemas that are uncovered by the output of the tests - https://github.com/redis/redis/issues/11897 - [x] (probably a separate PR) add all missing schemas - [x] check why "SDOWN is triggered by misconfigured instance replying with errors" fails with --log-req-res - [x] move the response transformers to their own file (run both regular, cluster, and sentinel tests - need to fight with the tcl including mechanism a bit) - [x] issue: module API - https://github.com/redis/redis/issues/11898 - [x] (probably a separate PR): improve schemas: add `required` to `object`s - https://github.com/redis/redis/issues/11899 Co-authored-by: Ozan Tezcan <ozantezcan@gmail.com> Co-authored-by: Hanna Fadida <hanna.fadida@redislabs.com> Co-authored-by: Oran Agra <oran@redislabs.com> Co-authored-by: Shaya Potter <shaya@redislabs.com>
Diffstat (limited to 'src/logreqres.c')
-rw-r--r--src/logreqres.c318
1 files changed, 318 insertions, 0 deletions
diff --git a/src/logreqres.c b/src/logreqres.c
new file mode 100644
index 000000000..aa54b721d
--- /dev/null
+++ b/src/logreqres.c
@@ -0,0 +1,318 @@
+/*
+ * Copyright (c) 2021, Redis Ltd.
+ * 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.
+ * * Neither the name of Redis nor the names of its contributors may be used
+ * to endorse or promote products derived from this software without
+ * specific prior written permission.
+ *
+ * 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 OWNER 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.
+ */
+
+/* This file implements the interface of logging clients' requests and
+ * responses into a file.
+ * This feature needs the LOG_REQ_RES macro to be compiled and is turned
+ * on by the req-res-logfile config."
+ *
+ * Some examples:
+ *
+ * PING:
+ *
+ * 4
+ * ping
+ * 12
+ * __argv_end__
+ * +PONG
+ *
+ * LRANGE:
+ *
+ * 6
+ * lrange
+ * 4
+ * list
+ * 1
+ * 0
+ * 2
+ * -1
+ * 12
+ * __argv_end__
+ * *1
+ * $3
+ * ele
+ *
+ * The request is everything up until the __argv_end__ marker.
+ * The format is:
+ * <number of characters>
+ * <the argument>
+ *
+ * After __argv_end__ the response appears, and the format is
+ * RESP (2 or 3, depending on what the client has configured)
+ */
+
+#include "server.h"
+#include <ctype.h>
+
+#ifdef LOG_REQ_RES
+
+/* ----- Helpers ----- */
+
+static int reqresShouldLog(client *c) {
+ if (!server.req_res_logfile)
+ return 0;
+
+ /* Ignore client with streaming non-standard response */
+ if (c->flags & (CLIENT_PUBSUB|CLIENT_MONITOR|CLIENT_SLAVE))
+ return 0;
+
+ /* We only work on masters (didn't implement reqresAppendResponse to work on shared slave buffers) */
+ if (getClientType(c) == CLIENT_TYPE_MASTER)
+ return 0;
+
+ return 1;
+}
+
+static size_t reqresAppendBuffer(client *c, void *buf, size_t len) {
+ if (!c->reqres.buf) {
+ c->reqres.capacity = max(len, 1024);
+ c->reqres.buf = zmalloc(c->reqres.capacity);
+ } else if (c->reqres.capacity - c->reqres.used < len) {
+ c->reqres.capacity += len;
+ c->reqres.buf = zrealloc(c->reqres.buf, c->reqres.capacity);
+ }
+
+ memcpy(c->reqres.buf + c->reqres.used, buf, len);
+ c->reqres.used += len;
+ return len;
+}
+
+/* Functions for requests */
+
+static size_t reqresAppendArg(client *c, char *arg, size_t arg_len) {
+ char argv_len_buf[LONG_STR_SIZE];
+ size_t argv_len_buf_len = ll2string(argv_len_buf,sizeof(argv_len_buf),(long)arg_len);
+ size_t ret = reqresAppendBuffer(c, argv_len_buf, argv_len_buf_len);
+ ret += reqresAppendBuffer(c, "\r\n", 2);
+ ret += reqresAppendBuffer(c, arg, arg_len);
+ ret += reqresAppendBuffer(c, "\r\n", 2);
+ return ret;
+}
+
+/* ----- API ----- */
+
+
+/* Zero out the clientReqResInfo struct inside the client,
+ * and free the buffer if needed */
+void reqresReset(client *c, int free_buf) {
+ if (free_buf && c->reqres.buf)
+ zfree(c->reqres.buf);
+ memset(&c->reqres, 0, sizeof(c->reqres));
+}
+
+/* Save the offset of the reply buffer (or the reply list).
+ * Should be called when adding a reply (but it will only save the offset
+ * on the very first time it's called, because of c->reqres.offset.saved)
+ * The idea is:
+ * 1. When a client is executing a command, we save the reply offset.
+ * 2. During the execution, the reply offset may grow, as addReply* functions are called.
+ * 3. When client is done with the command (commandProcessed), reqresAppendResponse
+ * is called.
+ * 4. reqresAppendResponse will append the diff between the current offset and the one from step (1)
+ * 5. When client is reset before the next command, we clear c->reqres.offset.saved and start again
+ *
+ * We cannot reply on c->sentlen to keep track because it depends on the network
+ * (reqresAppendResponse will always write the whole buffer, unlike writeToClient)
+ *
+ * Ideally, we would just have this code inside reqresAppendRequest, which is called
+ * from processCommand, but we cannot save the reply offset inside processCommand
+ * because of the following pipe-lining scenario:
+ * set rd [redis_deferring_client]
+ * set buf ""
+ * append buf "SET key vale\r\n"
+ * append buf "BLPOP mylist 0\r\n"
+ * $rd write $buf
+ * $rd flush
+ *
+ * Let's assume we save the reply offset in processCommand
+ * When BLPOP is processed the offset is 5 (+OK\r\n from the SET)
+ * Then beforeSleep is called, the +OK is written to network, and bufpos is 0
+ * When the client is finally unblocked, the cached offset is 5, but bufpos is already
+ * 0, so we would miss the first 5 bytes of the reply.
+ **/
+void reqresSaveClientReplyOffset(client *c) {
+ if (!reqresShouldLog(c))
+ return;
+
+ if (c->reqres.offset.saved)
+ return;
+
+ c->reqres.offset.saved = 1;
+
+ c->reqres.offset.bufpos = c->bufpos;
+ if (listLength(c->reply) && listNodeValue(listLast(c->reply))) {
+ c->reqres.offset.last_node.index = listLength(c->reply) - 1;
+ c->reqres.offset.last_node.used = ((clientReplyBlock *)listNodeValue(listLast(c->reply)))->used;
+ } else {
+ c->reqres.offset.last_node.index = 0;
+ c->reqres.offset.last_node.used = 0;
+ }
+}
+
+size_t reqresAppendRequest(client *c) {
+ robj **argv = c->argv;
+ int argc = c->argc;
+
+ serverAssert(argc);
+
+ if (!reqresShouldLog(c))
+ return 0;
+
+ /* Ignore commands that have streaming non-standard response */
+ sds cmd = argv[0]->ptr;
+ if (!strcasecmp(cmd,"sync") ||
+ !strcasecmp(cmd,"psync") ||
+ !strcasecmp(cmd,"monitor") ||
+ !strcasecmp(cmd,"subscribe") ||
+ !strcasecmp(cmd,"unsubscribe") ||
+ !strcasecmp(cmd,"ssubscribe") ||
+ !strcasecmp(cmd,"sunsubscribe") ||
+ !strcasecmp(cmd,"psubscribe") ||
+ !strcasecmp(cmd,"punsubscribe") ||
+ !strcasecmp(cmd,"debug") ||
+ !strcasecmp(cmd,"pfdebug") ||
+ !strcasecmp(cmd,"lolwut") ||
+ (!strcasecmp(cmd,"sentinel") && argc > 1 && !strcasecmp(argv[1]->ptr,"debug")))
+ {
+ return 0;
+ }
+
+ c->reqres.argv_logged = 1;
+
+ size_t ret = 0;
+ for (int i = 0; i < argc; i++) {
+ if (sdsEncodedObject(argv[i])) {
+ ret += reqresAppendArg(c, argv[i]->ptr, sdslen(argv[i]->ptr));
+ } else if (argv[i]->encoding == OBJ_ENCODING_INT) {
+ char buf[LONG_STR_SIZE];
+ size_t len = ll2string(buf,sizeof(buf),(long)argv[i]->ptr);
+ ret += reqresAppendArg(c, buf, len);
+ } else {
+ serverPanic("Wrong encoding in reqresAppendRequest()");
+ }
+ }
+ return ret + reqresAppendArg(c, "__argv_end__", 12);
+}
+
+size_t reqresAppendResponse(client *c) {
+ size_t ret = 0;
+
+ if (!reqresShouldLog(c))
+ return 0;
+
+ if (!c->reqres.argv_logged) /* Example: UNSUBSCRIBE */
+ return 0;
+
+ if (!c->reqres.offset.saved) /* Example: module client blocked on keys + CLIENT KILL */
+ return 0;
+
+ /* First append the static reply buffer */
+ if (c->bufpos > c->reqres.offset.bufpos) {
+ size_t written = reqresAppendBuffer(c, c->buf + c->reqres.offset.bufpos, c->bufpos - c->reqres.offset.bufpos);
+ ret += written;
+ }
+
+ int curr_index = 0;
+ size_t curr_used = 0;
+ if (listLength(c->reply)) {
+ curr_index = listLength(c->reply) - 1;
+ curr_used = ((clientReplyBlock *)listNodeValue(listLast(c->reply)))->used;
+ }
+
+ /* Now, append reply bytes from the reply list */
+ if (curr_index > c->reqres.offset.last_node.index ||
+ curr_used > c->reqres.offset.last_node.used)
+ {
+ int i = 0;
+ listIter iter;
+ listNode *curr;
+ clientReplyBlock *o;
+ listRewind(c->reply, &iter);
+ while ((curr = listNext(&iter)) != NULL) {
+ size_t written;
+
+ /* Skip nodes we had already processed */
+ if (i < c->reqres.offset.last_node.index) {
+ i++;
+ continue;
+ }
+ o = listNodeValue(curr);
+ if (o->used == 0) {
+ i++;
+ continue;
+ }
+ if (i == c->reqres.offset.last_node.index) {
+ /* Write the potentially incomplete node, which had data from
+ * before the current command started */
+ written = reqresAppendBuffer(c,
+ o->buf + c->reqres.offset.last_node.used,
+ o->used - c->reqres.offset.last_node.used);
+ } else {
+ /* New node */
+ written = reqresAppendBuffer(c, o->buf, o->used);
+ }
+ ret += written;
+ i++;
+ }
+ }
+ serverAssert(ret);
+
+ /* Flush both request and response to file */
+ FILE *fp = fopen(server.req_res_logfile, "a");
+ serverAssert(fp);
+ fwrite(c->reqres.buf, c->reqres.used, 1, fp);
+ fclose(fp);
+
+ return ret;
+}
+
+#else /* #ifdef LOG_REQ_RES */
+
+/* Just mimic the API without doing anything */
+
+void reqresReset(client *c, int free_buf) {
+ UNUSED(c);
+ UNUSED(free_buf);
+}
+
+inline void reqresSaveClientReplyOffset(client *c) {
+ UNUSED(c);
+}
+
+inline size_t reqresAppendRequest(client *c) {
+ UNUSED(c);
+ return 0;
+}
+
+inline size_t reqresAppendResponse(client *c) {
+ UNUSED(c);
+ return 0;
+}
+
+#endif /* #ifdef LOG_REQ_RES */