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