blob: e96c32381dfbf75a960d6becd4ae6a4caa22fdea [file] [log] [blame]
William Lallemand74c24fb2016-11-21 17:18:36 +01001/*
2 * Functions dedicated to statistics output and the stats socket
3 *
4 * Copyright 2000-2012 Willy Tarreau <w@1wt.eu>
5 * Copyright 2007-2009 Krzysztof Piotr Oledzki <ole@ans.pl>
6 *
7 * This program is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU General Public License
9 * as published by the Free Software Foundation; either version
10 * 2 of the License, or (at your option) any later version.
11 *
12 */
13
14#include <ctype.h>
15#include <errno.h>
16#include <fcntl.h>
17#include <stdio.h>
18#include <stdlib.h>
19#include <string.h>
20#include <pwd.h>
21#include <grp.h>
22
23#include <sys/socket.h>
24#include <sys/stat.h>
25#include <sys/types.h>
26
27#include <common/cfgparse.h>
28#include <common/compat.h>
29#include <common/config.h>
30#include <common/debug.h>
31#include <common/memory.h>
32#include <common/mini-clist.h>
33#include <common/standard.h>
34#include <common/ticks.h>
35#include <common/time.h>
36#include <common/uri_auth.h>
37#include <common/version.h>
38#include <common/base64.h>
39
40#include <types/applet.h>
William Lallemand9ed62032016-11-21 17:49:11 +010041#include <types/cli.h>
William Lallemand74c24fb2016-11-21 17:18:36 +010042#include <types/global.h>
43#include <types/dns.h>
William Lallemand9ed62032016-11-21 17:49:11 +010044#include <types/stats.h>
William Lallemand74c24fb2016-11-21 17:18:36 +010045
46#include <proto/backend.h>
47#include <proto/channel.h>
48#include <proto/checks.h>
49#include <proto/compression.h>
William Lallemand9ed62032016-11-21 17:49:11 +010050#include <proto/stats.h>
William Lallemand74c24fb2016-11-21 17:18:36 +010051#include <proto/fd.h>
52#include <proto/freq_ctr.h>
53#include <proto/frontend.h>
54#include <proto/log.h>
55#include <proto/pattern.h>
56#include <proto/pipe.h>
57#include <proto/listener.h>
58#include <proto/map.h>
59#include <proto/proto_http.h>
60#include <proto/proto_uxst.h>
61#include <proto/proxy.h>
62#include <proto/sample.h>
63#include <proto/session.h>
64#include <proto/stream.h>
65#include <proto/server.h>
66#include <proto/raw_sock.h>
67#include <proto/stream_interface.h>
68#include <proto/task.h>
69
70#ifdef USE_OPENSSL
71#include <proto/ssl_sock.h>
72#include <types/ssl_sock.h>
73#endif
74
75/* These are the field names for each INF_* field position. Please pay attention
76 * to always use the exact same name except that the strings for new names must
77 * be lower case or CamelCase while the enum entries must be upper case.
78 */
79const char *info_field_names[INF_TOTAL_FIELDS] = {
80 [INF_NAME] = "Name",
81 [INF_VERSION] = "Version",
82 [INF_RELEASE_DATE] = "Release_date",
83 [INF_NBPROC] = "Nbproc",
84 [INF_PROCESS_NUM] = "Process_num",
85 [INF_PID] = "Pid",
86 [INF_UPTIME] = "Uptime",
87 [INF_UPTIME_SEC] = "Uptime_sec",
88 [INF_MEMMAX_MB] = "Memmax_MB",
89 [INF_POOL_ALLOC_MB] = "PoolAlloc_MB",
90 [INF_POOL_USED_MB] = "PoolUsed_MB",
91 [INF_POOL_FAILED] = "PoolFailed",
92 [INF_ULIMIT_N] = "Ulimit-n",
93 [INF_MAXSOCK] = "Maxsock",
94 [INF_MAXCONN] = "Maxconn",
95 [INF_HARD_MAXCONN] = "Hard_maxconn",
96 [INF_CURR_CONN] = "CurrConns",
97 [INF_CUM_CONN] = "CumConns",
98 [INF_CUM_REQ] = "CumReq",
99 [INF_MAX_SSL_CONNS] = "MaxSslConns",
100 [INF_CURR_SSL_CONNS] = "CurrSslConns",
101 [INF_CUM_SSL_CONNS] = "CumSslConns",
102 [INF_MAXPIPES] = "Maxpipes",
103 [INF_PIPES_USED] = "PipesUsed",
104 [INF_PIPES_FREE] = "PipesFree",
105 [INF_CONN_RATE] = "ConnRate",
106 [INF_CONN_RATE_LIMIT] = "ConnRateLimit",
107 [INF_MAX_CONN_RATE] = "MaxConnRate",
108 [INF_SESS_RATE] = "SessRate",
109 [INF_SESS_RATE_LIMIT] = "SessRateLimit",
110 [INF_MAX_SESS_RATE] = "MaxSessRate",
111 [INF_SSL_RATE] = "SslRate",
112 [INF_SSL_RATE_LIMIT] = "SslRateLimit",
113 [INF_MAX_SSL_RATE] = "MaxSslRate",
114 [INF_SSL_FRONTEND_KEY_RATE] = "SslFrontendKeyRate",
115 [INF_SSL_FRONTEND_MAX_KEY_RATE] = "SslFrontendMaxKeyRate",
116 [INF_SSL_FRONTEND_SESSION_REUSE_PCT] = "SslFrontendSessionReuse_pct",
117 [INF_SSL_BACKEND_KEY_RATE] = "SslBackendKeyRate",
118 [INF_SSL_BACKEND_MAX_KEY_RATE] = "SslBackendMaxKeyRate",
119 [INF_SSL_CACHE_LOOKUPS] = "SslCacheLookups",
120 [INF_SSL_CACHE_MISSES] = "SslCacheMisses",
121 [INF_COMPRESS_BPS_IN] = "CompressBpsIn",
122 [INF_COMPRESS_BPS_OUT] = "CompressBpsOut",
123 [INF_COMPRESS_BPS_RATE_LIM] = "CompressBpsRateLim",
124 [INF_ZLIB_MEM_USAGE] = "ZlibMemUsage",
125 [INF_MAX_ZLIB_MEM_USAGE] = "MaxZlibMemUsage",
126 [INF_TASKS] = "Tasks",
127 [INF_RUN_QUEUE] = "Run_queue",
128 [INF_IDLE_PCT] = "Idle_pct",
129 [INF_NODE] = "node",
130 [INF_DESCRIPTION] = "description",
131};
132
133/* one line of stats */
134static struct field info[INF_TOTAL_FIELDS];
135
136static int stats_dump_backend_to_buffer(struct stream_interface *si);
137static int stats_dump_env_to_buffer(struct stream_interface *si);
138static int stats_dump_info_to_buffer(struct stream_interface *si);
139static int stats_dump_servers_state_to_buffer(struct stream_interface *si);
William Lallemand74c24fb2016-11-21 17:18:36 +0100140static int stats_dump_full_sess_to_buffer(struct stream_interface *si, struct stream *sess);
141static int stats_dump_sess_to_buffer(struct stream_interface *si);
142static int stats_dump_errors_to_buffer(struct stream_interface *si);
143static int stats_table_request(struct stream_interface *si, int show);
William Lallemand74c24fb2016-11-21 17:18:36 +0100144
145static int dump_servers_state(struct stream_interface *si, struct chunk *buf);
146
147static struct applet cli_applet;
148
149static const char stats_sock_usage_msg[] =
150 "Unknown command. Please enter one of the following commands only :\n"
151 " clear counters : clear max statistics counters (add 'all' for all counters)\n"
152 " clear table : remove an entry from a table\n"
153 " help : this message\n"
154 " prompt : toggle interactive mode with prompt\n"
155 " quit : disconnect\n"
156 " show backend : list backends in the current running config\n"
157 " show env [var] : dump environment variables known to the process\n"
158 " show info : report information about the running process\n"
William Lallemand74c24fb2016-11-21 17:18:36 +0100159 " show stat : report counters for each proxy and server\n"
William Lallemand74c24fb2016-11-21 17:18:36 +0100160 " show errors : report last request and response errors for each proxy\n"
161 " show sess [id] : report the list of current sessions or dump this session\n"
162 " show table [id]: report table usage stats or dump this table's contents\n"
163 " show servers state [id]: dump volatile server information (for backend <id>)\n"
164 " get weight : report a server's current weight\n"
165 " set weight : change a server's weight\n"
William Lallemand74c24fb2016-11-21 17:18:36 +0100166 " set table [id] : update or create a table entry's data\n"
167 " set timeout : change a timeout setting\n"
168 " set maxconn : change a maxconn setting\n"
169 " set rate-limit : change a rate limiting value\n"
170 " disable : put a server or frontend in maintenance mode\n"
171 " enable : re-enable a server or frontend which is in maintenance mode\n"
172 " shutdown : kill a session or a frontend (eg:to release listening ports)\n"
William Lallemand74c24fb2016-11-21 17:18:36 +0100173 "";
174
175static const char stats_permission_denied_msg[] =
176 "Permission denied\n"
177 "";
178
179
180static char *dynamic_usage_msg = NULL;
181
182/* List head of cli keywords */
183static struct cli_kw_list cli_keywords = {
184 .list = LIST_HEAD_INIT(cli_keywords.list)
185};
186
187extern const char *stat_status_codes[];
188
189char *cli_gen_usage_msg()
190{
191 struct cli_kw_list *kw_list;
192 struct cli_kw *kw;
193 struct chunk *tmp = get_trash_chunk();
194 struct chunk out;
195
196 free(dynamic_usage_msg);
197 dynamic_usage_msg = NULL;
198
199 if (LIST_ISEMPTY(&cli_keywords.list))
200 return NULL;
201
202 chunk_reset(tmp);
203 chunk_strcat(tmp, stats_sock_usage_msg);
204 list_for_each_entry(kw_list, &cli_keywords.list, list) {
205 kw = &kw_list->kw[0];
206 while (kw->usage) {
207 chunk_appendf(tmp, " %s\n", kw->usage);
208 kw++;
209 }
210 }
211 chunk_init(&out, NULL, 0);
212 chunk_dup(&out, tmp);
213 dynamic_usage_msg = out.str;
214 return dynamic_usage_msg;
215}
216
217struct cli_kw* cli_find_kw(char **args)
218{
219 struct cli_kw_list *kw_list;
220 struct cli_kw *kw;/* current cli_kw */
221 char **tmp_args;
222 const char **tmp_str_kw;
223 int found = 0;
224
225 if (LIST_ISEMPTY(&cli_keywords.list))
226 return NULL;
227
228 list_for_each_entry(kw_list, &cli_keywords.list, list) {
229 kw = &kw_list->kw[0];
230 while (*kw->str_kw) {
231 tmp_args = args;
232 tmp_str_kw = kw->str_kw;
233 while (*tmp_str_kw) {
234 if (strcmp(*tmp_str_kw, *tmp_args) == 0) {
235 found = 1;
236 } else {
237 found = 0;
238 break;
239 }
240 tmp_args++;
241 tmp_str_kw++;
242 }
243 if (found)
244 return (kw);
245 kw++;
246 }
247 }
248 return NULL;
249}
250
251void cli_register_kw(struct cli_kw_list *kw_list)
252{
253 LIST_ADDQ(&cli_keywords.list, &kw_list->list);
254}
255
256
257/* allocate a new stats frontend named <name>, and return it
258 * (or NULL in case of lack of memory).
259 */
260static struct proxy *alloc_stats_fe(const char *name, const char *file, int line)
261{
262 struct proxy *fe;
263
264 fe = calloc(1, sizeof(*fe));
265 if (!fe)
266 return NULL;
267
268 init_new_proxy(fe);
269 fe->next = proxy;
270 proxy = fe;
271 fe->last_change = now.tv_sec;
272 fe->id = strdup("GLOBAL");
273 fe->cap = PR_CAP_FE;
274 fe->maxconn = 10; /* default to 10 concurrent connections */
275 fe->timeout.client = MS_TO_TICKS(10000); /* default timeout of 10 seconds */
276 fe->conf.file = strdup(file);
277 fe->conf.line = line;
278 fe->accept = frontend_accept;
279 fe->default_target = &cli_applet.obj_type;
280
281 /* the stats frontend is the only one able to assign ID #0 */
282 fe->conf.id.key = fe->uuid = 0;
283 eb32_insert(&used_proxy_id, &fe->conf.id);
284 return fe;
285}
286
287/* This function parses a "stats" statement in the "global" section. It returns
288 * -1 if there is any error, otherwise zero. If it returns -1, it will write an
289 * error message into the <err> buffer which will be preallocated. The trailing
290 * '\n' must not be written. The function must be called with <args> pointing to
291 * the first word after "stats".
292 */
293static int stats_parse_global(char **args, int section_type, struct proxy *curpx,
294 struct proxy *defpx, const char *file, int line,
295 char **err)
296{
297 struct bind_conf *bind_conf;
298 struct listener *l;
299
300 if (!strcmp(args[1], "socket")) {
301 int cur_arg;
302
303 if (*args[2] == 0) {
304 memprintf(err, "'%s %s' in global section expects an address or a path to a UNIX socket", args[0], args[1]);
305 return -1;
306 }
307
308 if (!global.stats_fe) {
309 if ((global.stats_fe = alloc_stats_fe("GLOBAL", file, line)) == NULL) {
310 memprintf(err, "'%s %s' : out of memory trying to allocate a frontend", args[0], args[1]);
311 return -1;
312 }
313 }
314
315 bind_conf = bind_conf_alloc(&global.stats_fe->conf.bind, file, line, args[2]);
316 bind_conf->level = ACCESS_LVL_OPER; /* default access level */
317
318 if (!str2listener(args[2], global.stats_fe, bind_conf, file, line, err)) {
319 memprintf(err, "parsing [%s:%d] : '%s %s' : %s\n",
320 file, line, args[0], args[1], err && *err ? *err : "error");
321 return -1;
322 }
323
324 cur_arg = 3;
325 while (*args[cur_arg]) {
326 static int bind_dumped;
327 struct bind_kw *kw;
328
329 kw = bind_find_kw(args[cur_arg]);
330 if (kw) {
331 if (!kw->parse) {
332 memprintf(err, "'%s %s' : '%s' option is not implemented in this version (check build options).",
333 args[0], args[1], args[cur_arg]);
334 return -1;
335 }
336
337 if (kw->parse(args, cur_arg, global.stats_fe, bind_conf, err) != 0) {
338 if (err && *err)
339 memprintf(err, "'%s %s' : '%s'", args[0], args[1], *err);
340 else
341 memprintf(err, "'%s %s' : error encountered while processing '%s'",
342 args[0], args[1], args[cur_arg]);
343 return -1;
344 }
345
346 cur_arg += 1 + kw->skip;
347 continue;
348 }
349
350 if (!bind_dumped) {
351 bind_dump_kws(err);
352 indent_msg(err, 4);
353 bind_dumped = 1;
354 }
355
356 memprintf(err, "'%s %s' : unknown keyword '%s'.%s%s",
357 args[0], args[1], args[cur_arg],
358 err && *err ? " Registered keywords :" : "", err && *err ? *err : "");
359 return -1;
360 }
361
362 list_for_each_entry(l, &bind_conf->listeners, by_bind) {
363 l->maxconn = global.stats_fe->maxconn;
364 l->backlog = global.stats_fe->backlog;
365 l->accept = session_accept_fd;
366 l->handler = process_stream;
367 l->default_target = global.stats_fe->default_target;
368 l->options |= LI_O_UNLIMITED; /* don't make the peers subject to global limits */
369 l->nice = -64; /* we want to boost priority for local stats */
370 global.maxsock += l->maxconn;
371 }
372 }
373 else if (!strcmp(args[1], "timeout")) {
374 unsigned timeout;
375 const char *res = parse_time_err(args[2], &timeout, TIME_UNIT_MS);
376
377 if (res) {
378 memprintf(err, "'%s %s' : unexpected character '%c'", args[0], args[1], *res);
379 return -1;
380 }
381
382 if (!timeout) {
383 memprintf(err, "'%s %s' expects a positive value", args[0], args[1]);
384 return -1;
385 }
386 if (!global.stats_fe) {
387 if ((global.stats_fe = alloc_stats_fe("GLOBAL", file, line)) == NULL) {
388 memprintf(err, "'%s %s' : out of memory trying to allocate a frontend", args[0], args[1]);
389 return -1;
390 }
391 }
392 global.stats_fe->timeout.client = MS_TO_TICKS(timeout);
393 }
394 else if (!strcmp(args[1], "maxconn")) {
395 int maxconn = atol(args[2]);
396
397 if (maxconn <= 0) {
398 memprintf(err, "'%s %s' expects a positive value", args[0], args[1]);
399 return -1;
400 }
401
402 if (!global.stats_fe) {
403 if ((global.stats_fe = alloc_stats_fe("GLOBAL", file, line)) == NULL) {
404 memprintf(err, "'%s %s' : out of memory trying to allocate a frontend", args[0], args[1]);
405 return -1;
406 }
407 }
408 global.stats_fe->maxconn = maxconn;
409 }
410 else if (!strcmp(args[1], "bind-process")) { /* enable the socket only on some processes */
411 int cur_arg = 2;
412 unsigned long set = 0;
413
414 if (!global.stats_fe) {
415 if ((global.stats_fe = alloc_stats_fe("GLOBAL", file, line)) == NULL) {
416 memprintf(err, "'%s %s' : out of memory trying to allocate a frontend", args[0], args[1]);
417 return -1;
418 }
419 }
420
421 while (*args[cur_arg]) {
422 unsigned int low, high;
423
424 if (strcmp(args[cur_arg], "all") == 0) {
425 set = 0;
426 break;
427 }
428 else if (strcmp(args[cur_arg], "odd") == 0) {
429 set |= ~0UL/3UL; /* 0x555....555 */
430 }
431 else if (strcmp(args[cur_arg], "even") == 0) {
432 set |= (~0UL/3UL) << 1; /* 0xAAA...AAA */
433 }
434 else if (isdigit((int)*args[cur_arg])) {
435 char *dash = strchr(args[cur_arg], '-');
436
437 low = high = str2uic(args[cur_arg]);
438 if (dash)
439 high = str2uic(dash + 1);
440
441 if (high < low) {
442 unsigned int swap = low;
443 low = high;
444 high = swap;
445 }
446
447 if (low < 1 || high > LONGBITS) {
448 memprintf(err, "'%s %s' supports process numbers from 1 to %d.\n",
449 args[0], args[1], LONGBITS);
450 return -1;
451 }
452 while (low <= high)
453 set |= 1UL << (low++ - 1);
454 }
455 else {
456 memprintf(err,
457 "'%s %s' expects 'all', 'odd', 'even', or a list of process ranges with numbers from 1 to %d.\n",
458 args[0], args[1], LONGBITS);
459 return -1;
460 }
461 cur_arg++;
462 }
463 global.stats_fe->bind_proc = set;
464 }
465 else {
466 memprintf(err, "'%s' only supports 'socket', 'maxconn', 'bind-process' and 'timeout' (got '%s')", args[0], args[1]);
467 return -1;
468 }
469 return 0;
470}
471
Willy Tarreaude57a572016-11-23 17:01:39 +0100472/* Verifies that the CLI at least has a level at least as high as <level>
473 * (typically ACCESS_LVL_ADMIN). Returns 1 if OK, otherwise 0. In case of
474 * failure, an error message is prepared and the appctx's state is adjusted
475 * to print it so that a return 1 is enough to abort any processing.
476 */
477int cli_has_level(struct appctx *appctx, int level)
478{
479 struct stream_interface *si = appctx->owner;
480 struct stream *s = si_strm(si);
481
482 if (strm_li(s)->bind_conf->level < level) {
483 appctx->ctx.cli.msg = stats_permission_denied_msg;
484 appctx->st0 = STAT_CLI_PRINT;
485 return 0;
486 }
487 return 1;
488}
489
William Lallemand74c24fb2016-11-21 17:18:36 +0100490
491/* print a string of text buffer to <out>. The format is :
492 * Non-printable chars \t, \n, \r and \e are * encoded in C format.
493 * Other non-printable chars are encoded "\xHH". Space, '\', and '=' are also escaped.
494 * Print stopped if null char or <bsize> is reached, or if no more place in the chunk.
495 */
496static int dump_text(struct chunk *out, const char *buf, int bsize)
497{
498 unsigned char c;
499 int ptr = 0;
500
501 while (buf[ptr] && ptr < bsize) {
502 c = buf[ptr];
503 if (isprint(c) && isascii(c) && c != '\\' && c != ' ' && c != '=') {
504 if (out->len > out->size - 1)
505 break;
506 out->str[out->len++] = c;
507 }
508 else if (c == '\t' || c == '\n' || c == '\r' || c == '\e' || c == '\\' || c == ' ' || c == '=') {
509 if (out->len > out->size - 2)
510 break;
511 out->str[out->len++] = '\\';
512 switch (c) {
513 case ' ': c = ' '; break;
514 case '\t': c = 't'; break;
515 case '\n': c = 'n'; break;
516 case '\r': c = 'r'; break;
517 case '\e': c = 'e'; break;
518 case '\\': c = '\\'; break;
519 case '=': c = '='; break;
520 }
521 out->str[out->len++] = c;
522 }
523 else {
524 if (out->len > out->size - 4)
525 break;
526 out->str[out->len++] = '\\';
527 out->str[out->len++] = 'x';
528 out->str[out->len++] = hextab[(c >> 4) & 0xF];
529 out->str[out->len++] = hextab[c & 0xF];
530 }
531 ptr++;
532 }
533
534 return ptr;
535}
536
537/* print a buffer in hexa.
538 * Print stopped if <bsize> is reached, or if no more place in the chunk.
539 */
540static int dump_binary(struct chunk *out, const char *buf, int bsize)
541{
542 unsigned char c;
543 int ptr = 0;
544
545 while (ptr < bsize) {
546 c = buf[ptr];
547
548 if (out->len > out->size - 2)
549 break;
550 out->str[out->len++] = hextab[(c >> 4) & 0xF];
551 out->str[out->len++] = hextab[c & 0xF];
552
553 ptr++;
554 }
555 return ptr;
556}
557
558/* Dump the status of a table to a stream interface's
559 * read buffer. It returns 0 if the output buffer is full
560 * and needs to be called again, otherwise non-zero.
561 */
562static int stats_dump_table_head_to_buffer(struct chunk *msg, struct stream_interface *si,
563 struct proxy *proxy, struct proxy *target)
564{
565 struct stream *s = si_strm(si);
566
567 chunk_appendf(msg, "# table: %s, type: %s, size:%d, used:%d\n",
568 proxy->id, stktable_types[proxy->table.type].kw, proxy->table.size, proxy->table.current);
569
570 /* any other information should be dumped here */
571
572 if (target && strm_li(s)->bind_conf->level < ACCESS_LVL_OPER)
573 chunk_appendf(msg, "# contents not dumped due to insufficient privileges\n");
574
575 if (bi_putchk(si_ic(si), msg) == -1) {
576 si_applet_cant_put(si);
577 return 0;
578 }
579
580 return 1;
581}
582
583/* Dump the a table entry to a stream interface's
584 * read buffer. It returns 0 if the output buffer is full
585 * and needs to be called again, otherwise non-zero.
586 */
587static int stats_dump_table_entry_to_buffer(struct chunk *msg, struct stream_interface *si,
588 struct proxy *proxy, struct stksess *entry)
589{
590 int dt;
591
592 chunk_appendf(msg, "%p:", entry);
593
594 if (proxy->table.type == SMP_T_IPV4) {
595 char addr[INET_ADDRSTRLEN];
596 inet_ntop(AF_INET, (const void *)&entry->key.key, addr, sizeof(addr));
597 chunk_appendf(msg, " key=%s", addr);
598 }
599 else if (proxy->table.type == SMP_T_IPV6) {
600 char addr[INET6_ADDRSTRLEN];
601 inet_ntop(AF_INET6, (const void *)&entry->key.key, addr, sizeof(addr));
602 chunk_appendf(msg, " key=%s", addr);
603 }
604 else if (proxy->table.type == SMP_T_SINT) {
605 chunk_appendf(msg, " key=%u", *(unsigned int *)entry->key.key);
606 }
607 else if (proxy->table.type == SMP_T_STR) {
608 chunk_appendf(msg, " key=");
609 dump_text(msg, (const char *)entry->key.key, proxy->table.key_size);
610 }
611 else {
612 chunk_appendf(msg, " key=");
613 dump_binary(msg, (const char *)entry->key.key, proxy->table.key_size);
614 }
615
616 chunk_appendf(msg, " use=%d exp=%d", entry->ref_cnt - 1, tick_remain(now_ms, entry->expire));
617
618 for (dt = 0; dt < STKTABLE_DATA_TYPES; dt++) {
619 void *ptr;
620
621 if (proxy->table.data_ofs[dt] == 0)
622 continue;
623 if (stktable_data_types[dt].arg_type == ARG_T_DELAY)
624 chunk_appendf(msg, " %s(%d)=", stktable_data_types[dt].name, proxy->table.data_arg[dt].u);
625 else
626 chunk_appendf(msg, " %s=", stktable_data_types[dt].name);
627
628 ptr = stktable_data_ptr(&proxy->table, entry, dt);
629 switch (stktable_data_types[dt].std_type) {
630 case STD_T_SINT:
631 chunk_appendf(msg, "%d", stktable_data_cast(ptr, std_t_sint));
632 break;
633 case STD_T_UINT:
634 chunk_appendf(msg, "%u", stktable_data_cast(ptr, std_t_uint));
635 break;
636 case STD_T_ULL:
637 chunk_appendf(msg, "%lld", stktable_data_cast(ptr, std_t_ull));
638 break;
639 case STD_T_FRQP:
640 chunk_appendf(msg, "%d",
641 read_freq_ctr_period(&stktable_data_cast(ptr, std_t_frqp),
642 proxy->table.data_arg[dt].u));
643 break;
644 }
645 }
646 chunk_appendf(msg, "\n");
647
648 if (bi_putchk(si_ic(si), msg) == -1) {
649 si_applet_cant_put(si);
650 return 0;
651 }
652
653 return 1;
654}
655
656static void stats_sock_table_key_request(struct stream_interface *si, char **args, int action)
657{
658 struct stream *s = si_strm(si);
659 struct appctx *appctx = __objt_appctx(si->end);
660 struct proxy *px = appctx->ctx.table.target;
661 struct stksess *ts;
662 uint32_t uint32_key;
663 unsigned char ip6_key[sizeof(struct in6_addr)];
664 long long value;
665 int data_type;
666 int cur_arg;
667 void *ptr;
668 struct freq_ctr_period *frqp;
669
670 appctx->st0 = STAT_CLI_OUTPUT;
671
672 if (!*args[4]) {
673 appctx->ctx.cli.msg = "Key value expected\n";
674 appctx->st0 = STAT_CLI_PRINT;
675 return;
676 }
677
678 switch (px->table.type) {
679 case SMP_T_IPV4:
680 uint32_key = htonl(inetaddr_host(args[4]));
681 static_table_key->key = &uint32_key;
682 break;
683 case SMP_T_IPV6:
684 inet_pton(AF_INET6, args[4], ip6_key);
685 static_table_key->key = &ip6_key;
686 break;
687 case SMP_T_SINT:
688 {
689 char *endptr;
690 unsigned long val;
691 errno = 0;
692 val = strtoul(args[4], &endptr, 10);
693 if ((errno == ERANGE && val == ULONG_MAX) ||
694 (errno != 0 && val == 0) || endptr == args[4] ||
695 val > 0xffffffff) {
696 appctx->ctx.cli.msg = "Invalid key\n";
697 appctx->st0 = STAT_CLI_PRINT;
698 return;
699 }
700 uint32_key = (uint32_t) val;
701 static_table_key->key = &uint32_key;
702 break;
703 }
704 break;
705 case SMP_T_STR:
706 static_table_key->key = args[4];
707 static_table_key->key_len = strlen(args[4]);
708 break;
709 default:
710 switch (action) {
711 case STAT_CLI_O_TAB:
712 appctx->ctx.cli.msg = "Showing keys from tables of type other than ip, ipv6, string and integer is not supported\n";
713 break;
714 case STAT_CLI_O_CLR:
715 appctx->ctx.cli.msg = "Removing keys from ip tables of type other than ip, ipv6, string and integer is not supported\n";
716 break;
717 default:
718 appctx->ctx.cli.msg = "Unknown action\n";
719 break;
720 }
721 appctx->st0 = STAT_CLI_PRINT;
722 return;
723 }
724
725 /* check permissions */
726 if (strm_li(s)->bind_conf->level < ACCESS_LVL_OPER) {
727 appctx->ctx.cli.msg = stats_permission_denied_msg;
728 appctx->st0 = STAT_CLI_PRINT;
729 return;
730 }
731
732 ts = stktable_lookup_key(&px->table, static_table_key);
733
734 switch (action) {
735 case STAT_CLI_O_TAB:
736 if (!ts)
737 return;
738 chunk_reset(&trash);
739 if (!stats_dump_table_head_to_buffer(&trash, si, px, px))
740 return;
741 stats_dump_table_entry_to_buffer(&trash, si, px, ts);
742 return;
743
744 case STAT_CLI_O_CLR:
745 if (!ts)
746 return;
747 if (ts->ref_cnt) {
748 /* don't delete an entry which is currently referenced */
749 appctx->ctx.cli.msg = "Entry currently in use, cannot remove\n";
750 appctx->st0 = STAT_CLI_PRINT;
751 return;
752 }
753 stksess_kill(&px->table, ts);
754 break;
755
756 case STAT_CLI_O_SET:
757 if (ts)
758 stktable_touch(&px->table, ts, 1);
759 else {
760 ts = stksess_new(&px->table, static_table_key);
761 if (!ts) {
762 /* don't delete an entry which is currently referenced */
763 appctx->ctx.cli.msg = "Unable to allocate a new entry\n";
764 appctx->st0 = STAT_CLI_PRINT;
765 return;
766 }
767 stktable_store(&px->table, ts, 1);
768 }
769
770 for (cur_arg = 5; *args[cur_arg]; cur_arg += 2) {
771 if (strncmp(args[cur_arg], "data.", 5) != 0) {
772 appctx->ctx.cli.msg = "\"data.<type>\" followed by a value expected\n";
773 appctx->st0 = STAT_CLI_PRINT;
774 return;
775 }
776
777 data_type = stktable_get_data_type(args[cur_arg] + 5);
778 if (data_type < 0) {
779 appctx->ctx.cli.msg = "Unknown data type\n";
780 appctx->st0 = STAT_CLI_PRINT;
781 return;
782 }
783
784 if (!px->table.data_ofs[data_type]) {
785 appctx->ctx.cli.msg = "Data type not stored in this table\n";
786 appctx->st0 = STAT_CLI_PRINT;
787 return;
788 }
789
790 if (!*args[cur_arg+1] || strl2llrc(args[cur_arg+1], strlen(args[cur_arg+1]), &value) != 0) {
791 appctx->ctx.cli.msg = "Require a valid integer value to store\n";
792 appctx->st0 = STAT_CLI_PRINT;
793 return;
794 }
795
796 ptr = stktable_data_ptr(&px->table, ts, data_type);
797
798 switch (stktable_data_types[data_type].std_type) {
799 case STD_T_SINT:
800 stktable_data_cast(ptr, std_t_sint) = value;
801 break;
802 case STD_T_UINT:
803 stktable_data_cast(ptr, std_t_uint) = value;
804 break;
805 case STD_T_ULL:
806 stktable_data_cast(ptr, std_t_ull) = value;
807 break;
808 case STD_T_FRQP:
809 /* We set both the current and previous values. That way
810 * the reported frequency is stable during all the period
811 * then slowly fades out. This allows external tools to
812 * push measures without having to update them too often.
813 */
814 frqp = &stktable_data_cast(ptr, std_t_frqp);
815 frqp->curr_tick = now_ms;
816 frqp->prev_ctr = 0;
817 frqp->curr_ctr = value;
818 break;
819 }
820 }
821 break;
822
823 default:
824 appctx->ctx.cli.msg = "Unknown action\n";
825 appctx->st0 = STAT_CLI_PRINT;
826 break;
827 }
828}
829
830static void stats_sock_table_data_request(struct stream_interface *si, char **args, int action)
831{
832 struct appctx *appctx = __objt_appctx(si->end);
833
834 if (action != STAT_CLI_O_TAB && action != STAT_CLI_O_CLR) {
835 appctx->ctx.cli.msg = "content-based lookup is only supported with the \"show\" and \"clear\" actions";
836 appctx->st0 = STAT_CLI_PRINT;
837 return;
838 }
839
840 /* condition on stored data value */
841 appctx->ctx.table.data_type = stktable_get_data_type(args[3] + 5);
842 if (appctx->ctx.table.data_type < 0) {
843 appctx->ctx.cli.msg = "Unknown data type\n";
844 appctx->st0 = STAT_CLI_PRINT;
845 return;
846 }
847
848 if (!((struct proxy *)appctx->ctx.table.target)->table.data_ofs[appctx->ctx.table.data_type]) {
849 appctx->ctx.cli.msg = "Data type not stored in this table\n";
850 appctx->st0 = STAT_CLI_PRINT;
851 return;
852 }
853
854 appctx->ctx.table.data_op = get_std_op(args[4]);
855 if (appctx->ctx.table.data_op < 0) {
856 appctx->ctx.cli.msg = "Require and operator among \"eq\", \"ne\", \"le\", \"ge\", \"lt\", \"gt\"\n";
857 appctx->st0 = STAT_CLI_PRINT;
858 return;
859 }
860
861 if (!*args[5] || strl2llrc(args[5], strlen(args[5]), &appctx->ctx.table.value) != 0) {
862 appctx->ctx.cli.msg = "Require a valid integer value to compare against\n";
863 appctx->st0 = STAT_CLI_PRINT;
864 return;
865 }
866}
867
868static void stats_sock_table_request(struct stream_interface *si, char **args, int action)
869{
870 struct appctx *appctx = __objt_appctx(si->end);
871
872 appctx->ctx.table.data_type = -1;
873 appctx->st2 = STAT_ST_INIT;
874 appctx->ctx.table.target = NULL;
875 appctx->ctx.table.proxy = NULL;
876 appctx->ctx.table.entry = NULL;
877 appctx->st0 = action;
878
879 if (*args[2]) {
880 appctx->ctx.table.target = proxy_tbl_by_name(args[2]);
881 if (!appctx->ctx.table.target) {
882 appctx->ctx.cli.msg = "No such table\n";
883 appctx->st0 = STAT_CLI_PRINT;
884 return;
885 }
886 }
887 else {
888 if (action != STAT_CLI_O_TAB)
889 goto err_args;
890 return;
891 }
892
893 if (strcmp(args[3], "key") == 0)
894 stats_sock_table_key_request(si, args, action);
895 else if (strncmp(args[3], "data.", 5) == 0)
896 stats_sock_table_data_request(si, args, action);
897 else if (*args[3])
898 goto err_args;
899
900 return;
901
902err_args:
903 switch (action) {
904 case STAT_CLI_O_TAB:
905 appctx->ctx.cli.msg = "Optional argument only supports \"data.<store_data_type>\" <operator> <value> and key <key>\n";
906 break;
907 case STAT_CLI_O_CLR:
908 appctx->ctx.cli.msg = "Required arguments: <table> \"data.<store_data_type>\" <operator> <value> or <table> key <key>\n";
909 break;
910 default:
911 appctx->ctx.cli.msg = "Unknown action\n";
912 break;
913 }
914 appctx->st0 = STAT_CLI_PRINT;
915}
916
917/* Expects to find a frontend named <arg> and returns it, otherwise displays various
918 * adequate error messages and returns NULL. This function also expects the stream
919 * level to be admin.
920 */
921static struct proxy *expect_frontend_admin(struct stream *s, struct stream_interface *si, const char *arg)
922{
923 struct appctx *appctx = __objt_appctx(si->end);
924 struct proxy *px;
925
926 if (strm_li(s)->bind_conf->level < ACCESS_LVL_ADMIN) {
927 appctx->ctx.cli.msg = stats_permission_denied_msg;
928 appctx->st0 = STAT_CLI_PRINT;
929 return NULL;
930 }
931
932 if (!*arg) {
933 appctx->ctx.cli.msg = "A frontend name is expected.\n";
934 appctx->st0 = STAT_CLI_PRINT;
935 return NULL;
936 }
937
938 px = proxy_fe_by_name(arg);
939 if (!px) {
940 appctx->ctx.cli.msg = "No such frontend.\n";
941 appctx->st0 = STAT_CLI_PRINT;
942 return NULL;
943 }
944 return px;
945}
946
947/* Expects to find a backend and a server in <arg> under the form <backend>/<server>,
948 * and returns the pointer to the server. Otherwise, display adequate error messages
949 * and returns NULL. This function also expects the stream level to be admin. Note:
950 * the <arg> is modified to remove the '/'.
951 */
William Lallemand222baf22016-11-19 02:00:33 +0100952struct server *expect_server_admin(struct stream *s, struct stream_interface *si, char *arg)
William Lallemand74c24fb2016-11-21 17:18:36 +0100953{
954 struct appctx *appctx = __objt_appctx(si->end);
955 struct proxy *px;
956 struct server *sv;
957 char *line;
958
959 if (strm_li(s)->bind_conf->level < ACCESS_LVL_ADMIN) {
960 appctx->ctx.cli.msg = stats_permission_denied_msg;
961 appctx->st0 = STAT_CLI_PRINT;
962 return NULL;
963 }
964
965 /* split "backend/server" and make <line> point to server */
966 for (line = arg; *line; line++)
967 if (*line == '/') {
968 *line++ = '\0';
969 break;
970 }
971
972 if (!*line || !*arg) {
973 appctx->ctx.cli.msg = "Require 'backend/server'.\n";
974 appctx->st0 = STAT_CLI_PRINT;
975 return NULL;
976 }
977
978 if (!get_backend_server(arg, line, &px, &sv)) {
979 appctx->ctx.cli.msg = px ? "No such server.\n" : "No such backend.\n";
980 appctx->st0 = STAT_CLI_PRINT;
981 return NULL;
982 }
983
984 if (px->state == PR_STSTOPPED) {
985 appctx->ctx.cli.msg = "Proxy is disabled.\n";
986 appctx->st0 = STAT_CLI_PRINT;
987 return NULL;
988 }
989
990 return sv;
991}
992
William Lallemand74c24fb2016-11-21 17:18:36 +0100993/* Processes the stats interpreter on the statistics socket. This function is
994 * called from an applet running in a stream interface. The function returns 1
995 * if the request was understood, otherwise zero. It sets appctx->st0 to a value
996 * designating the function which will have to process the request, which can
997 * also be the print function to display the return message set into cli.msg.
998 */
999static int stats_sock_parse_request(struct stream_interface *si, char *line)
1000{
1001 struct stream *s = si_strm(si);
1002 struct appctx *appctx = __objt_appctx(si->end);
1003 char *args[MAX_STATS_ARGS + 1];
1004 struct cli_kw *kw;
1005 int arg;
1006 int i, j;
1007
1008 while (isspace((unsigned char)*line))
1009 line++;
1010
1011 arg = 0;
1012 args[arg] = line;
1013
1014 while (*line && arg < MAX_STATS_ARGS) {
1015 if (*line == '\\') {
1016 line++;
1017 if (*line == '\0')
1018 break;
1019 }
1020 else if (isspace((unsigned char)*line)) {
1021 *line++ = '\0';
1022
1023 while (isspace((unsigned char)*line))
1024 line++;
1025
1026 args[++arg] = line;
1027 continue;
1028 }
1029
1030 line++;
1031 }
1032
1033 while (++arg <= MAX_STATS_ARGS)
1034 args[arg] = line;
1035
1036 /* remove \ */
1037 arg = 0;
1038 while (*args[arg] != '\0') {
1039 j = 0;
1040 for (i=0; args[arg][i] != '\0'; i++) {
1041 if (args[arg][i] == '\\')
1042 continue;
1043 args[arg][j] = args[arg][i];
1044 j++;
1045 }
1046 args[arg][j] = '\0';
1047 arg++;
1048 }
1049
1050 appctx->ctx.stats.scope_str = 0;
1051 appctx->ctx.stats.scope_len = 0;
1052 appctx->ctx.stats.flags = 0;
1053 if ((kw = cli_find_kw(args))) {
1054 if (kw->parse) {
1055 if (kw->parse(args, appctx, kw->private) == 0 && kw->io_handler) {
1056 appctx->st0 = STAT_CLI_O_CUSTOM;
1057 appctx->io_handler = kw->io_handler;
1058 appctx->io_release = kw->io_release;
1059 }
1060 }
1061 } else if (strcmp(args[0], "show") == 0) {
1062 if (strcmp(args[1], "backend") == 0) {
1063 appctx->ctx.be.px = NULL;
1064 appctx->st2 = STAT_ST_INIT;
1065 appctx->st0 = STAT_CLI_O_BACKEND;
1066 }
1067 else if (strcmp(args[1], "env") == 0) {
1068 extern char **environ;
1069
1070 if (strm_li(s)->bind_conf->level < ACCESS_LVL_OPER) {
1071 appctx->ctx.cli.msg = stats_permission_denied_msg;
1072 appctx->st0 = STAT_CLI_PRINT;
1073 return 1;
1074 }
1075 appctx->ctx.env.var = environ;
1076 appctx->st2 = STAT_ST_INIT;
1077 appctx->st0 = STAT_CLI_O_ENV; // stats_dump_env_to_buffer
1078
1079 if (*args[2]) {
1080 int len = strlen(args[2]);
1081
1082 for (; *appctx->ctx.env.var; appctx->ctx.env.var++) {
1083 if (strncmp(*appctx->ctx.env.var, args[2], len) == 0 &&
1084 (*appctx->ctx.env.var)[len] == '=')
1085 break;
1086 }
1087 if (!*appctx->ctx.env.var) {
1088 appctx->ctx.cli.msg = "Variable not found\n";
1089 appctx->st0 = STAT_CLI_PRINT;
1090 return 1;
1091 }
1092 appctx->st2 = STAT_ST_END;
1093 }
1094 }
1095 else if (strcmp(args[1], "stat") == 0) {
William Lallemand69e96442016-11-19 00:58:54 +01001096 if (*args[2] && *args[3] && *args[4]) {
William Lallemand74c24fb2016-11-21 17:18:36 +01001097 appctx->ctx.stats.flags |= STAT_BOUND;
1098 appctx->ctx.stats.iid = atoi(args[2]);
1099 appctx->ctx.stats.type = atoi(args[3]);
1100 appctx->ctx.stats.sid = atoi(args[4]);
1101 if (strcmp(args[5], "typed") == 0)
1102 appctx->ctx.stats.flags |= STAT_FMT_TYPED;
1103 }
1104 else if (strcmp(args[2], "typed") == 0)
1105 appctx->ctx.stats.flags |= STAT_FMT_TYPED;
1106
1107 appctx->st2 = STAT_ST_INIT;
1108 appctx->st0 = STAT_CLI_O_STAT; // stats_dump_stat_to_buffer
1109 }
1110 else if (strcmp(args[1], "info") == 0) {
1111 if (strcmp(args[2], "typed") == 0)
1112 appctx->ctx.stats.flags |= STAT_FMT_TYPED;
1113 appctx->st2 = STAT_ST_INIT;
1114 appctx->st0 = STAT_CLI_O_INFO; // stats_dump_info_to_buffer
1115 }
1116 else if (strcmp(args[1], "servers") == 0 && strcmp(args[2], "state") == 0) {
1117 appctx->ctx.server_state.iid = 0;
1118 appctx->ctx.server_state.px = NULL;
1119 appctx->ctx.server_state.sv = NULL;
1120
1121 /* check if a backend name has been provided */
1122 if (*args[3]) {
1123 /* read server state from local file */
1124 appctx->ctx.server_state.px = proxy_be_by_name(args[3]);
1125
1126 if (!appctx->ctx.server_state.px) {
1127 appctx->ctx.cli.msg = "Can't find backend.\n";
1128 appctx->st0 = STAT_CLI_PRINT;
1129 return 1;
1130 }
1131 appctx->ctx.server_state.iid = appctx->ctx.server_state.px->uuid;
1132 }
1133 appctx->st2 = STAT_ST_INIT;
1134 appctx->st0 = STAT_CLI_O_SERVERS_STATE; // stats_dump_servers_state_to_buffer
1135 return 1;
1136 }
William Lallemand74c24fb2016-11-21 17:18:36 +01001137 else if (strcmp(args[1], "sess") == 0) {
1138 appctx->st2 = STAT_ST_INIT;
1139 if (strm_li(s)->bind_conf->level < ACCESS_LVL_OPER) {
1140 appctx->ctx.cli.msg = stats_permission_denied_msg;
1141 appctx->st0 = STAT_CLI_PRINT;
1142 return 1;
1143 }
1144 if (*args[2] && strcmp(args[2], "all") == 0)
1145 appctx->ctx.sess.target = (void *)-1;
1146 else if (*args[2])
1147 appctx->ctx.sess.target = (void *)strtoul(args[2], NULL, 0);
1148 else
1149 appctx->ctx.sess.target = NULL;
1150 appctx->ctx.sess.section = 0; /* start with stream status */
1151 appctx->ctx.sess.pos = 0;
1152 appctx->st0 = STAT_CLI_O_SESS; // stats_dump_sess_to_buffer
1153 }
1154 else if (strcmp(args[1], "errors") == 0) {
1155 if (strm_li(s)->bind_conf->level < ACCESS_LVL_OPER) {
1156 appctx->ctx.cli.msg = stats_permission_denied_msg;
1157 appctx->st0 = STAT_CLI_PRINT;
1158 return 1;
1159 }
1160 if (*args[2])
1161 appctx->ctx.errors.iid = atoi(args[2]);
1162 else
1163 appctx->ctx.errors.iid = -1;
1164 appctx->ctx.errors.px = NULL;
1165 appctx->st2 = STAT_ST_INIT;
1166 appctx->st0 = STAT_CLI_O_ERR; // stats_dump_errors_to_buffer
1167 }
1168 else if (strcmp(args[1], "table") == 0) {
1169 stats_sock_table_request(si, args, STAT_CLI_O_TAB);
1170 }
William Lallemand74c24fb2016-11-21 17:18:36 +01001171 else { /* neither "stat" nor "info" nor "sess" nor "errors" nor "table" */
1172 return 0;
1173 }
1174 }
1175 else if (strcmp(args[0], "clear") == 0) {
1176 if (strcmp(args[1], "counters") == 0) {
1177 struct proxy *px;
1178 struct server *sv;
1179 struct listener *li;
1180 int clrall = 0;
1181
1182 if (strcmp(args[2], "all") == 0)
1183 clrall = 1;
1184
1185 /* check permissions */
1186 if (strm_li(s)->bind_conf->level < ACCESS_LVL_OPER ||
1187 (clrall && strm_li(s)->bind_conf->level < ACCESS_LVL_ADMIN)) {
1188 appctx->ctx.cli.msg = stats_permission_denied_msg;
1189 appctx->st0 = STAT_CLI_PRINT;
1190 return 1;
1191 }
1192
1193 for (px = proxy; px; px = px->next) {
1194 if (clrall) {
1195 memset(&px->be_counters, 0, sizeof(px->be_counters));
1196 memset(&px->fe_counters, 0, sizeof(px->fe_counters));
1197 }
1198 else {
1199 px->be_counters.conn_max = 0;
1200 px->be_counters.p.http.rps_max = 0;
1201 px->be_counters.sps_max = 0;
1202 px->be_counters.cps_max = 0;
1203 px->be_counters.nbpend_max = 0;
1204
1205 px->fe_counters.conn_max = 0;
1206 px->fe_counters.p.http.rps_max = 0;
1207 px->fe_counters.sps_max = 0;
1208 px->fe_counters.cps_max = 0;
1209 px->fe_counters.nbpend_max = 0;
1210 }
1211
1212 for (sv = px->srv; sv; sv = sv->next)
1213 if (clrall)
1214 memset(&sv->counters, 0, sizeof(sv->counters));
1215 else {
1216 sv->counters.cur_sess_max = 0;
1217 sv->counters.nbpend_max = 0;
1218 sv->counters.sps_max = 0;
1219 }
1220
1221 list_for_each_entry(li, &px->conf.listeners, by_fe)
1222 if (li->counters) {
1223 if (clrall)
1224 memset(li->counters, 0, sizeof(*li->counters));
1225 else
1226 li->counters->conn_max = 0;
1227 }
1228 }
1229
1230 global.cps_max = 0;
1231 global.sps_max = 0;
1232 return 1;
1233 }
1234 else if (strcmp(args[1], "table") == 0) {
1235 stats_sock_table_request(si, args, STAT_CLI_O_CLR);
1236 /* end of processing */
1237 return 1;
1238 }
William Lallemand74c24fb2016-11-21 17:18:36 +01001239 else {
1240 /* unknown "clear" argument */
1241 return 0;
1242 }
1243 }
1244 else if (strcmp(args[0], "get") == 0) {
1245 if (strcmp(args[1], "weight") == 0) {
1246 struct proxy *px;
1247 struct server *sv;
1248
1249 /* split "backend/server" and make <line> point to server */
1250 for (line = args[2]; *line; line++)
1251 if (*line == '/') {
1252 *line++ = '\0';
1253 break;
1254 }
1255
1256 if (!*line) {
1257 appctx->ctx.cli.msg = "Require 'backend/server'.\n";
1258 appctx->st0 = STAT_CLI_PRINT;
1259 return 1;
1260 }
1261
1262 if (!get_backend_server(args[2], line, &px, &sv)) {
1263 appctx->ctx.cli.msg = px ? "No such server.\n" : "No such backend.\n";
1264 appctx->st0 = STAT_CLI_PRINT;
1265 return 1;
1266 }
1267
1268 /* return server's effective weight at the moment */
1269 snprintf(trash.str, trash.size, "%d (initial %d)\n", sv->uweight, sv->iweight);
1270 if (bi_putstr(si_ic(si), trash.str) == -1)
1271 si_applet_cant_put(si);
1272
1273 return 1;
1274 }
William Lallemand74c24fb2016-11-21 17:18:36 +01001275 else { /* not "get weight" */
1276 return 0;
1277 }
1278 }
1279 else if (strcmp(args[0], "set") == 0) {
1280 if (strcmp(args[1], "weight") == 0) {
1281 struct server *sv;
1282 const char *warning;
1283
1284 sv = expect_server_admin(s, si, args[2]);
1285 if (!sv)
1286 return 1;
1287
1288 warning = server_parse_weight_change_request(sv, args[3]);
1289 if (warning) {
1290 appctx->ctx.cli.msg = warning;
1291 appctx->st0 = STAT_CLI_PRINT;
1292 }
1293 return 1;
1294 }
William Lallemand74c24fb2016-11-21 17:18:36 +01001295 else if (strcmp(args[1], "timeout") == 0) {
1296 if (strcmp(args[2], "cli") == 0) {
1297 unsigned timeout;
1298 const char *res;
1299
1300 if (!*args[3]) {
1301 appctx->ctx.cli.msg = "Expects an integer value.\n";
1302 appctx->st0 = STAT_CLI_PRINT;
1303 return 1;
1304 }
1305
1306 res = parse_time_err(args[3], &timeout, TIME_UNIT_S);
1307 if (res || timeout < 1) {
1308 appctx->ctx.cli.msg = "Invalid timeout value.\n";
1309 appctx->st0 = STAT_CLI_PRINT;
1310 return 1;
1311 }
1312
1313 s->req.rto = s->res.wto = 1 + MS_TO_TICKS(timeout*1000);
1314 task_wakeup(s->task, TASK_WOKEN_MSG); // recompute timeouts
1315 return 1;
1316 }
1317 else {
1318 appctx->ctx.cli.msg = "'set timeout' only supports 'cli'.\n";
1319 appctx->st0 = STAT_CLI_PRINT;
1320 return 1;
1321 }
1322 }
1323 else if (strcmp(args[1], "maxconn") == 0) {
1324 if (strcmp(args[2], "frontend") == 0) {
1325 struct proxy *px;
1326 struct listener *l;
1327 int v;
1328
1329 px = expect_frontend_admin(s, si, args[3]);
1330 if (!px)
1331 return 1;
1332
1333 if (!*args[4]) {
1334 appctx->ctx.cli.msg = "Integer value expected.\n";
1335 appctx->st0 = STAT_CLI_PRINT;
1336 return 1;
1337 }
1338
1339 v = atoi(args[4]);
1340 if (v < 0) {
1341 appctx->ctx.cli.msg = "Value out of range.\n";
1342 appctx->st0 = STAT_CLI_PRINT;
1343 return 1;
1344 }
1345
1346 /* OK, the value is fine, so we assign it to the proxy and to all of
1347 * its listeners. The blocked ones will be dequeued.
1348 */
1349 px->maxconn = v;
1350 list_for_each_entry(l, &px->conf.listeners, by_fe) {
1351 l->maxconn = v;
1352 if (l->state == LI_FULL)
1353 resume_listener(l);
1354 }
1355
1356 if (px->maxconn > px->feconn && !LIST_ISEMPTY(&px->listener_queue))
1357 dequeue_all_listeners(&px->listener_queue);
1358
1359 return 1;
1360 }
1361 else if (strcmp(args[2], "server") == 0) {
1362 struct server *sv;
1363 const char *warning;
1364
1365 sv = expect_server_admin(s, si, args[3]);
1366 if (!sv)
1367 return 1;
1368
1369 warning = server_parse_maxconn_change_request(sv, args[4]);
1370 if (warning) {
1371 appctx->ctx.cli.msg = warning;
1372 appctx->st0 = STAT_CLI_PRINT;
1373 }
1374
1375 return 1;
1376 }
1377 else if (strcmp(args[2], "global") == 0) {
1378 int v;
1379
1380 if (strm_li(s)->bind_conf->level < ACCESS_LVL_ADMIN) {
1381 appctx->ctx.cli.msg = stats_permission_denied_msg;
1382 appctx->st0 = STAT_CLI_PRINT;
1383 return 1;
1384 }
1385
1386 if (!*args[3]) {
1387 appctx->ctx.cli.msg = "Expects an integer value.\n";
1388 appctx->st0 = STAT_CLI_PRINT;
1389 return 1;
1390 }
1391
1392 v = atoi(args[3]);
1393 if (v > global.hardmaxconn) {
1394 appctx->ctx.cli.msg = "Value out of range.\n";
1395 appctx->st0 = STAT_CLI_PRINT;
1396 return 1;
1397 }
1398
1399 /* check for unlimited values */
1400 if (v <= 0)
1401 v = global.hardmaxconn;
1402
1403 global.maxconn = v;
1404
1405 /* Dequeues all of the listeners waiting for a resource */
1406 if (!LIST_ISEMPTY(&global_listener_queue))
1407 dequeue_all_listeners(&global_listener_queue);
1408
1409 return 1;
1410 }
1411 else {
1412 appctx->ctx.cli.msg = "'set maxconn' only supports 'frontend', 'server', and 'global'.\n";
1413 appctx->st0 = STAT_CLI_PRINT;
1414 return 1;
1415 }
1416 }
1417 else if (strcmp(args[1], "rate-limit") == 0) {
1418 if (strcmp(args[2], "connections") == 0) {
1419 if (strcmp(args[3], "global") == 0) {
1420 int v;
1421
1422 if (strm_li(s)->bind_conf->level < ACCESS_LVL_ADMIN) {
1423 appctx->ctx.cli.msg = stats_permission_denied_msg;
1424 appctx->st0 = STAT_CLI_PRINT;
1425 return 1;
1426 }
1427
1428 if (!*args[4]) {
1429 appctx->ctx.cli.msg = "Expects an integer value.\n";
1430 appctx->st0 = STAT_CLI_PRINT;
1431 return 1;
1432 }
1433
1434 v = atoi(args[4]);
1435 if (v < 0) {
1436 appctx->ctx.cli.msg = "Value out of range.\n";
1437 appctx->st0 = STAT_CLI_PRINT;
1438 return 1;
1439 }
1440
1441 global.cps_lim = v;
1442
1443 /* Dequeues all of the listeners waiting for a resource */
1444 if (!LIST_ISEMPTY(&global_listener_queue))
1445 dequeue_all_listeners(&global_listener_queue);
1446
1447 return 1;
1448 }
1449 else {
1450 appctx->ctx.cli.msg = "'set rate-limit connections' only supports 'global'.\n";
1451 appctx->st0 = STAT_CLI_PRINT;
1452 return 1;
1453 }
1454 }
1455 else if (strcmp(args[2], "sessions") == 0) {
1456 if (strcmp(args[3], "global") == 0) {
1457 int v;
1458
1459 if (strm_li(s)->bind_conf->level < ACCESS_LVL_ADMIN) {
1460 appctx->ctx.cli.msg = stats_permission_denied_msg;
1461 appctx->st0 = STAT_CLI_PRINT;
1462 return 1;
1463 }
1464
1465 if (!*args[4]) {
1466 appctx->ctx.cli.msg = "Expects an integer value.\n";
1467 appctx->st0 = STAT_CLI_PRINT;
1468 return 1;
1469 }
1470
1471 v = atoi(args[4]);
1472 if (v < 0) {
1473 appctx->ctx.cli.msg = "Value out of range.\n";
1474 appctx->st0 = STAT_CLI_PRINT;
1475 return 1;
1476 }
1477
1478 global.sps_lim = v;
1479
1480 /* Dequeues all of the listeners waiting for a resource */
1481 if (!LIST_ISEMPTY(&global_listener_queue))
1482 dequeue_all_listeners(&global_listener_queue);
1483
1484 return 1;
1485 }
1486 else {
1487 appctx->ctx.cli.msg = "'set rate-limit sessions' only supports 'global'.\n";
1488 appctx->st0 = STAT_CLI_PRINT;
1489 return 1;
1490 }
1491 }
1492#ifdef USE_OPENSSL
1493 else if (strcmp(args[2], "ssl-sessions") == 0) {
1494 if (strcmp(args[3], "global") == 0) {
1495 int v;
1496
1497 if (strm_li(s)->bind_conf->level < ACCESS_LVL_ADMIN) {
1498 appctx->ctx.cli.msg = stats_permission_denied_msg;
1499 appctx->st0 = STAT_CLI_PRINT;
1500 return 1;
1501 }
1502
1503 if (!*args[4]) {
1504 appctx->ctx.cli.msg = "Expects an integer value.\n";
1505 appctx->st0 = STAT_CLI_PRINT;
1506 return 1;
1507 }
1508
1509 v = atoi(args[4]);
1510 if (v < 0) {
1511 appctx->ctx.cli.msg = "Value out of range.\n";
1512 appctx->st0 = STAT_CLI_PRINT;
1513 return 1;
1514 }
1515
1516 global.ssl_lim = v;
1517
1518 /* Dequeues all of the listeners waiting for a resource */
1519 if (!LIST_ISEMPTY(&global_listener_queue))
1520 dequeue_all_listeners(&global_listener_queue);
1521
1522 return 1;
1523 }
1524 else {
1525 appctx->ctx.cli.msg = "'set rate-limit ssl-sessions' only supports 'global'.\n";
1526 appctx->st0 = STAT_CLI_PRINT;
1527 return 1;
1528 }
1529 }
1530#endif
1531 else if (strcmp(args[2], "http-compression") == 0) {
1532 if (strcmp(args[3], "global") == 0) {
1533 int v;
1534
1535 if (strm_li(s)->bind_conf->level < ACCESS_LVL_ADMIN) {
1536 appctx->ctx.cli.msg = stats_permission_denied_msg;
1537 appctx->st0 = STAT_CLI_PRINT;
1538 return 1;
1539 }
1540
1541 if (!*args[4]) {
1542 appctx->ctx.cli.msg = "Expects a maximum input byte rate in kB/s.\n";
1543 appctx->st0 = STAT_CLI_PRINT;
1544 return 1;
1545 }
1546
1547 v = atoi(args[4]);
1548 global.comp_rate_lim = v * 1024; /* Kilo to bytes. */
1549 }
1550 else {
1551 appctx->ctx.cli.msg = "'set rate-limit http-compression' only supports 'global'.\n";
1552 appctx->st0 = STAT_CLI_PRINT;
1553 return 1;
1554 }
1555 }
1556 else {
1557 appctx->ctx.cli.msg = "'set rate-limit' supports 'connections', 'sessions', 'ssl-sessions', and 'http-compression'.\n";
1558 appctx->st0 = STAT_CLI_PRINT;
1559 return 1;
1560 }
1561 }
1562 else if (strcmp(args[1], "table") == 0) {
1563 stats_sock_table_request(si, args, STAT_CLI_O_SET);
William Lallemand32af2032016-10-29 18:09:35 +02001564 } else { /* unknown "set" parameter */
William Lallemand74c24fb2016-11-21 17:18:36 +01001565 return 0;
1566 }
1567 }
1568 else if (strcmp(args[0], "enable") == 0) {
1569 if (strcmp(args[1], "agent") == 0) {
1570 struct server *sv;
1571
1572 sv = expect_server_admin(s, si, args[2]);
1573 if (!sv)
1574 return 1;
1575
1576 if (!(sv->agent.state & CHK_ST_CONFIGURED)) {
1577 appctx->ctx.cli.msg = "Agent was not configured on this server, cannot enable.\n";
1578 appctx->st0 = STAT_CLI_PRINT;
1579 return 1;
1580 }
1581
1582 sv->agent.state |= CHK_ST_ENABLED;
1583 return 1;
1584 }
1585 else if (strcmp(args[1], "health") == 0) {
1586 struct server *sv;
1587
1588 sv = expect_server_admin(s, si, args[2]);
1589 if (!sv)
1590 return 1;
1591
1592 if (!(sv->check.state & CHK_ST_CONFIGURED)) {
1593 appctx->ctx.cli.msg = "Health checks are not configured on this server, cannot enable.\n";
1594 appctx->st0 = STAT_CLI_PRINT;
1595 return 1;
1596 }
1597
1598 sv->check.state |= CHK_ST_ENABLED;
1599 return 1;
1600 }
1601 else if (strcmp(args[1], "server") == 0) {
1602 struct server *sv;
1603
1604 sv = expect_server_admin(s, si, args[2]);
1605 if (!sv)
1606 return 1;
1607
1608 srv_adm_set_ready(sv);
1609 return 1;
1610 }
1611 else if (strcmp(args[1], "frontend") == 0) {
1612 struct proxy *px;
1613
1614 px = expect_frontend_admin(s, si, args[2]);
1615 if (!px)
1616 return 1;
1617
1618 if (px->state == PR_STSTOPPED) {
1619 appctx->ctx.cli.msg = "Frontend was previously shut down, cannot enable.\n";
1620 appctx->st0 = STAT_CLI_PRINT;
1621 return 1;
1622 }
1623
1624 if (px->state != PR_STPAUSED) {
1625 appctx->ctx.cli.msg = "Frontend is already enabled.\n";
1626 appctx->st0 = STAT_CLI_PRINT;
1627 return 1;
1628 }
1629
1630 if (!resume_proxy(px)) {
1631 appctx->ctx.cli.msg = "Failed to resume frontend, check logs for precise cause (port conflict?).\n";
1632 appctx->st0 = STAT_CLI_PRINT;
1633 return 1;
1634 }
1635 return 1;
1636 }
1637 else { /* unknown "enable" parameter */
1638 appctx->ctx.cli.msg = "'enable' only supports 'agent', 'frontend', 'health', and 'server'.\n";
1639 appctx->st0 = STAT_CLI_PRINT;
1640 return 1;
1641 }
1642 }
1643 else if (strcmp(args[0], "disable") == 0) {
1644 if (strcmp(args[1], "agent") == 0) {
1645 struct server *sv;
1646
1647 sv = expect_server_admin(s, si, args[2]);
1648 if (!sv)
1649 return 1;
1650
1651 sv->agent.state &= ~CHK_ST_ENABLED;
1652 return 1;
1653 }
1654 else if (strcmp(args[1], "health") == 0) {
1655 struct server *sv;
1656
1657 sv = expect_server_admin(s, si, args[2]);
1658 if (!sv)
1659 return 1;
1660
1661 sv->check.state &= ~CHK_ST_ENABLED;
1662 return 1;
1663 }
1664 else if (strcmp(args[1], "server") == 0) {
1665 struct server *sv;
1666
1667 sv = expect_server_admin(s, si, args[2]);
1668 if (!sv)
1669 return 1;
1670
1671 srv_adm_set_maint(sv);
1672 return 1;
1673 }
1674 else if (strcmp(args[1], "frontend") == 0) {
1675 struct proxy *px;
1676
1677 px = expect_frontend_admin(s, si, args[2]);
1678 if (!px)
1679 return 1;
1680
1681 if (px->state == PR_STSTOPPED) {
1682 appctx->ctx.cli.msg = "Frontend was previously shut down, cannot disable.\n";
1683 appctx->st0 = STAT_CLI_PRINT;
1684 return 1;
1685 }
1686
1687 if (px->state == PR_STPAUSED) {
1688 appctx->ctx.cli.msg = "Frontend is already disabled.\n";
1689 appctx->st0 = STAT_CLI_PRINT;
1690 return 1;
1691 }
1692
1693 if (!pause_proxy(px)) {
1694 appctx->ctx.cli.msg = "Failed to pause frontend, check logs for precise cause.\n";
1695 appctx->st0 = STAT_CLI_PRINT;
1696 return 1;
1697 }
1698 return 1;
1699 }
1700 else { /* unknown "disable" parameter */
1701 appctx->ctx.cli.msg = "'disable' only supports 'agent', 'frontend', 'health', and 'server'.\n";
1702 appctx->st0 = STAT_CLI_PRINT;
1703 return 1;
1704 }
1705 }
1706 else if (strcmp(args[0], "shutdown") == 0) {
1707 if (strcmp(args[1], "frontend") == 0) {
1708 struct proxy *px;
1709
1710 px = expect_frontend_admin(s, si, args[2]);
1711 if (!px)
1712 return 1;
1713
1714 if (px->state == PR_STSTOPPED) {
1715 appctx->ctx.cli.msg = "Frontend was already shut down.\n";
1716 appctx->st0 = STAT_CLI_PRINT;
1717 return 1;
1718 }
1719
1720 Warning("Proxy %s stopped (FE: %lld conns, BE: %lld conns).\n",
1721 px->id, px->fe_counters.cum_conn, px->be_counters.cum_conn);
1722 send_log(px, LOG_WARNING, "Proxy %s stopped (FE: %lld conns, BE: %lld conns).\n",
1723 px->id, px->fe_counters.cum_conn, px->be_counters.cum_conn);
1724 stop_proxy(px);
1725 return 1;
1726 }
1727 else if (strcmp(args[1], "session") == 0) {
1728 struct stream *sess, *ptr;
1729
1730 if (strm_li(s)->bind_conf->level < ACCESS_LVL_ADMIN) {
1731 appctx->ctx.cli.msg = stats_permission_denied_msg;
1732 appctx->st0 = STAT_CLI_PRINT;
1733 return 1;
1734 }
1735
1736 if (!*args[2]) {
1737 appctx->ctx.cli.msg = "Session pointer expected (use 'show sess').\n";
1738 appctx->st0 = STAT_CLI_PRINT;
1739 return 1;
1740 }
1741
1742 ptr = (void *)strtoul(args[2], NULL, 0);
1743
1744 /* first, look for the requested stream in the stream table */
1745 list_for_each_entry(sess, &streams, list) {
1746 if (sess == ptr)
1747 break;
1748 }
1749
1750 /* do we have the stream ? */
1751 if (sess != ptr) {
1752 appctx->ctx.cli.msg = "No such session (use 'show sess').\n";
1753 appctx->st0 = STAT_CLI_PRINT;
1754 return 1;
1755 }
1756
1757 stream_shutdown(sess, SF_ERR_KILLED);
1758 return 1;
1759 }
1760 else if (strcmp(args[1], "sessions") == 0) {
1761 if (strcmp(args[2], "server") == 0) {
1762 struct server *sv;
1763 struct stream *sess, *sess_bck;
1764
1765 sv = expect_server_admin(s, si, args[3]);
1766 if (!sv)
1767 return 1;
1768
1769 /* kill all the stream that are on this server */
1770 list_for_each_entry_safe(sess, sess_bck, &sv->actconns, by_srv)
1771 if (sess->srv_conn == sv)
1772 stream_shutdown(sess, SF_ERR_KILLED);
1773
1774 return 1;
1775 }
1776 else {
1777 appctx->ctx.cli.msg = "'shutdown sessions' only supports 'server'.\n";
1778 appctx->st0 = STAT_CLI_PRINT;
1779 return 1;
1780 }
1781 }
1782 else { /* unknown "disable" parameter */
1783 appctx->ctx.cli.msg = "'shutdown' only supports 'frontend', 'session' and 'sessions'.\n";
1784 appctx->st0 = STAT_CLI_PRINT;
1785 return 1;
1786 }
1787 }
William Lallemand74c24fb2016-11-21 17:18:36 +01001788 else { /* not "show" nor "clear" nor "get" nor "set" nor "enable" nor "disable" */
1789 return 0;
1790 }
1791 return 1;
1792}
1793
1794/* This I/O handler runs as an applet embedded in a stream interface. It is
1795 * used to processes I/O from/to the stats unix socket. The system relies on a
1796 * state machine handling requests and various responses. We read a request,
1797 * then we process it and send the response, and we possibly display a prompt.
1798 * Then we can read again. The state is stored in appctx->st0 and is one of the
1799 * STAT_CLI_* constants. appctx->st1 is used to indicate whether prompt is enabled
1800 * or not.
1801 */
1802static void cli_io_handler(struct appctx *appctx)
1803{
1804 struct stream_interface *si = appctx->owner;
1805 struct channel *req = si_oc(si);
1806 struct channel *res = si_ic(si);
1807 int reql;
1808 int len;
1809
1810 if (unlikely(si->state == SI_ST_DIS || si->state == SI_ST_CLO))
1811 goto out;
1812
1813 while (1) {
1814 if (appctx->st0 == STAT_CLI_INIT) {
1815 /* Stats output not initialized yet */
1816 memset(&appctx->ctx.stats, 0, sizeof(appctx->ctx.stats));
1817 appctx->st0 = STAT_CLI_GETREQ;
1818 }
1819 else if (appctx->st0 == STAT_CLI_END) {
1820 /* Let's close for real now. We just close the request
1821 * side, the conditions below will complete if needed.
1822 */
1823 si_shutw(si);
1824 break;
1825 }
1826 else if (appctx->st0 == STAT_CLI_GETREQ) {
1827 /* ensure we have some output room left in the event we
1828 * would want to return some info right after parsing.
1829 */
1830 if (buffer_almost_full(si_ib(si))) {
1831 si_applet_cant_put(si);
1832 break;
1833 }
1834
1835 reql = bo_getline(si_oc(si), trash.str, trash.size);
1836 if (reql <= 0) { /* closed or EOL not found */
1837 if (reql == 0)
1838 break;
1839 appctx->st0 = STAT_CLI_END;
1840 continue;
1841 }
1842
1843 /* seek for a possible unescaped semi-colon. If we find
1844 * one, we replace it with an LF and skip only this part.
1845 */
1846 for (len = 0; len < reql; len++) {
1847 if (trash.str[len] == '\\') {
1848 len++;
1849 continue;
1850 }
1851 if (trash.str[len] == ';') {
1852 trash.str[len] = '\n';
1853 reql = len + 1;
1854 break;
1855 }
1856 }
1857
1858 /* now it is time to check that we have a full line,
1859 * remove the trailing \n and possibly \r, then cut the
1860 * line.
1861 */
1862 len = reql - 1;
1863 if (trash.str[len] != '\n') {
1864 appctx->st0 = STAT_CLI_END;
1865 continue;
1866 }
1867
1868 if (len && trash.str[len-1] == '\r')
1869 len--;
1870
1871 trash.str[len] = '\0';
1872
1873 appctx->st0 = STAT_CLI_PROMPT;
1874 if (len) {
1875 if (strcmp(trash.str, "quit") == 0) {
1876 appctx->st0 = STAT_CLI_END;
1877 continue;
1878 }
1879 else if (strcmp(trash.str, "prompt") == 0)
1880 appctx->st1 = !appctx->st1;
1881 else if (strcmp(trash.str, "help") == 0 ||
1882 !stats_sock_parse_request(si, trash.str)) {
1883 cli_gen_usage_msg();
1884 if (dynamic_usage_msg)
1885 appctx->ctx.cli.msg = dynamic_usage_msg;
1886 else
1887 appctx->ctx.cli.msg = stats_sock_usage_msg;
1888 appctx->st0 = STAT_CLI_PRINT;
1889 }
1890 /* NB: stats_sock_parse_request() may have put
1891 * another STAT_CLI_O_* into appctx->st0.
1892 */
1893 }
1894 else if (!appctx->st1) {
1895 /* if prompt is disabled, print help on empty lines,
1896 * so that the user at least knows how to enable
1897 * prompt and find help.
1898 */
1899 cli_gen_usage_msg();
1900 if (dynamic_usage_msg)
1901 appctx->ctx.cli.msg = dynamic_usage_msg;
1902 else
1903 appctx->ctx.cli.msg = stats_sock_usage_msg;
1904 appctx->st0 = STAT_CLI_PRINT;
1905 }
1906
1907 /* re-adjust req buffer */
1908 bo_skip(si_oc(si), reql);
1909 req->flags |= CF_READ_DONTWAIT; /* we plan to read small requests */
1910 }
1911 else { /* output functions */
1912 switch (appctx->st0) {
1913 case STAT_CLI_PROMPT:
1914 break;
1915 case STAT_CLI_PRINT:
1916 if (bi_putstr(si_ic(si), appctx->ctx.cli.msg) != -1)
1917 appctx->st0 = STAT_CLI_PROMPT;
1918 else
1919 si_applet_cant_put(si);
1920 break;
1921 case STAT_CLI_PRINT_FREE:
1922 if (bi_putstr(si_ic(si), appctx->ctx.cli.err) != -1) {
1923 free(appctx->ctx.cli.err);
1924 appctx->st0 = STAT_CLI_PROMPT;
1925 }
1926 else
1927 si_applet_cant_put(si);
1928 break;
1929 case STAT_CLI_O_BACKEND:
1930 if (stats_dump_backend_to_buffer(si))
1931 appctx->st0 = STAT_CLI_PROMPT;
1932 break;
1933 case STAT_CLI_O_INFO:
1934 if (stats_dump_info_to_buffer(si))
1935 appctx->st0 = STAT_CLI_PROMPT;
1936 break;
1937 case STAT_CLI_O_SERVERS_STATE:
1938 if (stats_dump_servers_state_to_buffer(si))
1939 appctx->st0 = STAT_CLI_PROMPT;
1940 break;
1941 case STAT_CLI_O_STAT:
1942 if (stats_dump_stat_to_buffer(si, NULL))
1943 appctx->st0 = STAT_CLI_PROMPT;
1944 break;
William Lallemand74c24fb2016-11-21 17:18:36 +01001945 case STAT_CLI_O_SESS:
1946 if (stats_dump_sess_to_buffer(si))
1947 appctx->st0 = STAT_CLI_PROMPT;
1948 break;
1949 case STAT_CLI_O_ERR: /* errors dump */
1950 if (stats_dump_errors_to_buffer(si))
1951 appctx->st0 = STAT_CLI_PROMPT;
1952 break;
1953 case STAT_CLI_O_TAB:
1954 case STAT_CLI_O_CLR:
1955 if (stats_table_request(si, appctx->st0))
1956 appctx->st0 = STAT_CLI_PROMPT;
1957 break;
William Lallemand74c24fb2016-11-21 17:18:36 +01001958 case STAT_CLI_O_ENV: /* environment dump */
1959 if (stats_dump_env_to_buffer(si))
1960 appctx->st0 = STAT_CLI_PROMPT;
1961 break;
1962 case STAT_CLI_O_CUSTOM: /* use custom pointer */
1963 if (appctx->io_handler)
1964 if (appctx->io_handler(appctx)) {
1965 appctx->st0 = STAT_CLI_PROMPT;
1966 if (appctx->io_release) {
1967 appctx->io_release(appctx);
1968 appctx->io_release = NULL;
1969 }
1970 }
1971 break;
1972 default: /* abnormal state */
1973 si->flags |= SI_FL_ERR;
1974 break;
1975 }
1976
1977 /* The post-command prompt is either LF alone or LF + '> ' in interactive mode */
1978 if (appctx->st0 == STAT_CLI_PROMPT) {
1979 if (bi_putstr(si_ic(si), appctx->st1 ? "\n> " : "\n") != -1)
1980 appctx->st0 = STAT_CLI_GETREQ;
1981 else
1982 si_applet_cant_put(si);
1983 }
1984
1985 /* If the output functions are still there, it means they require more room. */
1986 if (appctx->st0 >= STAT_CLI_OUTPUT)
1987 break;
1988
1989 /* Now we close the output if one of the writers did so,
1990 * or if we're not in interactive mode and the request
1991 * buffer is empty. This still allows pipelined requests
1992 * to be sent in non-interactive mode.
1993 */
1994 if ((res->flags & (CF_SHUTW|CF_SHUTW_NOW)) || (!appctx->st1 && !req->buf->o)) {
1995 appctx->st0 = STAT_CLI_END;
1996 continue;
1997 }
1998
1999 /* switch state back to GETREQ to read next requests */
2000 appctx->st0 = STAT_CLI_GETREQ;
2001 }
2002 }
2003
2004 if ((res->flags & CF_SHUTR) && (si->state == SI_ST_EST)) {
2005 DPRINTF(stderr, "%s@%d: si to buf closed. req=%08x, res=%08x, st=%d\n",
2006 __FUNCTION__, __LINE__, req->flags, res->flags, si->state);
2007 /* Other side has closed, let's abort if we have no more processing to do
2008 * and nothing more to consume. This is comparable to a broken pipe, so
2009 * we forward the close to the request side so that it flows upstream to
2010 * the client.
2011 */
2012 si_shutw(si);
2013 }
2014
2015 if ((req->flags & CF_SHUTW) && (si->state == SI_ST_EST) && (appctx->st0 < STAT_CLI_OUTPUT)) {
2016 DPRINTF(stderr, "%s@%d: buf to si closed. req=%08x, res=%08x, st=%d\n",
2017 __FUNCTION__, __LINE__, req->flags, res->flags, si->state);
2018 /* We have no more processing to do, and nothing more to send, and
2019 * the client side has closed. So we'll forward this state downstream
2020 * on the response buffer.
2021 */
2022 si_shutr(si);
2023 res->flags |= CF_READ_NULL;
2024 }
2025
2026 out:
2027 DPRINTF(stderr, "%s@%d: st=%d, rqf=%x, rpf=%x, rqh=%d, rqs=%d, rh=%d, rs=%d\n",
2028 __FUNCTION__, __LINE__,
2029 si->state, req->flags, res->flags, req->buf->i, req->buf->o, res->buf->i, res->buf->o);
2030}
2031
2032/* Dump all fields from <info> into <out> using the "show info" format (name: value) */
2033static int stats_dump_info_fields(struct chunk *out, const struct field *info)
2034{
2035 int field;
2036
2037 for (field = 0; field < INF_TOTAL_FIELDS; field++) {
2038 if (!field_format(info, field))
2039 continue;
2040
2041 if (!chunk_appendf(out, "%s: ", info_field_names[field]))
2042 return 0;
2043 if (!stats_emit_raw_data_field(out, &info[field]))
2044 return 0;
2045 if (!chunk_strcat(out, "\n"))
2046 return 0;
2047 }
2048 return 1;
2049}
2050
2051/* Dump all fields from <info> into <out> using the "show info typed" format */
2052static int stats_dump_typed_info_fields(struct chunk *out, const struct field *info)
2053{
2054 int field;
2055
2056 for (field = 0; field < INF_TOTAL_FIELDS; field++) {
2057 if (!field_format(info, field))
2058 continue;
2059
2060 if (!chunk_appendf(out, "%d.%s.%u:", field, info_field_names[field], info[INF_PROCESS_NUM].u.u32))
2061 return 0;
2062 if (!stats_emit_field_tags(out, &info[field], ':'))
2063 return 0;
2064 if (!stats_emit_typed_data_field(out, &info[field]))
2065 return 0;
2066 if (!chunk_strcat(out, "\n"))
2067 return 0;
2068 }
2069 return 1;
2070}
2071
2072/* Fill <info> with HAProxy global info. <info> is preallocated
2073 * array of length <len>. The length of the aray must be
2074 * INF_TOTAL_FIELDS. If this length is less then this value, the
2075 * function returns 0, otherwise, it returns 1.
2076 */
2077int stats_fill_info(struct field *info, int len)
2078{
2079 unsigned int up = (now.tv_sec - start_date.tv_sec);
2080 struct chunk *out = get_trash_chunk();
2081
2082#ifdef USE_OPENSSL
2083 int ssl_sess_rate = read_freq_ctr(&global.ssl_per_sec);
2084 int ssl_key_rate = read_freq_ctr(&global.ssl_fe_keys_per_sec);
2085 int ssl_reuse = 0;
2086
2087 if (ssl_key_rate < ssl_sess_rate) {
2088 /* count the ssl reuse ratio and avoid overflows in both directions */
2089 ssl_reuse = 100 - (100 * ssl_key_rate + (ssl_sess_rate - 1) / 2) / ssl_sess_rate;
2090 }
2091#endif
2092
2093 if (len < INF_TOTAL_FIELDS)
2094 return 0;
2095
2096 chunk_reset(out);
2097 memset(info, 0, sizeof(*info) * len);
2098
2099 info[INF_NAME] = mkf_str(FO_PRODUCT|FN_OUTPUT|FS_SERVICE, PRODUCT_NAME);
2100 info[INF_VERSION] = mkf_str(FO_PRODUCT|FN_OUTPUT|FS_SERVICE, HAPROXY_VERSION);
2101 info[INF_RELEASE_DATE] = mkf_str(FO_PRODUCT|FN_OUTPUT|FS_SERVICE, HAPROXY_DATE);
2102
2103 info[INF_NBPROC] = mkf_u32(FO_CONFIG|FS_SERVICE, global.nbproc);
2104 info[INF_PROCESS_NUM] = mkf_u32(FO_KEY, relative_pid);
2105 info[INF_PID] = mkf_u32(FO_STATUS, pid);
2106
2107 info[INF_UPTIME] = mkf_str(FN_DURATION, chunk_newstr(out));
2108 chunk_appendf(out, "%ud %uh%02um%02us", up / 86400, (up % 86400) / 3600, (up % 3600) / 60, (up % 60));
2109
2110 info[INF_UPTIME_SEC] = mkf_u32(FN_DURATION, up);
2111 info[INF_MEMMAX_MB] = mkf_u32(FO_CONFIG|FN_LIMIT, global.rlimit_memmax);
2112 info[INF_POOL_ALLOC_MB] = mkf_u32(0, (unsigned)(pool_total_allocated() / 1048576L));
2113 info[INF_POOL_USED_MB] = mkf_u32(0, (unsigned)(pool_total_used() / 1048576L));
2114 info[INF_POOL_FAILED] = mkf_u32(FN_COUNTER, pool_total_failures());
2115 info[INF_ULIMIT_N] = mkf_u32(FO_CONFIG|FN_LIMIT, global.rlimit_nofile);
2116 info[INF_MAXSOCK] = mkf_u32(FO_CONFIG|FN_LIMIT, global.maxsock);
2117 info[INF_MAXCONN] = mkf_u32(FO_CONFIG|FN_LIMIT, global.maxconn);
2118 info[INF_HARD_MAXCONN] = mkf_u32(FO_CONFIG|FN_LIMIT, global.hardmaxconn);
2119 info[INF_CURR_CONN] = mkf_u32(0, actconn);
2120 info[INF_CUM_CONN] = mkf_u32(FN_COUNTER, totalconn);
2121 info[INF_CUM_REQ] = mkf_u32(FN_COUNTER, global.req_count);
2122#ifdef USE_OPENSSL
2123 info[INF_MAX_SSL_CONNS] = mkf_u32(FN_MAX, global.maxsslconn);
2124 info[INF_CURR_SSL_CONNS] = mkf_u32(0, sslconns);
2125 info[INF_CUM_SSL_CONNS] = mkf_u32(FN_COUNTER, totalsslconns);
2126#endif
2127 info[INF_MAXPIPES] = mkf_u32(FO_CONFIG|FN_LIMIT, global.maxpipes);
2128 info[INF_PIPES_USED] = mkf_u32(0, pipes_used);
2129 info[INF_PIPES_FREE] = mkf_u32(0, pipes_free);
2130 info[INF_CONN_RATE] = mkf_u32(FN_RATE, read_freq_ctr(&global.conn_per_sec));
2131 info[INF_CONN_RATE_LIMIT] = mkf_u32(FO_CONFIG|FN_LIMIT, global.cps_lim);
2132 info[INF_MAX_CONN_RATE] = mkf_u32(FN_MAX, global.cps_max);
2133 info[INF_SESS_RATE] = mkf_u32(FN_RATE, read_freq_ctr(&global.sess_per_sec));
2134 info[INF_SESS_RATE_LIMIT] = mkf_u32(FO_CONFIG|FN_LIMIT, global.sps_lim);
2135 info[INF_MAX_SESS_RATE] = mkf_u32(FN_RATE, global.sps_max);
2136
2137#ifdef USE_OPENSSL
2138 info[INF_SSL_RATE] = mkf_u32(FN_RATE, ssl_sess_rate);
2139 info[INF_SSL_RATE_LIMIT] = mkf_u32(FO_CONFIG|FN_LIMIT, global.ssl_lim);
2140 info[INF_MAX_SSL_RATE] = mkf_u32(FN_MAX, global.ssl_max);
2141 info[INF_SSL_FRONTEND_KEY_RATE] = mkf_u32(0, ssl_key_rate);
2142 info[INF_SSL_FRONTEND_MAX_KEY_RATE] = mkf_u32(FN_MAX, global.ssl_fe_keys_max);
2143 info[INF_SSL_FRONTEND_SESSION_REUSE_PCT] = mkf_u32(0, ssl_reuse);
2144 info[INF_SSL_BACKEND_KEY_RATE] = mkf_u32(FN_RATE, read_freq_ctr(&global.ssl_be_keys_per_sec));
2145 info[INF_SSL_BACKEND_MAX_KEY_RATE] = mkf_u32(FN_MAX, global.ssl_be_keys_max);
2146 info[INF_SSL_CACHE_LOOKUPS] = mkf_u32(FN_COUNTER, global.shctx_lookups);
2147 info[INF_SSL_CACHE_MISSES] = mkf_u32(FN_COUNTER, global.shctx_misses);
2148#endif
2149 info[INF_COMPRESS_BPS_IN] = mkf_u32(FN_RATE, read_freq_ctr(&global.comp_bps_in));
2150 info[INF_COMPRESS_BPS_OUT] = mkf_u32(FN_RATE, read_freq_ctr(&global.comp_bps_out));
2151 info[INF_COMPRESS_BPS_RATE_LIM] = mkf_u32(FO_CONFIG|FN_LIMIT, global.comp_rate_lim);
2152#ifdef USE_ZLIB
2153 info[INF_ZLIB_MEM_USAGE] = mkf_u32(0, zlib_used_memory);
2154 info[INF_MAX_ZLIB_MEM_USAGE] = mkf_u32(FO_CONFIG|FN_LIMIT, global.maxzlibmem);
2155#endif
2156 info[INF_TASKS] = mkf_u32(0, nb_tasks_cur);
2157 info[INF_RUN_QUEUE] = mkf_u32(0, run_queue_cur);
2158 info[INF_IDLE_PCT] = mkf_u32(FN_AVG, idle_pct);
2159 info[INF_NODE] = mkf_str(FO_CONFIG|FN_OUTPUT|FS_SERVICE, global.node);
2160 if (global.desc)
2161 info[INF_DESCRIPTION] = mkf_str(FO_CONFIG|FN_OUTPUT|FS_SERVICE, global.desc);
2162
2163 return 1;
2164}
2165
2166/* This function dumps information onto the stream interface's read buffer.
2167 * It returns 0 as long as it does not complete, non-zero upon completion.
2168 * No state is used.
2169 */
2170static int stats_dump_info_to_buffer(struct stream_interface *si)
2171{
2172 struct appctx *appctx = __objt_appctx(si->end);
2173
2174 if (!stats_fill_info(info, INF_TOTAL_FIELDS))
2175 return 0;
2176
2177 chunk_reset(&trash);
2178
2179 if (appctx->ctx.stats.flags & STAT_FMT_TYPED)
2180 stats_dump_typed_info_fields(&trash, info);
2181 else
2182 stats_dump_info_fields(&trash, info);
2183
2184 if (bi_putchk(si_ic(si), &trash) == -1) {
2185 si_applet_cant_put(si);
2186 return 0;
2187 }
2188
2189 return 1;
2190}
2191
2192/* dumps server state information into <buf> for all the servers found in <backend>
2193 * These information are all the parameters which may change during HAProxy runtime.
2194 * By default, we only export to the last known server state file format.
2195 * These information can be used at next startup to recover same level of server state.
2196 */
2197static int dump_servers_state(struct stream_interface *si, struct chunk *buf)
2198{
2199 struct appctx *appctx = __objt_appctx(si->end);
2200 struct server *srv;
2201 char srv_addr[INET6_ADDRSTRLEN + 1];
2202 time_t srv_time_since_last_change;
2203 int bk_f_forced_id, srv_f_forced_id;
2204
2205
2206 /* we don't want to report any state if the backend is not enabled on this process */
2207 if (appctx->ctx.server_state.px->bind_proc && !(appctx->ctx.server_state.px->bind_proc & (1UL << (relative_pid - 1))))
2208 return 1;
2209
2210 if (!appctx->ctx.server_state.sv)
2211 appctx->ctx.server_state.sv = appctx->ctx.server_state.px->srv;
2212
2213 for (; appctx->ctx.server_state.sv != NULL; appctx->ctx.server_state.sv = srv->next) {
2214 srv = appctx->ctx.server_state.sv;
2215 srv_addr[0] = '\0';
2216
2217 switch (srv->addr.ss_family) {
2218 case AF_INET:
2219 inet_ntop(srv->addr.ss_family, &((struct sockaddr_in *)&srv->addr)->sin_addr,
2220 srv_addr, INET_ADDRSTRLEN + 1);
2221 break;
2222 case AF_INET6:
2223 inet_ntop(srv->addr.ss_family, &((struct sockaddr_in6 *)&srv->addr)->sin6_addr,
2224 srv_addr, INET6_ADDRSTRLEN + 1);
2225 break;
2226 }
2227 srv_time_since_last_change = now.tv_sec - srv->last_change;
2228 bk_f_forced_id = appctx->ctx.server_state.px->options & PR_O_FORCED_ID ? 1 : 0;
2229 srv_f_forced_id = srv->flags & SRV_F_FORCED_ID ? 1 : 0;
2230
2231 chunk_appendf(buf,
2232 "%d %s "
2233 "%d %s %s "
2234 "%d %d %d %d %ld "
2235 "%d %d %d %d %d "
2236 "%d %d"
2237 "\n",
2238 appctx->ctx.server_state.px->uuid, appctx->ctx.server_state.px->id,
2239 srv->puid, srv->id, srv_addr,
2240 srv->state, srv->admin, srv->uweight, srv->iweight, (long int)srv_time_since_last_change,
2241 srv->check.status, srv->check.result, srv->check.health, srv->check.state, srv->agent.state,
2242 bk_f_forced_id, srv_f_forced_id);
2243 if (bi_putchk(si_ic(si), &trash) == -1) {
2244 si_applet_cant_put(si);
2245 return 0;
2246 }
2247 }
2248 return 1;
2249}
2250
2251/* Parses backend list and simply report backend names */
2252static int stats_dump_backend_to_buffer(struct stream_interface *si)
2253{
2254 struct appctx *appctx = __objt_appctx(si->end);
2255 extern struct proxy *proxy;
2256 struct proxy *curproxy;
2257
2258 chunk_reset(&trash);
2259
2260 if (!appctx->ctx.be.px) {
2261 chunk_printf(&trash, "# name\n");
2262 if (bi_putchk(si_ic(si), &trash) == -1) {
2263 si_applet_cant_put(si);
2264 return 0;
2265 }
2266 appctx->ctx.be.px = proxy;
2267 }
2268
2269 for (; appctx->ctx.be.px != NULL; appctx->ctx.be.px = curproxy->next) {
2270 curproxy = appctx->ctx.be.px;
2271
2272 /* looking for backends only */
2273 if (!(curproxy->cap & PR_CAP_BE))
2274 continue;
2275
2276 /* we don't want to list a backend which is bound to this process */
2277 if (curproxy->bind_proc && !(curproxy->bind_proc & (1UL << (relative_pid - 1))))
2278 continue;
2279
2280 chunk_appendf(&trash, "%s\n", curproxy->id);
2281 if (bi_putchk(si_ic(si), &trash) == -1) {
2282 si_applet_cant_put(si);
2283 return 0;
2284 }
2285 }
2286
2287 return 1;
2288}
2289
2290/* Parses backend list or simply use backend name provided by the user to return
2291 * states of servers to stdout.
2292 */
2293static int stats_dump_servers_state_to_buffer(struct stream_interface *si)
2294{
2295 struct appctx *appctx = __objt_appctx(si->end);
2296 extern struct proxy *proxy;
2297 struct proxy *curproxy;
2298
2299 chunk_reset(&trash);
2300
2301 if (appctx->st2 == STAT_ST_INIT) {
2302 if (!appctx->ctx.server_state.px)
2303 appctx->ctx.server_state.px = proxy;
2304 appctx->st2 = STAT_ST_HEAD;
2305 }
2306
2307 if (appctx->st2 == STAT_ST_HEAD) {
2308 chunk_printf(&trash, "%d\n# %s\n", SRV_STATE_FILE_VERSION, SRV_STATE_FILE_FIELD_NAMES);
2309 if (bi_putchk(si_ic(si), &trash) == -1) {
2310 si_applet_cant_put(si);
2311 return 0;
2312 }
2313 appctx->st2 = STAT_ST_INFO;
2314 }
2315
2316 /* STAT_ST_INFO */
2317 for (; appctx->ctx.server_state.px != NULL; appctx->ctx.server_state.px = curproxy->next) {
2318 curproxy = appctx->ctx.server_state.px;
2319 /* servers are only in backends */
2320 if (curproxy->cap & PR_CAP_BE) {
2321 if (!dump_servers_state(si, &trash))
2322 return 0;
2323
2324 if (bi_putchk(si_ic(si), &trash) == -1) {
2325 si_applet_cant_put(si);
2326 return 0;
2327 }
2328 }
2329 /* only the selected proxy is dumped */
2330 if (appctx->ctx.server_state.iid)
2331 break;
2332 }
2333
2334 return 1;
2335}
2336
William Lallemand74c24fb2016-11-21 17:18:36 +01002337static inline const char *get_conn_ctrl_name(const struct connection *conn)
2338{
2339 if (!conn_ctrl_ready(conn))
2340 return "NONE";
2341 return conn->ctrl->name;
2342}
2343
2344static inline const char *get_conn_xprt_name(const struct connection *conn)
2345{
2346 static char ptr[19];
2347
2348 if (!conn_xprt_ready(conn))
2349 return "NONE";
2350
2351 if (conn->xprt == &raw_sock)
2352 return "RAW";
2353
2354#ifdef USE_OPENSSL
2355 if (conn->xprt == &ssl_sock)
2356 return "SSL";
2357#endif
2358 snprintf(ptr, sizeof(ptr), "%p", conn->xprt);
2359 return ptr;
2360}
2361
2362static inline const char *get_conn_data_name(const struct connection *conn)
2363{
2364 static char ptr[19];
2365
2366 if (!conn->data)
2367 return "NONE";
2368
2369 if (conn->data == &sess_conn_cb)
2370 return "SESS";
2371
2372 if (conn->data == &si_conn_cb)
2373 return "STRM";
2374
2375 if (conn->data == &check_conn_cb)
2376 return "CHCK";
2377
2378 snprintf(ptr, sizeof(ptr), "%p", conn->data);
2379 return ptr;
2380}
2381
2382/* This function dumps a complete stream state onto the stream interface's
2383 * read buffer. The stream has to be set in sess->target. It returns
2384 * 0 if the output buffer is full and it needs to be called again, otherwise
2385 * non-zero. It is designed to be called from stats_dump_sess_to_buffer() below.
2386 */
2387static int stats_dump_full_sess_to_buffer(struct stream_interface *si, struct stream *sess)
2388{
2389 struct appctx *appctx = __objt_appctx(si->end);
2390 struct tm tm;
2391 extern const char *monthname[12];
2392 char pn[INET6_ADDRSTRLEN];
2393 struct connection *conn;
2394 struct appctx *tmpctx;
2395
2396 chunk_reset(&trash);
2397
2398 if (appctx->ctx.sess.section > 0 && appctx->ctx.sess.uid != sess->uniq_id) {
2399 /* stream changed, no need to go any further */
2400 chunk_appendf(&trash, " *** session terminated while we were watching it ***\n");
2401 if (bi_putchk(si_ic(si), &trash) == -1) {
2402 si_applet_cant_put(si);
2403 return 0;
2404 }
2405 appctx->ctx.sess.uid = 0;
2406 appctx->ctx.sess.section = 0;
2407 return 1;
2408 }
2409
2410 switch (appctx->ctx.sess.section) {
2411 case 0: /* main status of the stream */
2412 appctx->ctx.sess.uid = sess->uniq_id;
2413 appctx->ctx.sess.section = 1;
2414 /* fall through */
2415
2416 case 1:
2417 get_localtime(sess->logs.accept_date.tv_sec, &tm);
2418 chunk_appendf(&trash,
2419 "%p: [%02d/%s/%04d:%02d:%02d:%02d.%06d] id=%u proto=%s",
2420 sess,
2421 tm.tm_mday, monthname[tm.tm_mon], tm.tm_year+1900,
2422 tm.tm_hour, tm.tm_min, tm.tm_sec, (int)(sess->logs.accept_date.tv_usec),
2423 sess->uniq_id,
2424 strm_li(sess) ? strm_li(sess)->proto->name : "?");
2425
2426 conn = objt_conn(strm_orig(sess));
2427 switch (conn ? addr_to_str(&conn->addr.from, pn, sizeof(pn)) : AF_UNSPEC) {
2428 case AF_INET:
2429 case AF_INET6:
2430 chunk_appendf(&trash, " source=%s:%d\n",
2431 pn, get_host_port(&conn->addr.from));
2432 break;
2433 case AF_UNIX:
2434 chunk_appendf(&trash, " source=unix:%d\n", strm_li(sess)->luid);
2435 break;
2436 default:
2437 /* no more information to print right now */
2438 chunk_appendf(&trash, "\n");
2439 break;
2440 }
2441
2442 chunk_appendf(&trash,
2443 " flags=0x%x, conn_retries=%d, srv_conn=%p, pend_pos=%p\n",
2444 sess->flags, sess->si[1].conn_retries, sess->srv_conn, sess->pend_pos);
2445
2446 chunk_appendf(&trash,
2447 " frontend=%s (id=%u mode=%s), listener=%s (id=%u)",
2448 strm_fe(sess)->id, strm_fe(sess)->uuid, strm_fe(sess)->mode ? "http" : "tcp",
2449 strm_li(sess) ? strm_li(sess)->name ? strm_li(sess)->name : "?" : "?",
2450 strm_li(sess) ? strm_li(sess)->luid : 0);
2451
2452 if (conn)
2453 conn_get_to_addr(conn);
2454
2455 switch (conn ? addr_to_str(&conn->addr.to, pn, sizeof(pn)) : AF_UNSPEC) {
2456 case AF_INET:
2457 case AF_INET6:
2458 chunk_appendf(&trash, " addr=%s:%d\n",
2459 pn, get_host_port(&conn->addr.to));
2460 break;
2461 case AF_UNIX:
2462 chunk_appendf(&trash, " addr=unix:%d\n", strm_li(sess)->luid);
2463 break;
2464 default:
2465 /* no more information to print right now */
2466 chunk_appendf(&trash, "\n");
2467 break;
2468 }
2469
2470 if (sess->be->cap & PR_CAP_BE)
2471 chunk_appendf(&trash,
2472 " backend=%s (id=%u mode=%s)",
2473 sess->be->id,
2474 sess->be->uuid, sess->be->mode ? "http" : "tcp");
2475 else
2476 chunk_appendf(&trash, " backend=<NONE> (id=-1 mode=-)");
2477
2478 conn = objt_conn(sess->si[1].end);
2479 if (conn)
2480 conn_get_from_addr(conn);
2481
2482 switch (conn ? addr_to_str(&conn->addr.from, pn, sizeof(pn)) : AF_UNSPEC) {
2483 case AF_INET:
2484 case AF_INET6:
2485 chunk_appendf(&trash, " addr=%s:%d\n",
2486 pn, get_host_port(&conn->addr.from));
2487 break;
2488 case AF_UNIX:
2489 chunk_appendf(&trash, " addr=unix\n");
2490 break;
2491 default:
2492 /* no more information to print right now */
2493 chunk_appendf(&trash, "\n");
2494 break;
2495 }
2496
2497 if (sess->be->cap & PR_CAP_BE)
2498 chunk_appendf(&trash,
2499 " server=%s (id=%u)",
2500 objt_server(sess->target) ? objt_server(sess->target)->id : "<none>",
2501 objt_server(sess->target) ? objt_server(sess->target)->puid : 0);
2502 else
2503 chunk_appendf(&trash, " server=<NONE> (id=-1)");
2504
2505 if (conn)
2506 conn_get_to_addr(conn);
2507
2508 switch (conn ? addr_to_str(&conn->addr.to, pn, sizeof(pn)) : AF_UNSPEC) {
2509 case AF_INET:
2510 case AF_INET6:
2511 chunk_appendf(&trash, " addr=%s:%d\n",
2512 pn, get_host_port(&conn->addr.to));
2513 break;
2514 case AF_UNIX:
2515 chunk_appendf(&trash, " addr=unix\n");
2516 break;
2517 default:
2518 /* no more information to print right now */
2519 chunk_appendf(&trash, "\n");
2520 break;
2521 }
2522
2523 chunk_appendf(&trash,
2524 " task=%p (state=0x%02x nice=%d calls=%d exp=%s%s",
2525 sess->task,
2526 sess->task->state,
2527 sess->task->nice, sess->task->calls,
2528 sess->task->expire ?
2529 tick_is_expired(sess->task->expire, now_ms) ? "<PAST>" :
2530 human_time(TICKS_TO_MS(sess->task->expire - now_ms),
2531 TICKS_TO_MS(1000)) : "<NEVER>",
2532 task_in_rq(sess->task) ? ", running" : "");
2533
2534 chunk_appendf(&trash,
2535 " age=%s)\n",
2536 human_time(now.tv_sec - sess->logs.accept_date.tv_sec, 1));
2537
2538 if (sess->txn)
2539 chunk_appendf(&trash,
2540 " txn=%p flags=0x%x meth=%d status=%d req.st=%s rsp.st=%s waiting=%d\n",
2541 sess->txn, sess->txn->flags, sess->txn->meth, sess->txn->status,
2542 http_msg_state_str(sess->txn->req.msg_state), http_msg_state_str(sess->txn->rsp.msg_state), !LIST_ISEMPTY(&sess->buffer_wait));
2543
2544 chunk_appendf(&trash,
2545 " si[0]=%p (state=%s flags=0x%02x endp0=%s:%p exp=%s, et=0x%03x)\n",
2546 &sess->si[0],
2547 si_state_str(sess->si[0].state),
2548 sess->si[0].flags,
2549 obj_type_name(sess->si[0].end),
2550 obj_base_ptr(sess->si[0].end),
2551 sess->si[0].exp ?
2552 tick_is_expired(sess->si[0].exp, now_ms) ? "<PAST>" :
2553 human_time(TICKS_TO_MS(sess->si[0].exp - now_ms),
2554 TICKS_TO_MS(1000)) : "<NEVER>",
2555 sess->si[0].err_type);
2556
2557 chunk_appendf(&trash,
2558 " si[1]=%p (state=%s flags=0x%02x endp1=%s:%p exp=%s, et=0x%03x)\n",
2559 &sess->si[1],
2560 si_state_str(sess->si[1].state),
2561 sess->si[1].flags,
2562 obj_type_name(sess->si[1].end),
2563 obj_base_ptr(sess->si[1].end),
2564 sess->si[1].exp ?
2565 tick_is_expired(sess->si[1].exp, now_ms) ? "<PAST>" :
2566 human_time(TICKS_TO_MS(sess->si[1].exp - now_ms),
2567 TICKS_TO_MS(1000)) : "<NEVER>",
2568 sess->si[1].err_type);
2569
2570 if ((conn = objt_conn(sess->si[0].end)) != NULL) {
2571 chunk_appendf(&trash,
2572 " co0=%p ctrl=%s xprt=%s data=%s target=%s:%p\n",
2573 conn,
2574 get_conn_ctrl_name(conn),
2575 get_conn_xprt_name(conn),
2576 get_conn_data_name(conn),
2577 obj_type_name(conn->target),
2578 obj_base_ptr(conn->target));
2579
2580 chunk_appendf(&trash, " flags=0x%08x", conn->flags);
2581
2582 if (conn->t.sock.fd >= 0) {
2583 chunk_appendf(&trash, " fd=%d fd.state=%02x fd.cache=%d updt=%d\n",
2584 conn->t.sock.fd, fdtab[conn->t.sock.fd].state,
2585 fdtab[conn->t.sock.fd].cache, fdtab[conn->t.sock.fd].updated);
2586 }
2587 else
2588 chunk_appendf(&trash, " fd=<dead>\n");
2589 }
2590 else if ((tmpctx = objt_appctx(sess->si[0].end)) != NULL) {
2591 chunk_appendf(&trash,
2592 " app0=%p st0=%d st1=%d st2=%d applet=%s\n",
2593 tmpctx,
2594 tmpctx->st0,
2595 tmpctx->st1,
2596 tmpctx->st2,
2597 tmpctx->applet->name);
2598 }
2599
2600 if ((conn = objt_conn(sess->si[1].end)) != NULL) {
2601 chunk_appendf(&trash,
2602 " co1=%p ctrl=%s xprt=%s data=%s target=%s:%p\n",
2603 conn,
2604 get_conn_ctrl_name(conn),
2605 get_conn_xprt_name(conn),
2606 get_conn_data_name(conn),
2607 obj_type_name(conn->target),
2608 obj_base_ptr(conn->target));
2609
2610 chunk_appendf(&trash, " flags=0x%08x", conn->flags);
2611
2612 if (conn->t.sock.fd >= 0) {
2613 chunk_appendf(&trash, " fd=%d fd.state=%02x fd.cache=%d updt=%d\n",
2614 conn->t.sock.fd, fdtab[conn->t.sock.fd].state,
2615 fdtab[conn->t.sock.fd].cache, fdtab[conn->t.sock.fd].updated);
2616 }
2617 else
2618 chunk_appendf(&trash, " fd=<dead>\n");
2619 }
2620 else if ((tmpctx = objt_appctx(sess->si[1].end)) != NULL) {
2621 chunk_appendf(&trash,
2622 " app1=%p st0=%d st1=%d st2=%d applet=%s\n",
2623 tmpctx,
2624 tmpctx->st0,
2625 tmpctx->st1,
2626 tmpctx->st2,
2627 tmpctx->applet->name);
2628 }
2629
2630 chunk_appendf(&trash,
2631 " req=%p (f=0x%06x an=0x%x pipe=%d tofwd=%d total=%lld)\n"
2632 " an_exp=%s",
2633 &sess->req,
2634 sess->req.flags, sess->req.analysers,
2635 sess->req.pipe ? sess->req.pipe->data : 0,
2636 sess->req.to_forward, sess->req.total,
2637 sess->req.analyse_exp ?
2638 human_time(TICKS_TO_MS(sess->req.analyse_exp - now_ms),
2639 TICKS_TO_MS(1000)) : "<NEVER>");
2640
2641 chunk_appendf(&trash,
2642 " rex=%s",
2643 sess->req.rex ?
2644 human_time(TICKS_TO_MS(sess->req.rex - now_ms),
2645 TICKS_TO_MS(1000)) : "<NEVER>");
2646
2647 chunk_appendf(&trash,
2648 " wex=%s\n"
2649 " buf=%p data=%p o=%d p=%d req.next=%d i=%d size=%d\n",
2650 sess->req.wex ?
2651 human_time(TICKS_TO_MS(sess->req.wex - now_ms),
2652 TICKS_TO_MS(1000)) : "<NEVER>",
2653 sess->req.buf,
2654 sess->req.buf->data, sess->req.buf->o,
2655 (int)(sess->req.buf->p - sess->req.buf->data),
2656 sess->txn ? sess->txn->req.next : 0, sess->req.buf->i,
2657 sess->req.buf->size);
2658
2659 chunk_appendf(&trash,
2660 " res=%p (f=0x%06x an=0x%x pipe=%d tofwd=%d total=%lld)\n"
2661 " an_exp=%s",
2662 &sess->res,
2663 sess->res.flags, sess->res.analysers,
2664 sess->res.pipe ? sess->res.pipe->data : 0,
2665 sess->res.to_forward, sess->res.total,
2666 sess->res.analyse_exp ?
2667 human_time(TICKS_TO_MS(sess->res.analyse_exp - now_ms),
2668 TICKS_TO_MS(1000)) : "<NEVER>");
2669
2670 chunk_appendf(&trash,
2671 " rex=%s",
2672 sess->res.rex ?
2673 human_time(TICKS_TO_MS(sess->res.rex - now_ms),
2674 TICKS_TO_MS(1000)) : "<NEVER>");
2675
2676 chunk_appendf(&trash,
2677 " wex=%s\n"
2678 " buf=%p data=%p o=%d p=%d rsp.next=%d i=%d size=%d\n",
2679 sess->res.wex ?
2680 human_time(TICKS_TO_MS(sess->res.wex - now_ms),
2681 TICKS_TO_MS(1000)) : "<NEVER>",
2682 sess->res.buf,
2683 sess->res.buf->data, sess->res.buf->o,
2684 (int)(sess->res.buf->p - sess->res.buf->data),
2685 sess->txn ? sess->txn->rsp.next : 0, sess->res.buf->i,
2686 sess->res.buf->size);
2687
2688 if (bi_putchk(si_ic(si), &trash) == -1) {
2689 si_applet_cant_put(si);
2690 return 0;
2691 }
2692
2693 /* use other states to dump the contents */
2694 }
2695 /* end of dump */
2696 appctx->ctx.sess.uid = 0;
2697 appctx->ctx.sess.section = 0;
2698 return 1;
2699}
2700
William Lallemand74c24fb2016-11-21 17:18:36 +01002701/* This function dumps all streams' states onto the stream interface's
2702 * read buffer. It returns 0 if the output buffer is full and it needs
2703 * to be called again, otherwise non-zero. It is designed to be called
2704 * from stats_dump_sess_to_buffer() below.
2705 */
2706static int stats_dump_sess_to_buffer(struct stream_interface *si)
2707{
2708 struct appctx *appctx = __objt_appctx(si->end);
2709 struct connection *conn;
2710
2711 if (unlikely(si_ic(si)->flags & (CF_WRITE_ERROR|CF_SHUTW))) {
2712 /* If we're forced to shut down, we might have to remove our
2713 * reference to the last stream being dumped.
2714 */
2715 if (appctx->st2 == STAT_ST_LIST) {
2716 if (!LIST_ISEMPTY(&appctx->ctx.sess.bref.users)) {
2717 LIST_DEL(&appctx->ctx.sess.bref.users);
2718 LIST_INIT(&appctx->ctx.sess.bref.users);
2719 }
2720 }
2721 return 1;
2722 }
2723
2724 chunk_reset(&trash);
2725
2726 switch (appctx->st2) {
2727 case STAT_ST_INIT:
2728 /* the function had not been called yet, let's prepare the
2729 * buffer for a response. We initialize the current stream
2730 * pointer to the first in the global list. When a target
2731 * stream is being destroyed, it is responsible for updating
2732 * this pointer. We know we have reached the end when this
2733 * pointer points back to the head of the streams list.
2734 */
2735 LIST_INIT(&appctx->ctx.sess.bref.users);
2736 appctx->ctx.sess.bref.ref = streams.n;
2737 appctx->st2 = STAT_ST_LIST;
2738 /* fall through */
2739
2740 case STAT_ST_LIST:
2741 /* first, let's detach the back-ref from a possible previous stream */
2742 if (!LIST_ISEMPTY(&appctx->ctx.sess.bref.users)) {
2743 LIST_DEL(&appctx->ctx.sess.bref.users);
2744 LIST_INIT(&appctx->ctx.sess.bref.users);
2745 }
2746
2747 /* and start from where we stopped */
2748 while (appctx->ctx.sess.bref.ref != &streams) {
2749 char pn[INET6_ADDRSTRLEN];
2750 struct stream *curr_sess;
2751
2752 curr_sess = LIST_ELEM(appctx->ctx.sess.bref.ref, struct stream *, list);
2753
2754 if (appctx->ctx.sess.target) {
2755 if (appctx->ctx.sess.target != (void *)-1 && appctx->ctx.sess.target != curr_sess)
2756 goto next_sess;
2757
2758 LIST_ADDQ(&curr_sess->back_refs, &appctx->ctx.sess.bref.users);
2759 /* call the proper dump() function and return if we're missing space */
2760 if (!stats_dump_full_sess_to_buffer(si, curr_sess))
2761 return 0;
2762
2763 /* stream dump complete */
2764 LIST_DEL(&appctx->ctx.sess.bref.users);
2765 LIST_INIT(&appctx->ctx.sess.bref.users);
2766 if (appctx->ctx.sess.target != (void *)-1) {
2767 appctx->ctx.sess.target = NULL;
2768 break;
2769 }
2770 else
2771 goto next_sess;
2772 }
2773
2774 chunk_appendf(&trash,
2775 "%p: proto=%s",
2776 curr_sess,
2777 strm_li(curr_sess) ? strm_li(curr_sess)->proto->name : "?");
2778
2779 conn = objt_conn(strm_orig(curr_sess));
2780 switch (conn ? addr_to_str(&conn->addr.from, pn, sizeof(pn)) : AF_UNSPEC) {
2781 case AF_INET:
2782 case AF_INET6:
2783 chunk_appendf(&trash,
2784 " src=%s:%d fe=%s be=%s srv=%s",
2785 pn,
2786 get_host_port(&conn->addr.from),
2787 strm_fe(curr_sess)->id,
2788 (curr_sess->be->cap & PR_CAP_BE) ? curr_sess->be->id : "<NONE>",
2789 objt_server(curr_sess->target) ? objt_server(curr_sess->target)->id : "<none>"
2790 );
2791 break;
2792 case AF_UNIX:
2793 chunk_appendf(&trash,
2794 " src=unix:%d fe=%s be=%s srv=%s",
2795 strm_li(curr_sess)->luid,
2796 strm_fe(curr_sess)->id,
2797 (curr_sess->be->cap & PR_CAP_BE) ? curr_sess->be->id : "<NONE>",
2798 objt_server(curr_sess->target) ? objt_server(curr_sess->target)->id : "<none>"
2799 );
2800 break;
2801 }
2802
2803 chunk_appendf(&trash,
2804 " ts=%02x age=%s calls=%d",
2805 curr_sess->task->state,
2806 human_time(now.tv_sec - curr_sess->logs.tv_accept.tv_sec, 1),
2807 curr_sess->task->calls);
2808
2809 chunk_appendf(&trash,
2810 " rq[f=%06xh,i=%d,an=%02xh,rx=%s",
2811 curr_sess->req.flags,
2812 curr_sess->req.buf->i,
2813 curr_sess->req.analysers,
2814 curr_sess->req.rex ?
2815 human_time(TICKS_TO_MS(curr_sess->req.rex - now_ms),
2816 TICKS_TO_MS(1000)) : "");
2817
2818 chunk_appendf(&trash,
2819 ",wx=%s",
2820 curr_sess->req.wex ?
2821 human_time(TICKS_TO_MS(curr_sess->req.wex - now_ms),
2822 TICKS_TO_MS(1000)) : "");
2823
2824 chunk_appendf(&trash,
2825 ",ax=%s]",
2826 curr_sess->req.analyse_exp ?
2827 human_time(TICKS_TO_MS(curr_sess->req.analyse_exp - now_ms),
2828 TICKS_TO_MS(1000)) : "");
2829
2830 chunk_appendf(&trash,
2831 " rp[f=%06xh,i=%d,an=%02xh,rx=%s",
2832 curr_sess->res.flags,
2833 curr_sess->res.buf->i,
2834 curr_sess->res.analysers,
2835 curr_sess->res.rex ?
2836 human_time(TICKS_TO_MS(curr_sess->res.rex - now_ms),
2837 TICKS_TO_MS(1000)) : "");
2838
2839 chunk_appendf(&trash,
2840 ",wx=%s",
2841 curr_sess->res.wex ?
2842 human_time(TICKS_TO_MS(curr_sess->res.wex - now_ms),
2843 TICKS_TO_MS(1000)) : "");
2844
2845 chunk_appendf(&trash,
2846 ",ax=%s]",
2847 curr_sess->res.analyse_exp ?
2848 human_time(TICKS_TO_MS(curr_sess->res.analyse_exp - now_ms),
2849 TICKS_TO_MS(1000)) : "");
2850
2851 conn = objt_conn(curr_sess->si[0].end);
2852 chunk_appendf(&trash,
2853 " s0=[%d,%1xh,fd=%d,ex=%s]",
2854 curr_sess->si[0].state,
2855 curr_sess->si[0].flags,
2856 (conn && conn->t.sock.fd >= 0) ? conn->t.sock.fd : -1,
2857 curr_sess->si[0].exp ?
2858 human_time(TICKS_TO_MS(curr_sess->si[0].exp - now_ms),
2859 TICKS_TO_MS(1000)) : "");
2860
2861 conn = objt_conn(curr_sess->si[1].end);
2862 chunk_appendf(&trash,
2863 " s1=[%d,%1xh,fd=%d,ex=%s]",
2864 curr_sess->si[1].state,
2865 curr_sess->si[1].flags,
2866 (conn && conn->t.sock.fd >= 0) ? conn->t.sock.fd : -1,
2867 curr_sess->si[1].exp ?
2868 human_time(TICKS_TO_MS(curr_sess->si[1].exp - now_ms),
2869 TICKS_TO_MS(1000)) : "");
2870
2871 chunk_appendf(&trash,
2872 " exp=%s",
2873 curr_sess->task->expire ?
2874 human_time(TICKS_TO_MS(curr_sess->task->expire - now_ms),
2875 TICKS_TO_MS(1000)) : "");
2876 if (task_in_rq(curr_sess->task))
2877 chunk_appendf(&trash, " run(nice=%d)", curr_sess->task->nice);
2878
2879 chunk_appendf(&trash, "\n");
2880
2881 if (bi_putchk(si_ic(si), &trash) == -1) {
2882 /* let's try again later from this stream. We add ourselves into
2883 * this stream's users so that it can remove us upon termination.
2884 */
2885 si_applet_cant_put(si);
2886 LIST_ADDQ(&curr_sess->back_refs, &appctx->ctx.sess.bref.users);
2887 return 0;
2888 }
2889
2890 next_sess:
2891 appctx->ctx.sess.bref.ref = curr_sess->list.n;
2892 }
2893
2894 if (appctx->ctx.sess.target && appctx->ctx.sess.target != (void *)-1) {
2895 /* specified stream not found */
2896 if (appctx->ctx.sess.section > 0)
2897 chunk_appendf(&trash, " *** session terminated while we were watching it ***\n");
2898 else
2899 chunk_appendf(&trash, "Session not found.\n");
2900
2901 if (bi_putchk(si_ic(si), &trash) == -1) {
2902 si_applet_cant_put(si);
2903 return 0;
2904 }
2905
2906 appctx->ctx.sess.target = NULL;
2907 appctx->ctx.sess.uid = 0;
2908 return 1;
2909 }
2910
2911 appctx->st2 = STAT_ST_FIN;
2912 /* fall through */
2913
2914 default:
2915 appctx->st2 = STAT_ST_FIN;
2916 return 1;
2917 }
2918}
2919
2920/* This is called when the stream interface is closed. For instance, upon an
2921 * external abort, we won't call the i/o handler anymore so we may need to
2922 * remove back references to the stream currently being dumped.
2923 */
2924static void cli_release_handler(struct appctx *appctx)
2925{
2926 if (appctx->io_release) {
2927 appctx->io_release(appctx);
2928 appctx->io_release = NULL;
2929 }
2930 if (appctx->st0 == STAT_CLI_O_SESS && appctx->st2 == STAT_ST_LIST) {
2931 if (!LIST_ISEMPTY(&appctx->ctx.sess.bref.users))
2932 LIST_DEL(&appctx->ctx.sess.bref.users);
2933 }
2934 else if ((appctx->st0 == STAT_CLI_O_TAB || appctx->st0 == STAT_CLI_O_CLR) &&
2935 appctx->st2 == STAT_ST_LIST) {
2936 appctx->ctx.table.entry->ref_cnt--;
2937 stksess_kill_if_expired(&appctx->ctx.table.proxy->table, appctx->ctx.table.entry);
2938 }
2939 else if (appctx->st0 == STAT_CLI_PRINT_FREE) {
2940 free(appctx->ctx.cli.err);
2941 appctx->ctx.cli.err = NULL;
2942 }
William Lallemand74c24fb2016-11-21 17:18:36 +01002943}
2944
2945/* This function is used to either dump tables states (when action is set
2946 * to STAT_CLI_O_TAB) or clear tables (when action is STAT_CLI_O_CLR).
2947 * It returns 0 if the output buffer is full and it needs to be called
2948 * again, otherwise non-zero.
2949 */
2950static int stats_table_request(struct stream_interface *si, int action)
2951{
2952 struct appctx *appctx = __objt_appctx(si->end);
2953 struct stream *s = si_strm(si);
2954 struct ebmb_node *eb;
2955 int dt;
2956 int skip_entry;
2957 int show = action == STAT_CLI_O_TAB;
2958
2959 /*
2960 * We have 3 possible states in appctx->st2 :
2961 * - STAT_ST_INIT : the first call
2962 * - STAT_ST_INFO : the proxy pointer points to the next table to
2963 * dump, the entry pointer is NULL ;
2964 * - STAT_ST_LIST : the proxy pointer points to the current table
2965 * and the entry pointer points to the next entry to be dumped,
2966 * and the refcount on the next entry is held ;
2967 * - STAT_ST_END : nothing left to dump, the buffer may contain some
2968 * data though.
2969 */
2970
2971 if (unlikely(si_ic(si)->flags & (CF_WRITE_ERROR|CF_SHUTW))) {
2972 /* in case of abort, remove any refcount we might have set on an entry */
2973 if (appctx->st2 == STAT_ST_LIST) {
2974 appctx->ctx.table.entry->ref_cnt--;
2975 stksess_kill_if_expired(&appctx->ctx.table.proxy->table, appctx->ctx.table.entry);
2976 }
2977 return 1;
2978 }
2979
2980 chunk_reset(&trash);
2981
2982 while (appctx->st2 != STAT_ST_FIN) {
2983 switch (appctx->st2) {
2984 case STAT_ST_INIT:
2985 appctx->ctx.table.proxy = appctx->ctx.table.target;
2986 if (!appctx->ctx.table.proxy)
2987 appctx->ctx.table.proxy = proxy;
2988
2989 appctx->ctx.table.entry = NULL;
2990 appctx->st2 = STAT_ST_INFO;
2991 break;
2992
2993 case STAT_ST_INFO:
2994 if (!appctx->ctx.table.proxy ||
2995 (appctx->ctx.table.target &&
2996 appctx->ctx.table.proxy != appctx->ctx.table.target)) {
2997 appctx->st2 = STAT_ST_END;
2998 break;
2999 }
3000
3001 if (appctx->ctx.table.proxy->table.size) {
3002 if (show && !stats_dump_table_head_to_buffer(&trash, si, appctx->ctx.table.proxy,
3003 appctx->ctx.table.target))
3004 return 0;
3005
3006 if (appctx->ctx.table.target &&
3007 strm_li(s)->bind_conf->level >= ACCESS_LVL_OPER) {
3008 /* dump entries only if table explicitly requested */
3009 eb = ebmb_first(&appctx->ctx.table.proxy->table.keys);
3010 if (eb) {
3011 appctx->ctx.table.entry = ebmb_entry(eb, struct stksess, key);
3012 appctx->ctx.table.entry->ref_cnt++;
3013 appctx->st2 = STAT_ST_LIST;
3014 break;
3015 }
3016 }
3017 }
3018 appctx->ctx.table.proxy = appctx->ctx.table.proxy->next;
3019 break;
3020
3021 case STAT_ST_LIST:
3022 skip_entry = 0;
3023
3024 if (appctx->ctx.table.data_type >= 0) {
3025 /* we're filtering on some data contents */
3026 void *ptr;
3027 long long data;
3028
3029 dt = appctx->ctx.table.data_type;
3030 ptr = stktable_data_ptr(&appctx->ctx.table.proxy->table,
3031 appctx->ctx.table.entry,
3032 dt);
3033
3034 data = 0;
3035 switch (stktable_data_types[dt].std_type) {
3036 case STD_T_SINT:
3037 data = stktable_data_cast(ptr, std_t_sint);
3038 break;
3039 case STD_T_UINT:
3040 data = stktable_data_cast(ptr, std_t_uint);
3041 break;
3042 case STD_T_ULL:
3043 data = stktable_data_cast(ptr, std_t_ull);
3044 break;
3045 case STD_T_FRQP:
3046 data = read_freq_ctr_period(&stktable_data_cast(ptr, std_t_frqp),
3047 appctx->ctx.table.proxy->table.data_arg[dt].u);
3048 break;
3049 }
3050
3051 /* skip the entry if the data does not match the test and the value */
3052 if ((data < appctx->ctx.table.value &&
3053 (appctx->ctx.table.data_op == STD_OP_EQ ||
3054 appctx->ctx.table.data_op == STD_OP_GT ||
3055 appctx->ctx.table.data_op == STD_OP_GE)) ||
3056 (data == appctx->ctx.table.value &&
3057 (appctx->ctx.table.data_op == STD_OP_NE ||
3058 appctx->ctx.table.data_op == STD_OP_GT ||
3059 appctx->ctx.table.data_op == STD_OP_LT)) ||
3060 (data > appctx->ctx.table.value &&
3061 (appctx->ctx.table.data_op == STD_OP_EQ ||
3062 appctx->ctx.table.data_op == STD_OP_LT ||
3063 appctx->ctx.table.data_op == STD_OP_LE)))
3064 skip_entry = 1;
3065 }
3066
3067 if (show && !skip_entry &&
3068 !stats_dump_table_entry_to_buffer(&trash, si, appctx->ctx.table.proxy,
3069 appctx->ctx.table.entry))
3070 return 0;
3071
3072 appctx->ctx.table.entry->ref_cnt--;
3073
3074 eb = ebmb_next(&appctx->ctx.table.entry->key);
3075 if (eb) {
3076 struct stksess *old = appctx->ctx.table.entry;
3077 appctx->ctx.table.entry = ebmb_entry(eb, struct stksess, key);
3078 if (show)
3079 stksess_kill_if_expired(&appctx->ctx.table.proxy->table, old);
3080 else if (!skip_entry && !appctx->ctx.table.entry->ref_cnt)
3081 stksess_kill(&appctx->ctx.table.proxy->table, old);
3082 appctx->ctx.table.entry->ref_cnt++;
3083 break;
3084 }
3085
3086
3087 if (show)
3088 stksess_kill_if_expired(&appctx->ctx.table.proxy->table, appctx->ctx.table.entry);
3089 else if (!skip_entry && !appctx->ctx.table.entry->ref_cnt)
3090 stksess_kill(&appctx->ctx.table.proxy->table, appctx->ctx.table.entry);
3091
3092 appctx->ctx.table.proxy = appctx->ctx.table.proxy->next;
3093 appctx->st2 = STAT_ST_INFO;
3094 break;
3095
3096 case STAT_ST_END:
3097 appctx->st2 = STAT_ST_FIN;
3098 break;
3099 }
3100 }
3101 return 1;
3102}
3103
3104/* print a line of text buffer (limited to 70 bytes) to <out>. The format is :
3105 * <2 spaces> <offset=5 digits> <space or plus> <space> <70 chars max> <\n>
3106 * which is 60 chars per line. Non-printable chars \t, \n, \r and \e are
3107 * encoded in C format. Other non-printable chars are encoded "\xHH". Original
3108 * lines are respected within the limit of 70 output chars. Lines that are
3109 * continuation of a previous truncated line begin with "+" instead of " "
3110 * after the offset. The new pointer is returned.
3111 */
3112static int dump_text_line(struct chunk *out, const char *buf, int bsize, int len,
3113 int *line, int ptr)
3114{
3115 int end;
3116 unsigned char c;
3117
3118 end = out->len + 80;
3119 if (end > out->size)
3120 return ptr;
3121
3122 chunk_appendf(out, " %05d%c ", ptr, (ptr == *line) ? ' ' : '+');
3123
3124 while (ptr < len && ptr < bsize) {
3125 c = buf[ptr];
3126 if (isprint(c) && isascii(c) && c != '\\') {
3127 if (out->len > end - 2)
3128 break;
3129 out->str[out->len++] = c;
3130 } else if (c == '\t' || c == '\n' || c == '\r' || c == '\e' || c == '\\') {
3131 if (out->len > end - 3)
3132 break;
3133 out->str[out->len++] = '\\';
3134 switch (c) {
3135 case '\t': c = 't'; break;
3136 case '\n': c = 'n'; break;
3137 case '\r': c = 'r'; break;
3138 case '\e': c = 'e'; break;
3139 case '\\': c = '\\'; break;
3140 }
3141 out->str[out->len++] = c;
3142 } else {
3143 if (out->len > end - 5)
3144 break;
3145 out->str[out->len++] = '\\';
3146 out->str[out->len++] = 'x';
3147 out->str[out->len++] = hextab[(c >> 4) & 0xF];
3148 out->str[out->len++] = hextab[c & 0xF];
3149 }
3150 if (buf[ptr++] == '\n') {
3151 /* we had a line break, let's return now */
3152 out->str[out->len++] = '\n';
3153 *line = ptr;
3154 return ptr;
3155 }
3156 }
3157 /* we have an incomplete line, we return it as-is */
3158 out->str[out->len++] = '\n';
3159 return ptr;
3160}
3161
William Lallemand74c24fb2016-11-21 17:18:36 +01003162/* This function dumps all captured errors onto the stream interface's
3163 * read buffer. It returns 0 if the output buffer is full and it needs
3164 * to be called again, otherwise non-zero.
3165 */
3166static int stats_dump_errors_to_buffer(struct stream_interface *si)
3167{
3168 struct appctx *appctx = __objt_appctx(si->end);
3169 extern const char *monthname[12];
3170
3171 if (unlikely(si_ic(si)->flags & (CF_WRITE_ERROR|CF_SHUTW)))
3172 return 1;
3173
3174 chunk_reset(&trash);
3175
3176 if (!appctx->ctx.errors.px) {
3177 /* the function had not been called yet, let's prepare the
3178 * buffer for a response.
3179 */
3180 struct tm tm;
3181
3182 get_localtime(date.tv_sec, &tm);
3183 chunk_appendf(&trash, "Total events captured on [%02d/%s/%04d:%02d:%02d:%02d.%03d] : %u\n",
3184 tm.tm_mday, monthname[tm.tm_mon], tm.tm_year+1900,
3185 tm.tm_hour, tm.tm_min, tm.tm_sec, (int)(date.tv_usec/1000),
3186 error_snapshot_id);
3187
3188 if (bi_putchk(si_ic(si), &trash) == -1) {
3189 /* Socket buffer full. Let's try again later from the same point */
3190 si_applet_cant_put(si);
3191 return 0;
3192 }
3193
3194 appctx->ctx.errors.px = proxy;
3195 appctx->ctx.errors.buf = 0;
3196 appctx->ctx.errors.bol = 0;
3197 appctx->ctx.errors.ptr = -1;
3198 }
3199
3200 /* we have two inner loops here, one for the proxy, the other one for
3201 * the buffer.
3202 */
3203 while (appctx->ctx.errors.px) {
3204 struct error_snapshot *es;
3205
3206 if (appctx->ctx.errors.buf == 0)
3207 es = &appctx->ctx.errors.px->invalid_req;
3208 else
3209 es = &appctx->ctx.errors.px->invalid_rep;
3210
3211 if (!es->when.tv_sec)
3212 goto next;
3213
3214 if (appctx->ctx.errors.iid >= 0 &&
3215 appctx->ctx.errors.px->uuid != appctx->ctx.errors.iid &&
3216 es->oe->uuid != appctx->ctx.errors.iid)
3217 goto next;
3218
3219 if (appctx->ctx.errors.ptr < 0) {
3220 /* just print headers now */
3221
3222 char pn[INET6_ADDRSTRLEN];
3223 struct tm tm;
3224 int port;
3225
3226 get_localtime(es->when.tv_sec, &tm);
3227 chunk_appendf(&trash, " \n[%02d/%s/%04d:%02d:%02d:%02d.%03d]",
3228 tm.tm_mday, monthname[tm.tm_mon], tm.tm_year+1900,
3229 tm.tm_hour, tm.tm_min, tm.tm_sec, (int)(es->when.tv_usec/1000));
3230
3231 switch (addr_to_str(&es->src, pn, sizeof(pn))) {
3232 case AF_INET:
3233 case AF_INET6:
3234 port = get_host_port(&es->src);
3235 break;
3236 default:
3237 port = 0;
3238 }
3239
3240 switch (appctx->ctx.errors.buf) {
3241 case 0:
3242 chunk_appendf(&trash,
3243 " frontend %s (#%d): invalid request\n"
3244 " backend %s (#%d)",
3245 appctx->ctx.errors.px->id, appctx->ctx.errors.px->uuid,
3246 (es->oe->cap & PR_CAP_BE) ? es->oe->id : "<NONE>",
3247 (es->oe->cap & PR_CAP_BE) ? es->oe->uuid : -1);
3248 break;
3249 case 1:
3250 chunk_appendf(&trash,
3251 " backend %s (#%d): invalid response\n"
3252 " frontend %s (#%d)",
3253 appctx->ctx.errors.px->id, appctx->ctx.errors.px->uuid,
3254 es->oe->id, es->oe->uuid);
3255 break;
3256 }
3257
3258 chunk_appendf(&trash,
3259 ", server %s (#%d), event #%u\n"
3260 " src %s:%d, session #%d, session flags 0x%08x\n"
3261 " HTTP msg state %d, msg flags 0x%08x, tx flags 0x%08x\n"
3262 " HTTP chunk len %lld bytes, HTTP body len %lld bytes\n"
3263 " buffer flags 0x%08x, out %d bytes, total %lld bytes\n"
3264 " pending %d bytes, wrapping at %d, error at position %d:\n \n",
3265 es->srv ? es->srv->id : "<NONE>", es->srv ? es->srv->puid : -1,
3266 es->ev_id,
3267 pn, port, es->sid, es->s_flags,
3268 es->state, es->m_flags, es->t_flags,
3269 es->m_clen, es->m_blen,
3270 es->b_flags, es->b_out, es->b_tot,
3271 es->len, es->b_wrap, es->pos);
3272
3273 if (bi_putchk(si_ic(si), &trash) == -1) {
3274 /* Socket buffer full. Let's try again later from the same point */
3275 si_applet_cant_put(si);
3276 return 0;
3277 }
3278 appctx->ctx.errors.ptr = 0;
3279 appctx->ctx.errors.sid = es->sid;
3280 }
3281
3282 if (appctx->ctx.errors.sid != es->sid) {
3283 /* the snapshot changed while we were dumping it */
3284 chunk_appendf(&trash,
3285 " WARNING! update detected on this snapshot, dump interrupted. Please re-check!\n");
3286 if (bi_putchk(si_ic(si), &trash) == -1) {
3287 si_applet_cant_put(si);
3288 return 0;
3289 }
3290 goto next;
3291 }
3292
3293 /* OK, ptr >= 0, so we have to dump the current line */
3294 while (es->buf && appctx->ctx.errors.ptr < es->len && appctx->ctx.errors.ptr < global.tune.bufsize) {
3295 int newptr;
3296 int newline;
3297
3298 newline = appctx->ctx.errors.bol;
3299 newptr = dump_text_line(&trash, es->buf, global.tune.bufsize, es->len, &newline, appctx->ctx.errors.ptr);
3300 if (newptr == appctx->ctx.errors.ptr)
3301 return 0;
3302
3303 if (bi_putchk(si_ic(si), &trash) == -1) {
3304 /* Socket buffer full. Let's try again later from the same point */
3305 si_applet_cant_put(si);
3306 return 0;
3307 }
3308 appctx->ctx.errors.ptr = newptr;
3309 appctx->ctx.errors.bol = newline;
3310 };
3311 next:
3312 appctx->ctx.errors.bol = 0;
3313 appctx->ctx.errors.ptr = -1;
3314 appctx->ctx.errors.buf++;
3315 if (appctx->ctx.errors.buf > 1) {
3316 appctx->ctx.errors.buf = 0;
3317 appctx->ctx.errors.px = appctx->ctx.errors.px->next;
3318 }
3319 }
3320
3321 /* dump complete */
3322 return 1;
3323}
3324
3325/* This function dumps all environmnent variables to the buffer. It returns 0
3326 * if the output buffer is full and it needs to be called again, otherwise
3327 * non-zero. Dumps only one entry if st2 == STAT_ST_END.
3328 */
3329static int stats_dump_env_to_buffer(struct stream_interface *si)
3330{
3331 struct appctx *appctx = __objt_appctx(si->end);
3332
3333 if (unlikely(si_ic(si)->flags & (CF_WRITE_ERROR|CF_SHUTW)))
3334 return 1;
3335
3336 chunk_reset(&trash);
3337
3338 /* we have two inner loops here, one for the proxy, the other one for
3339 * the buffer.
3340 */
3341 while (*appctx->ctx.env.var) {
3342 chunk_printf(&trash, "%s\n", *appctx->ctx.env.var);
3343
3344 if (bi_putchk(si_ic(si), &trash) == -1) {
3345 si_applet_cant_put(si);
3346 return 0;
3347 }
3348 if (appctx->st2 == STAT_ST_END)
3349 break;
3350 appctx->ctx.env.var++;
3351 }
3352
3353 /* dump complete */
3354 return 1;
3355}
3356
3357/* parse the "level" argument on the bind lines */
3358static int bind_parse_level(char **args, int cur_arg, struct proxy *px, struct bind_conf *conf, char **err)
3359{
3360 if (!*args[cur_arg + 1]) {
3361 memprintf(err, "'%s' : missing level", args[cur_arg]);
3362 return ERR_ALERT | ERR_FATAL;
3363 }
3364
3365 if (!strcmp(args[cur_arg+1], "user"))
3366 conf->level = ACCESS_LVL_USER;
3367 else if (!strcmp(args[cur_arg+1], "operator"))
3368 conf->level = ACCESS_LVL_OPER;
3369 else if (!strcmp(args[cur_arg+1], "admin"))
3370 conf->level = ACCESS_LVL_ADMIN;
3371 else {
3372 memprintf(err, "'%s' only supports 'user', 'operator', and 'admin' (got '%s')",
3373 args[cur_arg], args[cur_arg+1]);
3374 return ERR_ALERT | ERR_FATAL;
3375 }
3376
3377 return 0;
3378}
3379
3380static struct applet cli_applet = {
3381 .obj_type = OBJ_TYPE_APPLET,
3382 .name = "<CLI>", /* used for logging */
3383 .fct = cli_io_handler,
3384 .release = cli_release_handler,
3385};
3386
3387static struct cfg_kw_list cfg_kws = {ILH, {
3388 { CFG_GLOBAL, "stats", stats_parse_global },
3389 { 0, NULL, NULL },
3390}};
3391
3392static struct bind_kw_list bind_kws = { "STAT", { }, {
3393 { "level", bind_parse_level, 1 }, /* set the unix socket admin level */
3394 { NULL, NULL, 0 },
3395}};
3396
3397__attribute__((constructor))
3398static void __dumpstats_module_init(void)
3399{
3400 cfg_register_keywords(&cfg_kws);
3401 bind_register_keywords(&bind_kws);
3402}
3403
3404/*
3405 * Local variables:
3406 * c-indent-level: 8
3407 * c-basic-offset: 8
3408 * End:
3409 */