xref: /f-stack/app/redis-5.0.5/src/slowlog.c (revision 572c4311)
1 /* Slowlog implements a system that is able to remember the latest N
2  * queries that took more than M microseconds to execute.
3  *
4  * The execution time to reach to be logged in the slow log is set
5  * using the 'slowlog-log-slower-than' config directive, that is also
6  * readable and writable using the CONFIG SET/GET command.
7  *
8  * The slow queries log is actually not "logged" in the Redis log file
9  * but is accessible thanks to the SLOWLOG command.
10  *
11  * ----------------------------------------------------------------------------
12  *
13  * Copyright (c) 2009-2012, Salvatore Sanfilippo <antirez at gmail dot com>
14  * All rights reserved.
15  *
16  * Redistribution and use in source and binary forms, with or without
17  * modification, are permitted provided that the following conditions are met:
18  *
19  *   * Redistributions of source code must retain the above copyright notice,
20  *     this list of conditions and the following disclaimer.
21  *   * Redistributions in binary form must reproduce the above copyright
22  *     notice, this list of conditions and the following disclaimer in the
23  *     documentation and/or other materials provided with the distribution.
24  *   * Neither the name of Redis nor the names of its contributors may be used
25  *     to endorse or promote products derived from this software without
26  *     specific prior written permission.
27  *
28  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
29  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
30  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
31  * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
32  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
33  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
34  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
35  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
36  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
37  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
38  * POSSIBILITY OF SUCH DAMAGE.
39  */
40 
41 
42 #include "server.h"
43 #include "slowlog.h"
44 
45 /* Create a new slowlog entry.
46  * Incrementing the ref count of all the objects retained is up to
47  * this function. */
slowlogCreateEntry(client * c,robj ** argv,int argc,long long duration)48 slowlogEntry *slowlogCreateEntry(client *c, robj **argv, int argc, long long duration) {
49     slowlogEntry *se = zmalloc(sizeof(*se));
50     int j, slargc = argc;
51 
52     if (slargc > SLOWLOG_ENTRY_MAX_ARGC) slargc = SLOWLOG_ENTRY_MAX_ARGC;
53     se->argc = slargc;
54     se->argv = zmalloc(sizeof(robj*)*slargc);
55     for (j = 0; j < slargc; j++) {
56         /* Logging too many arguments is a useless memory waste, so we stop
57          * at SLOWLOG_ENTRY_MAX_ARGC, but use the last argument to specify
58          * how many remaining arguments there were in the original command. */
59         if (slargc != argc && j == slargc-1) {
60             se->argv[j] = createObject(OBJ_STRING,
61                 sdscatprintf(sdsempty(),"... (%d more arguments)",
62                 argc-slargc+1));
63         } else {
64             /* Trim too long strings as well... */
65             if (argv[j]->type == OBJ_STRING &&
66                 sdsEncodedObject(argv[j]) &&
67                 sdslen(argv[j]->ptr) > SLOWLOG_ENTRY_MAX_STRING)
68             {
69                 sds s = sdsnewlen(argv[j]->ptr, SLOWLOG_ENTRY_MAX_STRING);
70 
71                 s = sdscatprintf(s,"... (%lu more bytes)",
72                     (unsigned long)
73                     sdslen(argv[j]->ptr) - SLOWLOG_ENTRY_MAX_STRING);
74                 se->argv[j] = createObject(OBJ_STRING,s);
75             } else if (argv[j]->refcount == OBJ_SHARED_REFCOUNT) {
76                 se->argv[j] = argv[j];
77             } else {
78                 /* Here we need to dupliacate the string objects composing the
79                  * argument vector of the command, because those may otherwise
80                  * end shared with string objects stored into keys. Having
81                  * shared objects between any part of Redis, and the data
82                  * structure holding the data, is a problem: FLUSHALL ASYNC
83                  * may release the shared string object and create a race. */
84                 se->argv[j] = dupStringObject(argv[j]);
85             }
86         }
87     }
88     se->time = time(NULL);
89     se->duration = duration;
90     se->id = server.slowlog_entry_id++;
91     se->peerid = sdsnew(getClientPeerId(c));
92     se->cname = c->name ? sdsnew(c->name->ptr) : sdsempty();
93     return se;
94 }
95 
96 /* Free a slow log entry. The argument is void so that the prototype of this
97  * function matches the one of the 'free' method of adlist.c.
98  *
99  * This function will take care to release all the retained object. */
slowlogFreeEntry(void * septr)100 void slowlogFreeEntry(void *septr) {
101     slowlogEntry *se = septr;
102     int j;
103 
104     for (j = 0; j < se->argc; j++)
105         decrRefCount(se->argv[j]);
106     zfree(se->argv);
107     sdsfree(se->peerid);
108     sdsfree(se->cname);
109     zfree(se);
110 }
111 
112 /* Initialize the slow log. This function should be called a single time
113  * at server startup. */
slowlogInit(void)114 void slowlogInit(void) {
115     server.slowlog = listCreate();
116     server.slowlog_entry_id = 0;
117     listSetFreeMethod(server.slowlog,slowlogFreeEntry);
118 }
119 
120 /* Push a new entry into the slow log.
121  * This function will make sure to trim the slow log accordingly to the
122  * configured max length. */
slowlogPushEntryIfNeeded(client * c,robj ** argv,int argc,long long duration)123 void slowlogPushEntryIfNeeded(client *c, robj **argv, int argc, long long duration) {
124     if (server.slowlog_log_slower_than < 0) return; /* Slowlog disabled */
125     if (duration >= server.slowlog_log_slower_than)
126         listAddNodeHead(server.slowlog,
127                         slowlogCreateEntry(c,argv,argc,duration));
128 
129     /* Remove old entries if needed. */
130     while (listLength(server.slowlog) > server.slowlog_max_len)
131         listDelNode(server.slowlog,listLast(server.slowlog));
132 }
133 
134 /* Remove all the entries from the current slow log. */
slowlogReset(void)135 void slowlogReset(void) {
136     while (listLength(server.slowlog) > 0)
137         listDelNode(server.slowlog,listLast(server.slowlog));
138 }
139 
140 /* The SLOWLOG command. Implements all the subcommands needed to handle the
141  * Redis slow log. */
slowlogCommand(client * c)142 void slowlogCommand(client *c) {
143     if (c->argc == 2 && !strcasecmp(c->argv[1]->ptr,"help")) {
144         const char *help[] = {
145 "GET [count] -- Return top entries from the slowlog (default: 10)."
146 "    Entries are made of:",
147 "    id, timestamp, time in microseconds, arguments array, client IP and port, client name",
148 "LEN -- Return the length of the slowlog.",
149 "RESET -- Reset the slowlog.",
150 NULL
151         };
152         addReplyHelp(c, help);
153     } else if (c->argc == 2 && !strcasecmp(c->argv[1]->ptr,"reset")) {
154         slowlogReset();
155         addReply(c,shared.ok);
156     } else if (c->argc == 2 && !strcasecmp(c->argv[1]->ptr,"len")) {
157         addReplyLongLong(c,listLength(server.slowlog));
158     } else if ((c->argc == 2 || c->argc == 3) &&
159                !strcasecmp(c->argv[1]->ptr,"get"))
160     {
161         long count = 10, sent = 0;
162         listIter li;
163         void *totentries;
164         listNode *ln;
165         slowlogEntry *se;
166 
167         if (c->argc == 3 &&
168             getLongFromObjectOrReply(c,c->argv[2],&count,NULL) != C_OK)
169             return;
170 
171         listRewind(server.slowlog,&li);
172         totentries = addDeferredMultiBulkLength(c);
173         while(count-- && (ln = listNext(&li))) {
174             int j;
175 
176             se = ln->value;
177             addReplyMultiBulkLen(c,6);
178             addReplyLongLong(c,se->id);
179             addReplyLongLong(c,se->time);
180             addReplyLongLong(c,se->duration);
181             addReplyMultiBulkLen(c,se->argc);
182             for (j = 0; j < se->argc; j++)
183                 addReplyBulk(c,se->argv[j]);
184             addReplyBulkCBuffer(c,se->peerid,sdslen(se->peerid));
185             addReplyBulkCBuffer(c,se->cname,sdslen(se->cname));
186             sent++;
187         }
188         setDeferredMultiBulkLength(c,totentries,sent);
189     } else {
190         addReplySubcommandSyntaxError(c);
191     }
192 }
193