blob: 2ef14d10291b00ce4464b96ebbe8d317f3c32508 [file] [log] [blame]
Willy Tarreaubaaee002006-06-26 02:48:02 +02001/*
2 * Health-checks functions.
3 *
Willy Tarreau26c25062009-03-08 09:38:41 +01004 * Copyright 2000-2009 Willy Tarreau <w@1wt.eu>
Krzysztof Piotr Oledzki09605412009-09-23 22:09:24 +02005 * Copyright 2007-2009 Krzysztof Piotr Oledzki <ole@ans.pl>
Willy Tarreaubaaee002006-06-26 02:48:02 +02006 *
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
Willy Tarreaub8816082008-01-18 12:18:15 +010014#include <assert.h>
Krzysztof Piotr Oledzki09605412009-09-23 22:09:24 +020015#include <ctype.h>
Willy Tarreaubaaee002006-06-26 02:48:02 +020016#include <errno.h>
17#include <fcntl.h>
Willy Tarreau9b39dc52014-07-08 00:54:10 +020018#include <signal.h>
Simon Horman0ba0e4a2015-01-30 11:23:00 +090019#include <stdarg.h>
Willy Tarreaubaaee002006-06-26 02:48:02 +020020#include <stdio.h>
Krzysztof Oledzkib304dc72007-10-14 23:40:01 +020021#include <stdlib.h>
Willy Tarreau2dd0d472006-06-29 17:53:05 +020022#include <string.h>
Krzysztof Oledzkib304dc72007-10-14 23:40:01 +020023#include <time.h>
Willy Tarreaubaaee002006-06-26 02:48:02 +020024#include <unistd.h>
25#include <sys/socket.h>
Dmitry Sivachenkocaf58982009-08-24 15:11:06 +040026#include <sys/types.h>
Simon Horman98637e52014-06-20 12:30:16 +090027#include <sys/wait.h>
Willy Tarreaubaaee002006-06-26 02:48:02 +020028#include <netinet/in.h>
Willy Tarreau1274bc42009-07-15 07:16:31 +020029#include <netinet/tcp.h>
Willy Tarreaubaaee002006-06-26 02:48:02 +020030#include <arpa/inet.h>
31
Willy Tarreauc7e42382012-08-24 19:22:53 +020032#include <common/chunk.h>
Willy Tarreau2dd0d472006-06-29 17:53:05 +020033#include <common/compat.h>
34#include <common/config.h>
35#include <common/mini-clist.h>
Willy Tarreau83749182007-04-15 20:56:27 +020036#include <common/standard.h>
Willy Tarreau2dd0d472006-06-29 17:53:05 +020037#include <common/time.h>
Willy Tarreaubaaee002006-06-26 02:48:02 +020038
39#include <types/global.h>
Simon Horman0ba0e4a2015-01-30 11:23:00 +090040#include <types/mailers.h>
Willy Tarreaubaaee002006-06-26 02:48:02 +020041
Baptiste Assmann69e273f2013-12-11 00:52:19 +010042#ifdef USE_OPENSSL
43#include <types/ssl_sock.h>
44#include <proto/ssl_sock.h>
45#endif /* USE_OPENSSL */
46
Willy Tarreaubaaee002006-06-26 02:48:02 +020047#include <proto/backend.h>
Krzysztof Piotr Oledzki09605412009-09-23 22:09:24 +020048#include <proto/checks.h>
Simon Hormana2b9dad2013-02-12 10:45:54 +090049#include <proto/dumpstats.h>
Willy Tarreaubaaee002006-06-26 02:48:02 +020050#include <proto/fd.h>
51#include <proto/log.h>
52#include <proto/queue.h>
Willy Tarreauc6f4ce82009-06-10 11:09:37 +020053#include <proto/port_range.h>
Willy Tarreau3d300592007-03-18 18:34:41 +010054#include <proto/proto_http.h>
Willy Tarreaue8c66af2008-01-13 18:40:14 +010055#include <proto/proto_tcp.h>
Baptiste Assmann69e273f2013-12-11 00:52:19 +010056#include <proto/protocol.h>
Willy Tarreau2b5652f2006-12-31 17:46:05 +010057#include <proto/proxy.h>
Willy Tarreaufb56aab2012-09-28 14:40:02 +020058#include <proto/raw_sock.h>
Willy Tarreaubaaee002006-06-26 02:48:02 +020059#include <proto/server.h>
Simon Hormane0d1bfb2011-06-21 14:34:58 +090060#include <proto/session.h>
Willy Tarreau9e000c62011-03-10 14:03:36 +010061#include <proto/stream_interface.h>
Willy Tarreaubaaee002006-06-26 02:48:02 +020062#include <proto/task.h>
63
Willy Tarreaubd741542010-03-16 18:46:54 +010064static int httpchk_expect(struct server *s, int done);
Simon Hormane16c1b32015-01-30 11:22:57 +090065static int tcpcheck_get_step_id(struct check *);
Baptiste Assmann5ecb77f2013-10-06 23:24:13 +020066static void tcpcheck_main(struct connection *);
Willy Tarreaubd741542010-03-16 18:46:54 +010067
Simon Horman63a4a822012-03-19 07:24:41 +090068static const struct check_status check_statuses[HCHK_STATUS_SIZE] = {
Willy Tarreau6aaa1b82013-12-11 17:09:34 +010069 [HCHK_STATUS_UNKNOWN] = { CHK_RES_UNKNOWN, "UNK", "Unknown" },
70 [HCHK_STATUS_INI] = { CHK_RES_UNKNOWN, "INI", "Initializing" },
Krzysztof Piotr Oledzki213014e2009-09-27 15:50:02 +020071 [HCHK_STATUS_START] = { /* SPECIAL STATUS*/ },
Krzysztof Piotr Oledzki09605412009-09-23 22:09:24 +020072
Willy Tarreau23964182014-05-20 20:56:30 +020073 /* Below we have finished checks */
74 [HCHK_STATUS_CHECKED] = { CHK_RES_NEUTRAL, "CHECKED", "No status change" },
Willy Tarreau6aaa1b82013-12-11 17:09:34 +010075 [HCHK_STATUS_HANA] = { CHK_RES_FAILED, "HANA", "Health analyze" },
Krzysztof Piotr Oledzki97f07b82009-12-15 22:31:24 +010076
Willy Tarreau6aaa1b82013-12-11 17:09:34 +010077 [HCHK_STATUS_SOCKERR] = { CHK_RES_FAILED, "SOCKERR", "Socket error" },
Krzysztof Piotr Oledzki09605412009-09-23 22:09:24 +020078
Willy Tarreau6aaa1b82013-12-11 17:09:34 +010079 [HCHK_STATUS_L4OK] = { CHK_RES_PASSED, "L4OK", "Layer4 check passed" },
80 [HCHK_STATUS_L4TOUT] = { CHK_RES_FAILED, "L4TOUT", "Layer4 timeout" },
81 [HCHK_STATUS_L4CON] = { CHK_RES_FAILED, "L4CON", "Layer4 connection problem" },
Krzysztof Piotr Oledzki09605412009-09-23 22:09:24 +020082
Willy Tarreau6aaa1b82013-12-11 17:09:34 +010083 [HCHK_STATUS_L6OK] = { CHK_RES_PASSED, "L6OK", "Layer6 check passed" },
84 [HCHK_STATUS_L6TOUT] = { CHK_RES_FAILED, "L6TOUT", "Layer6 timeout" },
85 [HCHK_STATUS_L6RSP] = { CHK_RES_FAILED, "L6RSP", "Layer6 invalid response" },
Krzysztof Piotr Oledzki09605412009-09-23 22:09:24 +020086
Willy Tarreau6aaa1b82013-12-11 17:09:34 +010087 [HCHK_STATUS_L7TOUT] = { CHK_RES_FAILED, "L7TOUT", "Layer7 timeout" },
88 [HCHK_STATUS_L7RSP] = { CHK_RES_FAILED, "L7RSP", "Layer7 invalid response" },
Krzysztof Piotr Oledzki09605412009-09-23 22:09:24 +020089
Krzysztof Piotr Oledzki213014e2009-09-27 15:50:02 +020090 [HCHK_STATUS_L57DATA] = { /* DUMMY STATUS */ },
Krzysztof Piotr Oledzki09605412009-09-23 22:09:24 +020091
Willy Tarreau6aaa1b82013-12-11 17:09:34 +010092 [HCHK_STATUS_L7OKD] = { CHK_RES_PASSED, "L7OK", "Layer7 check passed" },
93 [HCHK_STATUS_L7OKCD] = { CHK_RES_CONDPASS, "L7OKC", "Layer7 check conditionally passed" },
94 [HCHK_STATUS_L7STS] = { CHK_RES_FAILED, "L7STS", "Layer7 wrong status" },
Simon Horman98637e52014-06-20 12:30:16 +090095
96 [HCHK_STATUS_PROCERR] = { CHK_RES_FAILED, "PROCERR", "External check error" },
97 [HCHK_STATUS_PROCTOUT] = { CHK_RES_FAILED, "PROCTOUT", "External check timeout" },
Cyril Bonté77010d82014-08-07 01:55:37 +020098 [HCHK_STATUS_PROCOK] = { CHK_RES_PASSED, "PROCOK", "External check passed" },
Krzysztof Piotr Oledzki09605412009-09-23 22:09:24 +020099};
100
Cyril Bontéac92a062014-12-27 22:28:38 +0100101const struct extcheck_env extcheck_envs[EXTCHK_SIZE] = {
102 [EXTCHK_PATH] = { "PATH", EXTCHK_SIZE_EVAL_INIT },
103 [EXTCHK_HAPROXY_PROXY_NAME] = { "HAPROXY_PROXY_NAME", EXTCHK_SIZE_EVAL_INIT },
104 [EXTCHK_HAPROXY_PROXY_ID] = { "HAPROXY_PROXY_ID", EXTCHK_SIZE_EVAL_INIT },
105 [EXTCHK_HAPROXY_PROXY_ADDR] = { "HAPROXY_PROXY_ADDR", EXTCHK_SIZE_EVAL_INIT },
106 [EXTCHK_HAPROXY_PROXY_PORT] = { "HAPROXY_PROXY_PORT", EXTCHK_SIZE_EVAL_INIT },
107 [EXTCHK_HAPROXY_SERVER_NAME] = { "HAPROXY_SERVER_NAME", EXTCHK_SIZE_EVAL_INIT },
108 [EXTCHK_HAPROXY_SERVER_ID] = { "HAPROXY_SERVER_ID", EXTCHK_SIZE_EVAL_INIT },
109 [EXTCHK_HAPROXY_SERVER_ADDR] = { "HAPROXY_SERVER_ADDR", EXTCHK_SIZE_EVAL_INIT },
110 [EXTCHK_HAPROXY_SERVER_PORT] = { "HAPROXY_SERVER_PORT", EXTCHK_SIZE_EVAL_INIT },
111 [EXTCHK_HAPROXY_SERVER_MAXCONN] = { "HAPROXY_SERVER_MAXCONN", EXTCHK_SIZE_EVAL_INIT },
112 [EXTCHK_HAPROXY_SERVER_CURCONN] = { "HAPROXY_SERVER_CURCONN", EXTCHK_SIZE_ULONG },
113};
114
Simon Horman63a4a822012-03-19 07:24:41 +0900115static const struct analyze_status analyze_statuses[HANA_STATUS_SIZE] = { /* 0: ignore, 1: error, 2: OK */
Krzysztof Piotr Oledzki97f07b82009-12-15 22:31:24 +0100116 [HANA_STATUS_UNKNOWN] = { "Unknown", { 0, 0 }},
117
118 [HANA_STATUS_L4_OK] = { "L4 successful connection", { 2, 0 }},
119 [HANA_STATUS_L4_ERR] = { "L4 unsuccessful connection", { 1, 1 }},
120
121 [HANA_STATUS_HTTP_OK] = { "Correct http response", { 0, 2 }},
122 [HANA_STATUS_HTTP_STS] = { "Wrong http response", { 0, 1 }},
123 [HANA_STATUS_HTTP_HDRRSP] = { "Invalid http response (headers)", { 0, 1 }},
124 [HANA_STATUS_HTTP_RSP] = { "Invalid http response", { 0, 1 }},
125
126 [HANA_STATUS_HTTP_READ_ERROR] = { "Read error (http)", { 0, 1 }},
127 [HANA_STATUS_HTTP_READ_TIMEOUT] = { "Read timeout (http)", { 0, 1 }},
128 [HANA_STATUS_HTTP_BROKEN_PIPE] = { "Close from server (http)", { 0, 1 }},
129};
130
Krzysztof Piotr Oledzki09605412009-09-23 22:09:24 +0200131/*
132 * Convert check_status code to description
133 */
134const char *get_check_status_description(short check_status) {
135
136 const char *desc;
137
138 if (check_status < HCHK_STATUS_SIZE)
Krzysztof Piotr Oledzki213014e2009-09-27 15:50:02 +0200139 desc = check_statuses[check_status].desc;
Krzysztof Piotr Oledzki09605412009-09-23 22:09:24 +0200140 else
141 desc = NULL;
142
143 if (desc && *desc)
144 return desc;
145 else
Krzysztof Piotr Oledzki213014e2009-09-27 15:50:02 +0200146 return check_statuses[HCHK_STATUS_UNKNOWN].desc;
Krzysztof Piotr Oledzki09605412009-09-23 22:09:24 +0200147}
148
149/*
150 * Convert check_status code to short info
151 */
152const char *get_check_status_info(short check_status) {
153
154 const char *info;
155
156 if (check_status < HCHK_STATUS_SIZE)
Krzysztof Piotr Oledzki213014e2009-09-27 15:50:02 +0200157 info = check_statuses[check_status].info;
Krzysztof Piotr Oledzki09605412009-09-23 22:09:24 +0200158 else
159 info = NULL;
160
161 if (info && *info)
162 return info;
163 else
Krzysztof Piotr Oledzki213014e2009-09-27 15:50:02 +0200164 return check_statuses[HCHK_STATUS_UNKNOWN].info;
Krzysztof Piotr Oledzki09605412009-09-23 22:09:24 +0200165}
166
Krzysztof Piotr Oledzki97f07b82009-12-15 22:31:24 +0100167const char *get_analyze_status(short analyze_status) {
168
169 const char *desc;
170
171 if (analyze_status < HANA_STATUS_SIZE)
172 desc = analyze_statuses[analyze_status].desc;
173 else
174 desc = NULL;
175
176 if (desc && *desc)
177 return desc;
178 else
179 return analyze_statuses[HANA_STATUS_UNKNOWN].desc;
180}
181
Willy Tarreaua150cf12014-05-20 21:57:23 +0200182/* Builds a string containing some information about the health check's result.
183 * The output string is allocated from the trash chunks. If the check is NULL,
184 * NULL is returned. This is designed to be used when emitting logs about health
185 * checks.
Willy Tarreauddd329c2014-05-16 16:46:12 +0200186 */
Willy Tarreaua150cf12014-05-20 21:57:23 +0200187static const char *check_reason_string(struct check *check)
Willy Tarreauddd329c2014-05-16 16:46:12 +0200188{
Willy Tarreaua150cf12014-05-20 21:57:23 +0200189 struct chunk *msg;
Krzysztof Piotr Oledzki99ab5f82009-09-27 17:28:21 +0200190
Willy Tarreaua150cf12014-05-20 21:57:23 +0200191 if (!check)
192 return NULL;
Krzysztof Piotr Oledzki99ab5f82009-09-27 17:28:21 +0200193
Willy Tarreaua150cf12014-05-20 21:57:23 +0200194 msg = get_trash_chunk();
195 chunk_printf(msg, "reason: %s", get_check_status_description(check->status));
Krzysztof Piotr Oledzki99ab5f82009-09-27 17:28:21 +0200196
Willy Tarreaua150cf12014-05-20 21:57:23 +0200197 if (check->status >= HCHK_STATUS_L57DATA)
198 chunk_appendf(msg, ", code: %d", check->code);
Krzysztof Piotr Oledzkif7089f52009-10-10 21:06:49 +0200199
Willy Tarreaua150cf12014-05-20 21:57:23 +0200200 if (*check->desc) {
201 struct chunk src;
Krzysztof Piotr Oledzkif7089f52009-10-10 21:06:49 +0200202
Willy Tarreaua150cf12014-05-20 21:57:23 +0200203 chunk_appendf(msg, ", info: \"");
Krzysztof Piotr Oledzkif7089f52009-10-10 21:06:49 +0200204
Willy Tarreaua150cf12014-05-20 21:57:23 +0200205 chunk_initlen(&src, check->desc, 0, strlen(check->desc));
206 chunk_asciiencode(msg, &src, '"');
Krzysztof Piotr Oledzkif7089f52009-10-10 21:06:49 +0200207
Willy Tarreaua150cf12014-05-20 21:57:23 +0200208 chunk_appendf(msg, "\"");
Krzysztof Piotr Oledzki99ab5f82009-09-27 17:28:21 +0200209 }
210
Willy Tarreaua150cf12014-05-20 21:57:23 +0200211 if (check->duration >= 0)
212 chunk_appendf(msg, ", check duration: %ldms", check->duration);
213
214 return msg->str;
Krzysztof Piotr Oledzki99ab5f82009-09-27 17:28:21 +0200215}
216
Krzysztof Piotr Oledzki09605412009-09-23 22:09:24 +0200217/*
Simon Horman4a741432013-02-23 15:35:38 +0900218 * Set check->status, update check->duration and fill check->result with
Willy Tarreau7b1d47c2014-05-20 14:55:13 +0200219 * an adequate CHK_RES_* value. The new check->health is computed based
220 * on the result.
Krzysztof Piotr Oledzki213014e2009-09-27 15:50:02 +0200221 *
222 * Show information in logs about failed health check if server is UP
223 * or succeeded health checks if server is DOWN.
Krzysztof Piotr Oledzki09605412009-09-23 22:09:24 +0200224 */
Simon Horman4a741432013-02-23 15:35:38 +0900225static void set_server_check_status(struct check *check, short status, const char *desc)
Willy Tarreau19d14ef2012-10-29 16:51:55 +0100226{
Simon Horman4a741432013-02-23 15:35:38 +0900227 struct server *s = check->server;
Willy Tarreaubef1b322014-05-13 21:01:39 +0200228 short prev_status = check->status;
Willy Tarreau7b1d47c2014-05-20 14:55:13 +0200229 int report = 0;
Simon Horman4a741432013-02-23 15:35:38 +0900230
Krzysztof Piotr Oledzki213014e2009-09-27 15:50:02 +0200231 if (status == HCHK_STATUS_START) {
Willy Tarreau6aaa1b82013-12-11 17:09:34 +0100232 check->result = CHK_RES_UNKNOWN; /* no result yet */
Simon Horman4a741432013-02-23 15:35:38 +0900233 check->desc[0] = '\0';
234 check->start = now;
Krzysztof Piotr Oledzki213014e2009-09-27 15:50:02 +0200235 return;
236 }
237
Simon Horman4a741432013-02-23 15:35:38 +0900238 if (!check->status)
Krzysztof Piotr Oledzki213014e2009-09-27 15:50:02 +0200239 return;
240
Krzysztof Piotr Oledzkif7089f52009-10-10 21:06:49 +0200241 if (desc && *desc) {
Simon Horman4a741432013-02-23 15:35:38 +0900242 strncpy(check->desc, desc, HCHK_DESC_LEN-1);
243 check->desc[HCHK_DESC_LEN-1] = '\0';
Krzysztof Piotr Oledzkif7089f52009-10-10 21:06:49 +0200244 } else
Simon Horman4a741432013-02-23 15:35:38 +0900245 check->desc[0] = '\0';
Krzysztof Piotr Oledzkif7089f52009-10-10 21:06:49 +0200246
Simon Horman4a741432013-02-23 15:35:38 +0900247 check->status = status;
Krzysztof Piotr Oledzki213014e2009-09-27 15:50:02 +0200248 if (check_statuses[status].result)
Simon Horman4a741432013-02-23 15:35:38 +0900249 check->result = check_statuses[status].result;
Krzysztof Piotr Oledzki09605412009-09-23 22:09:24 +0200250
Krzysztof Piotr Oledzki97f07b82009-12-15 22:31:24 +0100251 if (status == HCHK_STATUS_HANA)
Simon Horman4a741432013-02-23 15:35:38 +0900252 check->duration = -1;
253 else if (!tv_iszero(&check->start)) {
Krzysztof Piotr Oledzki213014e2009-09-27 15:50:02 +0200254 /* set_server_check_status() may be called more than once */
Simon Horman4a741432013-02-23 15:35:38 +0900255 check->duration = tv_ms_elapsed(&check->start, &now);
256 tv_zero(&check->start);
Krzysztof Piotr Oledzki213014e2009-09-27 15:50:02 +0200257 }
258
Willy Tarreau23964182014-05-20 20:56:30 +0200259 /* no change is expected if no state change occurred */
260 if (check->result == CHK_RES_NEUTRAL)
261 return;
262
Willy Tarreau7b1d47c2014-05-20 14:55:13 +0200263 report = 0;
Krzysztof Piotr Oledzki213014e2009-09-27 15:50:02 +0200264
Willy Tarreau7b1d47c2014-05-20 14:55:13 +0200265 switch (check->result) {
266 case CHK_RES_FAILED:
Willy Tarreau12634e12014-05-23 11:32:36 +0200267 /* Failure to connect to the agent as a secondary check should not
268 * cause the server to be marked down.
269 */
270 if ((!(check->state & CHK_ST_AGENT) ||
Simon Hormaneaabd522015-02-26 11:26:17 +0900271 (check->status >= HCHK_STATUS_L57DATA)) &&
Willy Tarreau12634e12014-05-23 11:32:36 +0200272 (check->health >= check->rise)) {
Willy Tarreau7b1d47c2014-05-20 14:55:13 +0200273 s->counters.failed_checks++;
274 report = 1;
275 check->health--;
276 if (check->health < check->rise)
277 check->health = 0;
278 }
279 break;
Krzysztof Piotr Oledzki213014e2009-09-27 15:50:02 +0200280
Willy Tarreau7b1d47c2014-05-20 14:55:13 +0200281 case CHK_RES_PASSED:
282 case CHK_RES_CONDPASS: /* "condpass" cannot make the first step but it OK after a "passed" */
283 if ((check->health < check->rise + check->fall - 1) &&
284 (check->result == CHK_RES_PASSED || check->health > 0)) {
285 report = 1;
286 check->health++;
Krzysztof Piotr Oledzki213014e2009-09-27 15:50:02 +0200287
Willy Tarreau7b1d47c2014-05-20 14:55:13 +0200288 if (check->health >= check->rise)
289 check->health = check->rise + check->fall - 1; /* OK now */
290 }
Krzysztof Piotr Oledzki213014e2009-09-27 15:50:02 +0200291
Willy Tarreau7b1d47c2014-05-20 14:55:13 +0200292 /* clear consecutive_errors if observing is enabled */
293 if (s->onerror)
294 s->consecutive_errors = 0;
295 break;
Krzysztof Piotr Oledzki97f07b82009-12-15 22:31:24 +0100296
Willy Tarreau7b1d47c2014-05-20 14:55:13 +0200297 default:
298 break;
299 }
Krzysztof Piotr Oledzki213014e2009-09-27 15:50:02 +0200300
Willy Tarreau7b1d47c2014-05-20 14:55:13 +0200301 if (s->proxy->options2 & PR_O2_LOGHCHKS &&
302 (status != prev_status || report)) {
303 chunk_printf(&trash,
Willy Tarreau12634e12014-05-23 11:32:36 +0200304 "%s check for %sserver %s/%s %s%s",
305 (check->state & CHK_ST_AGENT) ? "Agent" : "Health",
Willy Tarreauc93cd162014-05-13 15:54:22 +0200306 s->flags & SRV_F_BACKUP ? "backup " : "",
Willy Tarreau19d14ef2012-10-29 16:51:55 +0100307 s->proxy->id, s->id,
Willy Tarreau6aaa1b82013-12-11 17:09:34 +0100308 (check->result == CHK_RES_CONDPASS) ? "conditionally ":"",
Willy Tarreau7b1d47c2014-05-20 14:55:13 +0200309 (check->result >= CHK_RES_PASSED) ? "succeeded" : "failed");
Krzysztof Piotr Oledzki213014e2009-09-27 15:50:02 +0200310
Willy Tarreaua150cf12014-05-20 21:57:23 +0200311 srv_append_status(&trash, s, check_reason_string(check), -1, 0);
Krzysztof Piotr Oledzki213014e2009-09-27 15:50:02 +0200312
Willy Tarreau19d14ef2012-10-29 16:51:55 +0100313 chunk_appendf(&trash, ", status: %d/%d %s",
Willy Tarreau7b1d47c2014-05-20 14:55:13 +0200314 (check->health >= check->rise) ? check->health - check->rise + 1 : check->health,
315 (check->health >= check->rise) ? check->fall : check->rise,
316 (check->health >= check->rise) ? (s->uweight ? "UP" : "DRAIN") : "DOWN");
Krzysztof Piotr Oledzki213014e2009-09-27 15:50:02 +0200317
Willy Tarreau19d14ef2012-10-29 16:51:55 +0100318 Warning("%s.\n", trash.str);
319 send_log(s->proxy, LOG_NOTICE, "%s.\n", trash.str);
Simon Horman64e34162015-02-06 11:11:57 +0900320 send_email_alert(s, LOG_NOTICE, "%s", trash.str);
Krzysztof Piotr Oledzki213014e2009-09-27 15:50:02 +0200321 }
Krzysztof Piotr Oledzki09605412009-09-23 22:09:24 +0200322}
323
Willy Tarreau4eec5472014-05-20 22:32:27 +0200324/* Marks the check <check>'s server down if the current check is already failed
325 * and the server is not down yet nor in maintenance.
Willy Tarreaubaaee002006-06-26 02:48:02 +0200326 */
Willy Tarreau4eec5472014-05-20 22:32:27 +0200327static void check_notify_failure(struct check *check)
Willy Tarreaubaaee002006-06-26 02:48:02 +0200328{
Simon Horman4a741432013-02-23 15:35:38 +0900329 struct server *s = check->server;
Simon Hormane0d1bfb2011-06-21 14:34:58 +0900330
Willy Tarreau7b1d47c2014-05-20 14:55:13 +0200331 /* The agent secondary check should only cause a server to be marked
332 * as down if check->status is HCHK_STATUS_L7STS, which indicates
333 * that the agent returned "fail", "stopped" or "down".
334 * The implication here is that failure to connect to the agent
335 * as a secondary check should not cause the server to be marked
336 * down. */
337 if ((check->state & CHK_ST_AGENT) && check->status != HCHK_STATUS_L7STS)
338 return;
339
Willy Tarreau4eec5472014-05-20 22:32:27 +0200340 if (check->health > 0)
341 return;
Krzysztof Piotr Oledzkic8b16fc2008-02-18 01:26:35 +0100342
Willy Tarreau4eec5472014-05-20 22:32:27 +0200343 /* We only report a reason for the check if we did not do so previously */
344 srv_set_stopped(s, (!s->track && !(s->proxy->options2 & PR_O2_LOGHCHKS)) ? check_reason_string(check) : NULL);
Willy Tarreaubaaee002006-06-26 02:48:02 +0200345}
346
Willy Tarreauaf549582014-05-16 17:37:50 +0200347/* Marks the check <check> as valid and tries to set its server up, provided
Willy Tarreau3e048382014-05-21 10:30:54 +0200348 * it isn't in maintenance, it is not tracking a down server and other checks
349 * comply. The rule is simple : by default, a server is up, unless any of the
350 * following conditions is true :
351 * - health check failed (check->health < rise)
352 * - agent check failed (agent->health < rise)
353 * - the server tracks a down server (track && track->state == STOPPED)
354 * Note that if the server has a slowstart, it will switch to STARTING instead
355 * of RUNNING. Also, only the health checks support the nolb mode, so the
356 * agent's success may not take the server out of this mode.
Willy Tarreauaf549582014-05-16 17:37:50 +0200357 */
Willy Tarreau3e048382014-05-21 10:30:54 +0200358static void check_notify_success(struct check *check)
Willy Tarreauaf549582014-05-16 17:37:50 +0200359{
Simon Horman4a741432013-02-23 15:35:38 +0900360 struct server *s = check->server;
Krzysztof Piotr Oledzkic8b16fc2008-02-18 01:26:35 +0100361
Willy Tarreauaf549582014-05-16 17:37:50 +0200362 if (s->admin & SRV_ADMF_MAINT)
363 return;
Cyril Bontécd19e512010-01-31 22:34:03 +0100364
Willy Tarreau3e048382014-05-21 10:30:54 +0200365 if (s->track && s->track->state == SRV_ST_STOPPED)
Willy Tarreauaf549582014-05-16 17:37:50 +0200366 return;
Krzysztof Piotr Oledzkic8b16fc2008-02-18 01:26:35 +0100367
Willy Tarreau3e048382014-05-21 10:30:54 +0200368 if ((s->check.state & CHK_ST_ENABLED) && (s->check.health < s->check.rise))
369 return;
Krzysztof Piotr Oledzkic8b16fc2008-02-18 01:26:35 +0100370
Willy Tarreau3e048382014-05-21 10:30:54 +0200371 if ((s->agent.state & CHK_ST_ENABLED) && (s->agent.health < s->agent.rise))
372 return;
Willy Tarreauaf549582014-05-16 17:37:50 +0200373
Willy Tarreau3e048382014-05-21 10:30:54 +0200374 if ((check->state & CHK_ST_AGENT) && s->state == SRV_ST_STOPPING)
375 return;
Krzysztof Piotr Oledzkic8b16fc2008-02-18 01:26:35 +0100376
Willy Tarreau3e048382014-05-21 10:30:54 +0200377 srv_set_running(s, (!s->track && !(s->proxy->options2 & PR_O2_LOGHCHKS)) ? check_reason_string(check) : NULL);
Krzysztof Piotr Oledzkic8b16fc2008-02-18 01:26:35 +0100378}
379
Willy Tarreaudb58b792014-05-21 13:57:23 +0200380/* Marks the check <check> as valid and tries to set its server into stopping mode
381 * if it was running or starting, and provided it isn't in maintenance and other
382 * checks comply. The conditions for the server to be marked in stopping mode are
383 * the same as for it to be turned up. Also, only the health checks support the
384 * nolb mode.
Willy Tarreauaf549582014-05-16 17:37:50 +0200385 */
Willy Tarreaudb58b792014-05-21 13:57:23 +0200386static void check_notify_stopping(struct check *check)
Willy Tarreauaf549582014-05-16 17:37:50 +0200387{
Simon Horman4a741432013-02-23 15:35:38 +0900388 struct server *s = check->server;
Krzysztof Piotr Oledzkic8b16fc2008-02-18 01:26:35 +0100389
Willy Tarreauaf549582014-05-16 17:37:50 +0200390 if (s->admin & SRV_ADMF_MAINT)
391 return;
392
Willy Tarreaudb58b792014-05-21 13:57:23 +0200393 if (check->state & CHK_ST_AGENT)
394 return;
Krzysztof Piotr Oledzkic8b16fc2008-02-18 01:26:35 +0100395
Willy Tarreaudb58b792014-05-21 13:57:23 +0200396 if (s->track && s->track->state == SRV_ST_STOPPED)
397 return;
Krzysztof Piotr Oledzkic8b16fc2008-02-18 01:26:35 +0100398
Willy Tarreaudb58b792014-05-21 13:57:23 +0200399 if ((s->check.state & CHK_ST_ENABLED) && (s->check.health < s->check.rise))
400 return;
Krzysztof Piotr Oledzkic8b16fc2008-02-18 01:26:35 +0100401
Willy Tarreaudb58b792014-05-21 13:57:23 +0200402 if ((s->agent.state & CHK_ST_ENABLED) && (s->agent.health < s->agent.rise))
403 return;
Krzysztof Piotr Oledzkic8b16fc2008-02-18 01:26:35 +0100404
Willy Tarreaudb58b792014-05-21 13:57:23 +0200405 srv_set_stopping(s, (!s->track && !(s->proxy->options2 & PR_O2_LOGHCHKS)) ? check_reason_string(check) : NULL);
Krzysztof Piotr Oledzkic8b16fc2008-02-18 01:26:35 +0100406}
Willy Tarreaubaaee002006-06-26 02:48:02 +0200407
Willy Tarreau9fe7aae2013-12-31 23:47:37 +0100408/* note: use health_adjust() only, which first checks that the observe mode is
409 * enabled.
410 */
411void __health_adjust(struct server *s, short status)
Willy Tarreau19d14ef2012-10-29 16:51:55 +0100412{
Krzysztof Piotr Oledzki97f07b82009-12-15 22:31:24 +0100413 int failed;
414 int expire;
415
Krzysztof Piotr Oledzki97f07b82009-12-15 22:31:24 +0100416 if (s->observe >= HANA_OBS_SIZE)
417 return;
418
Willy Tarreaubb956662013-01-24 00:37:39 +0100419 if (status >= HANA_STATUS_SIZE || !analyze_statuses[status].desc)
Krzysztof Piotr Oledzki97f07b82009-12-15 22:31:24 +0100420 return;
421
422 switch (analyze_statuses[status].lr[s->observe - 1]) {
423 case 1:
424 failed = 1;
425 break;
426
427 case 2:
428 failed = 0;
429 break;
430
431 default:
432 return;
433 }
434
435 if (!failed) {
436 /* good: clear consecutive_errors */
437 s->consecutive_errors = 0;
438 return;
439 }
440
441 s->consecutive_errors++;
442
443 if (s->consecutive_errors < s->consecutive_errors_limit)
444 return;
445
Willy Tarreau19d14ef2012-10-29 16:51:55 +0100446 chunk_printf(&trash, "Detected %d consecutive errors, last one was: %s",
447 s->consecutive_errors, get_analyze_status(status));
Krzysztof Piotr Oledzki97f07b82009-12-15 22:31:24 +0100448
449 switch (s->onerror) {
450 case HANA_ONERR_FASTINTER:
451 /* force fastinter - nothing to do here as all modes force it */
452 break;
453
454 case HANA_ONERR_SUDDTH:
455 /* simulate a pre-fatal failed health check */
Simon Horman58c32972013-11-25 10:46:38 +0900456 if (s->check.health > s->check.rise)
457 s->check.health = s->check.rise + 1;
Krzysztof Piotr Oledzki97f07b82009-12-15 22:31:24 +0100458
459 /* no break - fall through */
460
461 case HANA_ONERR_FAILCHK:
462 /* simulate a failed health check */
Simon Horman4a741432013-02-23 15:35:38 +0900463 set_server_check_status(&s->check, HCHK_STATUS_HANA, trash.str);
Willy Tarreau4eec5472014-05-20 22:32:27 +0200464 check_notify_failure(&s->check);
Krzysztof Piotr Oledzki97f07b82009-12-15 22:31:24 +0100465 break;
466
467 case HANA_ONERR_MARKDWN:
468 /* mark server down */
Simon Horman58c32972013-11-25 10:46:38 +0900469 s->check.health = s->check.rise;
Simon Horman4a741432013-02-23 15:35:38 +0900470 set_server_check_status(&s->check, HCHK_STATUS_HANA, trash.str);
Willy Tarreau4eec5472014-05-20 22:32:27 +0200471 check_notify_failure(&s->check);
Krzysztof Piotr Oledzki97f07b82009-12-15 22:31:24 +0100472 break;
473
474 default:
475 /* write a warning? */
476 break;
477 }
478
479 s->consecutive_errors = 0;
480 s->counters.failed_hana++;
481
Simon Horman66183002013-02-23 10:16:43 +0900482 if (s->check.fastinter) {
483 expire = tick_add(now_ms, MS_TO_TICKS(s->check.fastinter));
Sergiy Prykhodko1d57e502013-09-21 12:05:00 +0300484 if (s->check.task->expire > expire) {
Willy Tarreau5b3a2022012-09-28 15:01:02 +0200485 s->check.task->expire = expire;
Sergiy Prykhodko1d57e502013-09-21 12:05:00 +0300486 /* requeue check task with new expire */
487 task_queue(s->check.task);
488 }
Krzysztof Piotr Oledzki97f07b82009-12-15 22:31:24 +0100489 }
490}
491
Willy Tarreaua1dab552014-04-14 15:04:54 +0200492static int httpchk_build_status_header(struct server *s, char *buffer, int size)
Willy Tarreauef781042010-01-27 11:53:01 +0100493{
494 int sv_state;
495 int ratio;
496 int hlen = 0;
497 const char *srv_hlt_st[7] = { "DOWN", "DOWN %d/%d",
498 "UP %d/%d", "UP",
499 "NOLB %d/%d", "NOLB",
500 "no check" };
501
502 memcpy(buffer + hlen, "X-Haproxy-Server-State: ", 24);
503 hlen += 24;
504
Willy Tarreauff5ae352013-12-11 20:36:34 +0100505 if (!(s->check.state & CHK_ST_ENABLED))
506 sv_state = 6;
Willy Tarreau892337c2014-05-13 23:41:20 +0200507 else if (s->state != SRV_ST_STOPPED) {
Simon Horman58c32972013-11-25 10:46:38 +0900508 if (s->check.health == s->check.rise + s->check.fall - 1)
Willy Tarreauef781042010-01-27 11:53:01 +0100509 sv_state = 3; /* UP */
510 else
511 sv_state = 2; /* going down */
512
Willy Tarreau892337c2014-05-13 23:41:20 +0200513 if (s->state == SRV_ST_STOPPING)
Willy Tarreauef781042010-01-27 11:53:01 +0100514 sv_state += 2;
515 } else {
Simon Horman125d0992013-02-24 17:23:38 +0900516 if (s->check.health)
Willy Tarreauef781042010-01-27 11:53:01 +0100517 sv_state = 1; /* going up */
518 else
519 sv_state = 0; /* DOWN */
520 }
521
Willy Tarreaua1dab552014-04-14 15:04:54 +0200522 hlen += snprintf(buffer + hlen, size - hlen,
Willy Tarreauef781042010-01-27 11:53:01 +0100523 srv_hlt_st[sv_state],
Willy Tarreau892337c2014-05-13 23:41:20 +0200524 (s->state != SRV_ST_STOPPED) ? (s->check.health - s->check.rise + 1) : (s->check.health),
525 (s->state != SRV_ST_STOPPED) ? (s->check.fall) : (s->check.rise));
Willy Tarreauef781042010-01-27 11:53:01 +0100526
Willy Tarreaua1dab552014-04-14 15:04:54 +0200527 hlen += snprintf(buffer + hlen, size - hlen, "; name=%s/%s; node=%s; weight=%d/%d; scur=%d/%d; qcur=%d",
Willy Tarreauef781042010-01-27 11:53:01 +0100528 s->proxy->id, s->id,
529 global.node,
530 (s->eweight * s->proxy->lbprm.wmult + s->proxy->lbprm.wdiv - 1) / s->proxy->lbprm.wdiv,
531 (s->proxy->lbprm.tot_weight * s->proxy->lbprm.wmult + s->proxy->lbprm.wdiv - 1) / s->proxy->lbprm.wdiv,
532 s->cur_sess, s->proxy->beconn - s->proxy->nbpend,
533 s->nbpend);
534
Willy Tarreau892337c2014-05-13 23:41:20 +0200535 if ((s->state == SRV_ST_STARTING) &&
Willy Tarreauef781042010-01-27 11:53:01 +0100536 now.tv_sec < s->last_change + s->slowstart &&
537 now.tv_sec >= s->last_change) {
538 ratio = MAX(1, 100 * (now.tv_sec - s->last_change) / s->slowstart);
Willy Tarreaua1dab552014-04-14 15:04:54 +0200539 hlen += snprintf(buffer + hlen, size - hlen, "; throttle=%d%%", ratio);
Willy Tarreauef781042010-01-27 11:53:01 +0100540 }
541
542 buffer[hlen++] = '\r';
543 buffer[hlen++] = '\n';
544
545 return hlen;
546}
547
Willy Tarreau20a18342013-12-05 00:31:46 +0100548/* Check the connection. If an error has already been reported or the socket is
549 * closed, keep errno intact as it is supposed to contain the valid error code.
550 * If no error is reported, check the socket's error queue using getsockopt().
551 * Warning, this must be done only once when returning from poll, and never
552 * after an I/O error was attempted, otherwise the error queue might contain
553 * inconsistent errors. If an error is detected, the CO_FL_ERROR is set on the
554 * socket. Returns non-zero if an error was reported, zero if everything is
555 * clean (including a properly closed socket).
556 */
557static int retrieve_errno_from_socket(struct connection *conn)
558{
559 int skerr;
560 socklen_t lskerr = sizeof(skerr);
561
562 if (conn->flags & CO_FL_ERROR && ((errno && errno != EAGAIN) || !conn->ctrl))
563 return 1;
564
Willy Tarreau3c728722014-01-23 13:50:42 +0100565 if (!conn_ctrl_ready(conn))
Willy Tarreau20a18342013-12-05 00:31:46 +0100566 return 0;
567
568 if (getsockopt(conn->t.sock.fd, SOL_SOCKET, SO_ERROR, &skerr, &lskerr) == 0)
569 errno = skerr;
570
571 if (errno == EAGAIN)
572 errno = 0;
573
574 if (!errno) {
575 /* we could not retrieve an error, that does not mean there is
576 * none. Just don't change anything and only report the prior
577 * error if any.
578 */
579 if (conn->flags & CO_FL_ERROR)
580 return 1;
581 else
582 return 0;
583 }
584
585 conn->flags |= CO_FL_ERROR | CO_FL_SOCK_WR_SH | CO_FL_SOCK_RD_SH;
586 return 1;
587}
588
Willy Tarreau25e2ab52013-12-04 11:17:05 +0100589/* Try to collect as much information as possible on the connection status,
590 * and adjust the server status accordingly. It may make use of <errno_bck>
591 * if non-null when the caller is absolutely certain of its validity (eg:
592 * checked just after a syscall). If the caller doesn't have a valid errno,
593 * it can pass zero, and retrieve_errno_from_socket() will be called to try
594 * to extract errno from the socket. If no error is reported, it will consider
595 * the <expired> flag. This is intended to be used when a connection error was
596 * reported in conn->flags or when a timeout was reported in <expired>. The
597 * function takes care of not updating a server status which was already set.
598 * All situations where at least one of <expired> or CO_FL_ERROR are set
599 * produce a status.
600 */
601static void chk_report_conn_err(struct connection *conn, int errno_bck, int expired)
602{
603 struct check *check = conn->owner;
604 const char *err_msg;
Baptiste Assmann5ecb77f2013-10-06 23:24:13 +0200605 struct chunk *chk;
Willy Tarreau213c6782014-10-02 14:51:02 +0200606 int step;
Willy Tarreau25e2ab52013-12-04 11:17:05 +0100607
Willy Tarreau6aaa1b82013-12-11 17:09:34 +0100608 if (check->result != CHK_RES_UNKNOWN)
Willy Tarreau25e2ab52013-12-04 11:17:05 +0100609 return;
610
611 errno = errno_bck;
612 if (!errno || errno == EAGAIN)
613 retrieve_errno_from_socket(conn);
614
615 if (!(conn->flags & CO_FL_ERROR) && !expired)
616 return;
617
618 /* we'll try to build a meaningful error message depending on the
619 * context of the error possibly present in conn->err_code, and the
620 * socket error possibly collected above. This is useful to know the
621 * exact step of the L6 layer (eg: SSL handshake).
622 */
Baptiste Assmann5ecb77f2013-10-06 23:24:13 +0200623 chk = get_trash_chunk();
624
625 if (check->type == PR_O2_TCPCHK_CHK) {
Simon Hormane16c1b32015-01-30 11:22:57 +0900626 step = tcpcheck_get_step_id(check);
Willy Tarreau213c6782014-10-02 14:51:02 +0200627 if (!step)
628 chunk_printf(chk, " at initial connection step of tcp-check");
629 else {
630 chunk_printf(chk, " at step %d of tcp-check", step);
631 /* we were looking for a string */
632 if (check->last_started_step && check->last_started_step->action == TCPCHK_ACT_CONNECT) {
633 if (check->last_started_step->port)
634 chunk_appendf(chk, " (connect port %d)" ,check->last_started_step->port);
635 else
636 chunk_appendf(chk, " (connect)");
637 }
638 else if (check->last_started_step && check->last_started_step->action == TCPCHK_ACT_EXPECT) {
639 if (check->last_started_step->string)
640 chunk_appendf(chk, " (string '%s')", check->last_started_step->string);
641 else if (check->last_started_step->expect_regex)
642 chunk_appendf(chk, " (expect regex)");
643 }
644 else if (check->last_started_step && check->last_started_step->action == TCPCHK_ACT_SEND) {
645 chunk_appendf(chk, " (send)");
646 }
Baptiste Assmann5ecb77f2013-10-06 23:24:13 +0200647 }
648 }
649
Willy Tarreau25e2ab52013-12-04 11:17:05 +0100650 if (conn->err_code) {
651 if (errno && errno != EAGAIN)
Baptiste Assmann5ecb77f2013-10-06 23:24:13 +0200652 chunk_printf(&trash, "%s (%s)%s", conn_err_code_str(conn), strerror(errno), chk->str);
Willy Tarreau25e2ab52013-12-04 11:17:05 +0100653 else
Baptiste Assmann5ecb77f2013-10-06 23:24:13 +0200654 chunk_printf(&trash, "%s%s", conn_err_code_str(conn), chk->str);
Willy Tarreau25e2ab52013-12-04 11:17:05 +0100655 err_msg = trash.str;
656 }
657 else {
658 if (errno && errno != EAGAIN) {
Baptiste Assmann5ecb77f2013-10-06 23:24:13 +0200659 chunk_printf(&trash, "%s%s", strerror(errno), chk->str);
Willy Tarreau25e2ab52013-12-04 11:17:05 +0100660 err_msg = trash.str;
661 }
662 else {
Baptiste Assmann5ecb77f2013-10-06 23:24:13 +0200663 err_msg = chk->str;
Willy Tarreau25e2ab52013-12-04 11:17:05 +0100664 }
665 }
666
667 if ((conn->flags & (CO_FL_CONNECTED|CO_FL_WAIT_L4_CONN)) == CO_FL_WAIT_L4_CONN) {
668 /* L4 not established (yet) */
669 if (conn->flags & CO_FL_ERROR)
670 set_server_check_status(check, HCHK_STATUS_L4CON, err_msg);
671 else if (expired)
672 set_server_check_status(check, HCHK_STATUS_L4TOUT, err_msg);
673 }
674 else if ((conn->flags & (CO_FL_CONNECTED|CO_FL_WAIT_L6_CONN)) == CO_FL_WAIT_L6_CONN) {
675 /* L6 not established (yet) */
676 if (conn->flags & CO_FL_ERROR)
677 set_server_check_status(check, HCHK_STATUS_L6RSP, err_msg);
678 else if (expired)
679 set_server_check_status(check, HCHK_STATUS_L6TOUT, err_msg);
680 }
681 else if (conn->flags & CO_FL_ERROR) {
682 /* I/O error after connection was established and before we could diagnose */
683 set_server_check_status(check, HCHK_STATUS_SOCKERR, err_msg);
684 }
685 else if (expired) {
686 /* connection established but expired check */
687 if (check->type == PR_O2_SSL3_CHK)
688 set_server_check_status(check, HCHK_STATUS_L6TOUT, err_msg);
689 else /* HTTP, SMTP, ... */
690 set_server_check_status(check, HCHK_STATUS_L7TOUT, err_msg);
691 }
692
693 return;
694}
695
Willy Tarreaubaaee002006-06-26 02:48:02 +0200696/*
697 * This function is used only for server health-checks. It handles
Krzysztof Piotr Oledzki213014e2009-09-27 15:50:02 +0200698 * the connection acknowledgement. If the proxy requires L7 health-checks,
699 * it sends the request. In other cases, it calls set_server_check_status()
Simon Horman4a741432013-02-23 15:35:38 +0900700 * to set check->status, check->duration and check->result.
Willy Tarreaubaaee002006-06-26 02:48:02 +0200701 */
Willy Tarreaufb56aab2012-09-28 14:40:02 +0200702static void event_srv_chk_w(struct connection *conn)
Willy Tarreaubaaee002006-06-26 02:48:02 +0200703{
Simon Horman4a741432013-02-23 15:35:38 +0900704 struct check *check = conn->owner;
705 struct server *s = check->server;
Simon Horman4a741432013-02-23 15:35:38 +0900706 struct task *t = check->task;
Willy Tarreaufb56aab2012-09-28 14:40:02 +0200707
Willy Tarreau6aaa1b82013-12-11 17:09:34 +0100708 if (unlikely(check->result == CHK_RES_FAILED))
Willy Tarreau25e2ab52013-12-04 11:17:05 +0100709 goto out_wakeup;
710
Willy Tarreau310987a2014-01-22 19:46:33 +0100711 if (conn->flags & CO_FL_HANDSHAKE)
Willy Tarreau25e2ab52013-12-04 11:17:05 +0100712 return;
713
Willy Tarreau20a18342013-12-05 00:31:46 +0100714 if (retrieve_errno_from_socket(conn)) {
Willy Tarreau25e2ab52013-12-04 11:17:05 +0100715 chk_report_conn_err(conn, errno, 0);
Willy Tarreau20a18342013-12-05 00:31:46 +0100716 __conn_data_stop_both(conn);
717 goto out_wakeup;
718 }
Krzysztof Piotr Oledzki6492db52010-01-02 22:03:01 +0100719
Willy Tarreau25e2ab52013-12-04 11:17:05 +0100720 if (conn->flags & (CO_FL_SOCK_WR_SH | CO_FL_DATA_WR_SH)) {
Willy Tarreau20a18342013-12-05 00:31:46 +0100721 /* if the output is closed, we can't do anything */
722 conn->flags |= CO_FL_ERROR;
Willy Tarreau25e2ab52013-12-04 11:17:05 +0100723 chk_report_conn_err(conn, 0, 0);
Willy Tarreau20a18342013-12-05 00:31:46 +0100724 goto out_wakeup;
Krzysztof Piotr Oledzki09605412009-09-23 22:09:24 +0200725 }
Willy Tarreau6996e152007-04-30 14:37:43 +0200726
Willy Tarreau06559ac2013-12-05 01:53:08 +0100727 /* here, we know that the connection is established. That's enough for
728 * a pure TCP check.
729 */
730 if (!check->type)
731 goto out_wakeup;
732
Baptiste Assmann5ecb77f2013-10-06 23:24:13 +0200733 if (check->type == PR_O2_TCPCHK_CHK) {
734 tcpcheck_main(conn);
735 return;
736 }
737
Willy Tarreau25e2ab52013-12-04 11:17:05 +0100738 if (check->bo->o) {
Willy Tarreau1049b1f2014-02-02 01:51:17 +0100739 conn->xprt->snd_buf(conn, check->bo, 0);
Willy Tarreau25e2ab52013-12-04 11:17:05 +0100740 if (conn->flags & CO_FL_ERROR) {
741 chk_report_conn_err(conn, errno, 0);
742 __conn_data_stop_both(conn);
743 goto out_wakeup;
Willy Tarreaubaaee002006-06-26 02:48:02 +0200744 }
Willy Tarreau25e2ab52013-12-04 11:17:05 +0100745 if (check->bo->o)
746 return;
747 }
Willy Tarreau6996e152007-04-30 14:37:43 +0200748
Willy Tarreau25e2ab52013-12-04 11:17:05 +0100749 /* full request sent, we allow up to <timeout.check> if nonzero for a response */
750 if (s->proxy->timeout.check) {
751 t->expire = tick_add_ifset(now_ms, s->proxy->timeout.check);
752 task_queue(t);
Willy Tarreaubaaee002006-06-26 02:48:02 +0200753 }
Willy Tarreau25e2ab52013-12-04 11:17:05 +0100754 goto out_nowake;
755
Willy Tarreau83749182007-04-15 20:56:27 +0200756 out_wakeup:
Willy Tarreaufdccded2008-08-29 18:19:04 +0200757 task_wakeup(t, TASK_WOKEN_IO);
Willy Tarreau83749182007-04-15 20:56:27 +0200758 out_nowake:
Willy Tarreaufb56aab2012-09-28 14:40:02 +0200759 __conn_data_stop_send(conn); /* nothing more to write */
Willy Tarreaubaaee002006-06-26 02:48:02 +0200760}
761
Willy Tarreaubaaee002006-06-26 02:48:02 +0200762/*
Willy Tarreauf3c69202006-07-09 16:42:34 +0200763 * This function is used only for server health-checks. It handles the server's
Hervé COMMOWICK8776f1b2010-10-18 15:58:36 +0200764 * reply to an HTTP request, SSL HELLO or MySQL client Auth. It calls
Simon Horman4a741432013-02-23 15:35:38 +0900765 * set_server_check_status() to update check->status, check->duration
766 * and check->result.
Krzysztof Piotr Oledzki213014e2009-09-27 15:50:02 +0200767
768 * The set_server_check_status function is called with HCHK_STATUS_L7OKD if
769 * an HTTP server replies HTTP 2xx or 3xx (valid responses), if an SMTP server
770 * returns 2xx, HCHK_STATUS_L6OK if an SSL server returns at least 5 bytes in
771 * response to an SSL HELLO (the principle is that this is enough to
772 * distinguish between an SSL server and a pure TCP relay). All other cases will
773 * call it with a proper error status like HCHK_STATUS_L7STS, HCHK_STATUS_L6RSP,
774 * etc.
Willy Tarreaubaaee002006-06-26 02:48:02 +0200775 */
Willy Tarreaufb56aab2012-09-28 14:40:02 +0200776static void event_srv_chk_r(struct connection *conn)
Willy Tarreaubaaee002006-06-26 02:48:02 +0200777{
Simon Horman4a741432013-02-23 15:35:38 +0900778 struct check *check = conn->owner;
779 struct server *s = check->server;
780 struct task *t = check->task;
Krzysztof Piotr Oledzkif7089f52009-10-10 21:06:49 +0200781 char *desc;
Willy Tarreau03938182010-03-17 21:52:07 +0100782 int done;
Gabor Lekenyb4c81e42010-09-29 18:17:05 +0200783 unsigned short msglen;
Willy Tarreau83749182007-04-15 20:56:27 +0200784
Willy Tarreau6aaa1b82013-12-11 17:09:34 +0100785 if (unlikely(check->result == CHK_RES_FAILED))
Willy Tarreau83749182007-04-15 20:56:27 +0200786 goto out_wakeup;
Willy Tarreau83749182007-04-15 20:56:27 +0200787
Willy Tarreau310987a2014-01-22 19:46:33 +0100788 if (conn->flags & CO_FL_HANDSHAKE)
Willy Tarreaufb56aab2012-09-28 14:40:02 +0200789 return;
Baptiste Assmann5ecb77f2013-10-06 23:24:13 +0200790
791 if (check->type == PR_O2_TCPCHK_CHK) {
792 tcpcheck_main(conn);
793 return;
794 }
Willy Tarreaufb56aab2012-09-28 14:40:02 +0200795
Willy Tarreau83749182007-04-15 20:56:27 +0200796 /* Warning! Linux returns EAGAIN on SO_ERROR if data are still available
797 * but the connection was closed on the remote end. Fortunately, recv still
798 * works correctly and we don't need to do the getsockopt() on linux.
799 */
Nick Chalk57b1bf72010-03-16 15:50:46 +0000800
801 /* Set buffer to point to the end of the data already read, and check
802 * that there is free space remaining. If the buffer is full, proceed
803 * with running the checks without attempting another socket read.
804 */
Nick Chalk57b1bf72010-03-16 15:50:46 +0000805
Willy Tarreau03938182010-03-17 21:52:07 +0100806 done = 0;
Nick Chalk57b1bf72010-03-16 15:50:46 +0000807
Simon Horman4a741432013-02-23 15:35:38 +0900808 conn->xprt->rcv_buf(conn, check->bi, check->bi->size);
Willy Tarreauf1503172012-09-28 19:39:36 +0200809 if (conn->flags & (CO_FL_ERROR | CO_FL_SOCK_RD_SH | CO_FL_DATA_RD_SH)) {
Willy Tarreau03938182010-03-17 21:52:07 +0100810 done = 1;
Simon Horman4a741432013-02-23 15:35:38 +0900811 if ((conn->flags & CO_FL_ERROR) && !check->bi->i) {
Willy Tarreauf1503172012-09-28 19:39:36 +0200812 /* Report network errors only if we got no other data. Otherwise
813 * we'll let the upper layers decide whether the response is OK
814 * or not. It is very common that an RST sent by the server is
815 * reported as an error just after the last data chunk.
816 */
Willy Tarreau25e2ab52013-12-04 11:17:05 +0100817 chk_report_conn_err(conn, errno, 0);
Willy Tarreauc1a07962010-03-16 20:55:43 +0100818 goto out_wakeup;
819 }
Willy Tarreaubaaee002006-06-26 02:48:02 +0200820 }
821
Willy Tarreau25e2ab52013-12-04 11:17:05 +0100822
Willy Tarreau03938182010-03-17 21:52:07 +0100823 /* Intermediate or complete response received.
Simon Horman4a741432013-02-23 15:35:38 +0900824 * Terminate string in check->bi->data buffer.
Willy Tarreau03938182010-03-17 21:52:07 +0100825 */
Simon Horman4a741432013-02-23 15:35:38 +0900826 if (check->bi->i < check->bi->size)
827 check->bi->data[check->bi->i] = '\0';
Willy Tarreau03938182010-03-17 21:52:07 +0100828 else {
Simon Horman4a741432013-02-23 15:35:38 +0900829 check->bi->data[check->bi->i - 1] = '\0';
Willy Tarreau03938182010-03-17 21:52:07 +0100830 done = 1; /* buffer full, don't wait for more data */
831 }
Krzysztof Piotr Oledzkif7089f52009-10-10 21:06:49 +0200832
Nick Chalk57b1bf72010-03-16 15:50:46 +0000833 /* Run the checks... */
Simon Horman4a741432013-02-23 15:35:38 +0900834 switch (check->type) {
Willy Tarreau1620ec32011-08-06 17:05:02 +0200835 case PR_O2_HTTP_CHK:
Simon Horman4a741432013-02-23 15:35:38 +0900836 if (!done && check->bi->i < strlen("HTTP/1.0 000\r"))
Willy Tarreau03938182010-03-17 21:52:07 +0100837 goto wait_more_data;
838
Willy Tarreauc7dd71a2007-11-30 08:33:21 +0100839 /* Check if the server speaks HTTP 1.X */
Simon Horman4a741432013-02-23 15:35:38 +0900840 if ((check->bi->i < strlen("HTTP/1.0 000\r")) ||
841 (memcmp(check->bi->data, "HTTP/1.", 7) != 0 ||
842 (*(check->bi->data + 12) != ' ' && *(check->bi->data + 12) != '\r')) ||
843 !isdigit((unsigned char) *(check->bi->data + 9)) || !isdigit((unsigned char) *(check->bi->data + 10)) ||
844 !isdigit((unsigned char) *(check->bi->data + 11))) {
845 cut_crlf(check->bi->data);
846 set_server_check_status(check, HCHK_STATUS_L7RSP, check->bi->data);
Krzysztof Piotr Oledzkif7089f52009-10-10 21:06:49 +0200847
Willy Tarreauc7dd71a2007-11-30 08:33:21 +0100848 goto out_wakeup;
849 }
850
Simon Horman4a741432013-02-23 15:35:38 +0900851 check->code = str2uic(check->bi->data + 9);
852 desc = ltrim(check->bi->data + 12, ' ');
Nick Chalk57b1bf72010-03-16 15:50:46 +0000853
Willy Tarreaubd741542010-03-16 18:46:54 +0100854 if ((s->proxy->options & PR_O_DISABLE404) &&
Willy Tarreau892337c2014-05-13 23:41:20 +0200855 (s->state != SRV_ST_STOPPED) && (check->code == 404)) {
Nick Chalk57b1bf72010-03-16 15:50:46 +0000856 /* 404 may be accepted as "stopping" only if the server was up */
857 cut_crlf(desc);
Simon Horman4a741432013-02-23 15:35:38 +0900858 set_server_check_status(check, HCHK_STATUS_L7OKCD, desc);
Nick Chalk57b1bf72010-03-16 15:50:46 +0000859 }
Willy Tarreaubd741542010-03-16 18:46:54 +0100860 else if (s->proxy->options2 & PR_O2_EXP_TYPE) {
861 /* Run content verification check... We know we have at least 13 chars */
862 if (!httpchk_expect(s, done))
863 goto wait_more_data;
864 }
865 /* check the reply : HTTP/1.X 2xx and 3xx are OK */
Simon Horman4a741432013-02-23 15:35:38 +0900866 else if (*(check->bi->data + 9) == '2' || *(check->bi->data + 9) == '3') {
Willy Tarreaubd741542010-03-16 18:46:54 +0100867 cut_crlf(desc);
Simon Horman4a741432013-02-23 15:35:38 +0900868 set_server_check_status(check, HCHK_STATUS_L7OKD, desc);
Willy Tarreaubd741542010-03-16 18:46:54 +0100869 }
Nick Chalk57b1bf72010-03-16 15:50:46 +0000870 else {
871 cut_crlf(desc);
Simon Horman4a741432013-02-23 15:35:38 +0900872 set_server_check_status(check, HCHK_STATUS_L7STS, desc);
Nick Chalk57b1bf72010-03-16 15:50:46 +0000873 }
Willy Tarreau1620ec32011-08-06 17:05:02 +0200874 break;
875
876 case PR_O2_SSL3_CHK:
Simon Horman4a741432013-02-23 15:35:38 +0900877 if (!done && check->bi->i < 5)
Willy Tarreau03938182010-03-17 21:52:07 +0100878 goto wait_more_data;
879
Willy Tarreauc7dd71a2007-11-30 08:33:21 +0100880 /* Check for SSLv3 alert or handshake */
Simon Horman4a741432013-02-23 15:35:38 +0900881 if ((check->bi->i >= 5) && (*check->bi->data == 0x15 || *check->bi->data == 0x16))
882 set_server_check_status(check, HCHK_STATUS_L6OK, NULL);
Krzysztof Piotr Oledzki213014e2009-09-27 15:50:02 +0200883 else
Simon Horman4a741432013-02-23 15:35:38 +0900884 set_server_check_status(check, HCHK_STATUS_L6RSP, NULL);
Willy Tarreau1620ec32011-08-06 17:05:02 +0200885 break;
886
887 case PR_O2_SMTP_CHK:
Simon Horman4a741432013-02-23 15:35:38 +0900888 if (!done && check->bi->i < strlen("000\r"))
Willy Tarreau03938182010-03-17 21:52:07 +0100889 goto wait_more_data;
890
Krzysztof Piotr Oledzki09605412009-09-23 22:09:24 +0200891 /* Check if the server speaks SMTP */
Simon Horman4a741432013-02-23 15:35:38 +0900892 if ((check->bi->i < strlen("000\r")) ||
893 (*(check->bi->data + 3) != ' ' && *(check->bi->data + 3) != '\r') ||
894 !isdigit((unsigned char) *check->bi->data) || !isdigit((unsigned char) *(check->bi->data + 1)) ||
895 !isdigit((unsigned char) *(check->bi->data + 2))) {
896 cut_crlf(check->bi->data);
897 set_server_check_status(check, HCHK_STATUS_L7RSP, check->bi->data);
Krzysztof Piotr Oledzkif7089f52009-10-10 21:06:49 +0200898
Krzysztof Piotr Oledzki09605412009-09-23 22:09:24 +0200899 goto out_wakeup;
900 }
901
Simon Horman4a741432013-02-23 15:35:38 +0900902 check->code = str2uic(check->bi->data);
Krzysztof Piotr Oledzki09605412009-09-23 22:09:24 +0200903
Simon Horman4a741432013-02-23 15:35:38 +0900904 desc = ltrim(check->bi->data + 3, ' ');
Krzysztof Piotr Oledzkif7089f52009-10-10 21:06:49 +0200905 cut_crlf(desc);
906
Willy Tarreauc7dd71a2007-11-30 08:33:21 +0100907 /* Check for SMTP code 2xx (should be 250) */
Simon Horman4a741432013-02-23 15:35:38 +0900908 if (*check->bi->data == '2')
909 set_server_check_status(check, HCHK_STATUS_L7OKD, desc);
Krzysztof Piotr Oledzki213014e2009-09-27 15:50:02 +0200910 else
Simon Horman4a741432013-02-23 15:35:38 +0900911 set_server_check_status(check, HCHK_STATUS_L7STS, desc);
Willy Tarreau1620ec32011-08-06 17:05:02 +0200912 break;
913
Simon Hormana2b9dad2013-02-12 10:45:54 +0900914 case PR_O2_LB_AGENT_CHK: {
Willy Tarreau81f5d942013-12-09 20:51:51 +0100915 int status = HCHK_STATUS_CHECKED;
916 const char *hs = NULL; /* health status */
917 const char *as = NULL; /* admin status */
918 const char *ps = NULL; /* performance status */
919 const char *err = NULL; /* first error to report */
920 const char *wrn = NULL; /* first warning to report */
921 char *cmd, *p;
Simon Hormana2b9dad2013-02-12 10:45:54 +0900922
Willy Tarreau81f5d942013-12-09 20:51:51 +0100923 /* We're getting an agent check response. The agent could
924 * have been disabled in the mean time with a long check
925 * still pending. It is important that we ignore the whole
926 * response.
927 */
928 if (!(check->server->agent.state & CHK_ST_ENABLED))
929 break;
930
931 /* The agent supports strings made of a single line ended by the
932 * first CR ('\r') or LF ('\n'). This line is composed of words
933 * delimited by spaces (' '), tabs ('\t'), or commas (','). The
934 * line may optionally contained a description of a state change
935 * after a sharp ('#'), which is only considered if a health state
936 * is announced.
937 *
938 * Words may be composed of :
939 * - a numeric weight suffixed by the percent character ('%').
940 * - a health status among "up", "down", "stopped", and "fail".
941 * - an admin status among "ready", "drain", "maint".
942 *
943 * These words may appear in any order. If multiple words of the
944 * same category appear, the last one wins.
945 */
946
Willy Tarreau9809b782013-12-11 21:40:11 +0100947 p = check->bi->data;
948 while (*p && *p != '\n' && *p != '\r')
949 p++;
950
951 if (!*p) {
952 if (!done)
953 goto wait_more_data;
Simon Hormana2b9dad2013-02-12 10:45:54 +0900954
Willy Tarreau9809b782013-12-11 21:40:11 +0100955 /* at least inform the admin that the agent is mis-behaving */
956 set_server_check_status(check, check->status, "Ignoring incomplete line from agent");
957 break;
958 }
Willy Tarreau81f5d942013-12-09 20:51:51 +0100959
Willy Tarreau9809b782013-12-11 21:40:11 +0100960 *p = 0;
Willy Tarreau81f5d942013-12-09 20:51:51 +0100961 cmd = check->bi->data;
Simon Hormana2b9dad2013-02-12 10:45:54 +0900962
Willy Tarreau81f5d942013-12-09 20:51:51 +0100963 while (*cmd) {
964 /* look for next word */
965 if (*cmd == ' ' || *cmd == '\t' || *cmd == ',') {
966 cmd++;
967 continue;
968 }
Simon Horman671b6f02013-11-25 10:46:39 +0900969
Willy Tarreau81f5d942013-12-09 20:51:51 +0100970 if (*cmd == '#') {
971 /* this is the beginning of a health status description,
972 * skip the sharp and blanks.
973 */
974 cmd++;
975 while (*cmd == '\t' || *cmd == ' ')
976 cmd++;
Simon Horman671b6f02013-11-25 10:46:39 +0900977 break;
Simon Hormana2b9dad2013-02-12 10:45:54 +0900978 }
Willy Tarreau81f5d942013-12-09 20:51:51 +0100979
980 /* find the end of the word so that we have a null-terminated
981 * word between <cmd> and <p>.
982 */
983 p = cmd + 1;
984 while (*p && *p != '\t' && *p != ' ' && *p != '\n' && *p != ',')
985 p++;
986 if (*p)
987 *p++ = 0;
988
989 /* first, health statuses */
990 if (strcasecmp(cmd, "up") == 0) {
991 check->health = check->rise + check->fall - 1;
Simon Hormana2b9dad2013-02-12 10:45:54 +0900992 status = HCHK_STATUS_L7OKD;
Willy Tarreau81f5d942013-12-09 20:51:51 +0100993 hs = cmd;
994 }
995 else if (strcasecmp(cmd, "down") == 0) {
996 check->health = 0;
997 status = HCHK_STATUS_L7STS;
998 hs = cmd;
Simon Hormana2b9dad2013-02-12 10:45:54 +0900999 }
Willy Tarreau81f5d942013-12-09 20:51:51 +01001000 else if (strcasecmp(cmd, "stopped") == 0) {
1001 check->health = 0;
1002 status = HCHK_STATUS_L7STS;
1003 hs = cmd;
1004 }
1005 else if (strcasecmp(cmd, "fail") == 0) {
1006 check->health = 0;
1007 status = HCHK_STATUS_L7STS;
1008 hs = cmd;
1009 }
1010 /* admin statuses */
1011 else if (strcasecmp(cmd, "ready") == 0) {
1012 as = cmd;
1013 }
1014 else if (strcasecmp(cmd, "drain") == 0) {
1015 as = cmd;
1016 }
1017 else if (strcasecmp(cmd, "maint") == 0) {
1018 as = cmd;
1019 }
1020 /* else try to parse a weight here and keep the last one */
1021 else if (isdigit((unsigned char)*cmd) && strchr(cmd, '%') != NULL) {
1022 ps = cmd;
1023 }
1024 else {
1025 /* keep a copy of the first error */
1026 if (!err)
1027 err = cmd;
1028 }
1029 /* skip to next word */
1030 cmd = p;
1031 }
1032 /* here, cmd points either to \0 or to the beginning of a
1033 * description. Skip possible leading spaces.
1034 */
1035 while (*cmd == ' ' || *cmd == '\n')
1036 cmd++;
1037
1038 /* First, update the admin status so that we avoid sending other
1039 * possibly useless warnings and can also update the health if
1040 * present after going back up.
1041 */
1042 if (as) {
1043 if (strcasecmp(as, "drain") == 0)
1044 srv_adm_set_drain(check->server);
1045 else if (strcasecmp(as, "maint") == 0)
1046 srv_adm_set_maint(check->server);
1047 else
1048 srv_adm_set_ready(check->server);
Simon Hormana2b9dad2013-02-12 10:45:54 +09001049 }
1050
Willy Tarreau81f5d942013-12-09 20:51:51 +01001051 /* now change weights */
1052 if (ps) {
1053 const char *msg;
1054
1055 msg = server_parse_weight_change_request(s, ps);
1056 if (!wrn || !*wrn)
1057 wrn = msg;
1058 }
1059
1060 /* and finally health status */
1061 if (hs) {
1062 /* We'll report some of the warnings and errors we have
1063 * here. Down reports are critical, we leave them untouched.
1064 * Lack of report, or report of 'UP' leaves the room for
1065 * ERR first, then WARN.
Simon Hormana2b9dad2013-02-12 10:45:54 +09001066 */
Willy Tarreau81f5d942013-12-09 20:51:51 +01001067 const char *msg = cmd;
1068 struct chunk *t;
1069
1070 if (!*msg || status == HCHK_STATUS_L7OKD) {
1071 if (err && *err)
1072 msg = err;
1073 else if (wrn && *wrn)
1074 msg = wrn;
Simon Hormana2b9dad2013-02-12 10:45:54 +09001075 }
Willy Tarreau81f5d942013-12-09 20:51:51 +01001076
1077 t = get_trash_chunk();
1078 chunk_printf(t, "via agent : %s%s%s%s",
1079 hs, *msg ? " (" : "",
1080 msg, *msg ? ")" : "");
1081
1082 set_server_check_status(check, status, t->str);
Simon Hormana2b9dad2013-02-12 10:45:54 +09001083 }
Willy Tarreau81f5d942013-12-09 20:51:51 +01001084 else if (err && *err) {
1085 /* No status change but we'd like to report something odd.
1086 * Just report the current state and copy the message.
1087 */
1088 chunk_printf(&trash, "agent reports an error : %s", err);
1089 set_server_check_status(check, status/*check->status*/, trash.str);
Simon Hormana2b9dad2013-02-12 10:45:54 +09001090
Willy Tarreau81f5d942013-12-09 20:51:51 +01001091 }
1092 else if (wrn && *wrn) {
1093 /* No status change but we'd like to report something odd.
1094 * Just report the current state and copy the message.
1095 */
1096 chunk_printf(&trash, "agent warns : %s", wrn);
1097 set_server_check_status(check, status/*check->status*/, trash.str);
1098 }
1099 else
1100 set_server_check_status(check, status, NULL);
Simon Hormana2b9dad2013-02-12 10:45:54 +09001101 break;
1102 }
1103
Willy Tarreau1620ec32011-08-06 17:05:02 +02001104 case PR_O2_PGSQL_CHK:
Simon Horman4a741432013-02-23 15:35:38 +09001105 if (!done && check->bi->i < 9)
Rauf Kuliyev38b41562011-01-04 15:14:13 +01001106 goto wait_more_data;
1107
Simon Horman4a741432013-02-23 15:35:38 +09001108 if (check->bi->data[0] == 'R') {
1109 set_server_check_status(check, HCHK_STATUS_L7OKD, "PostgreSQL server is ok");
Rauf Kuliyev38b41562011-01-04 15:14:13 +01001110 }
1111 else {
Simon Horman4a741432013-02-23 15:35:38 +09001112 if ((check->bi->data[0] == 'E') && (check->bi->data[5]!=0) && (check->bi->data[6]!=0))
1113 desc = &check->bi->data[6];
Rauf Kuliyev38b41562011-01-04 15:14:13 +01001114 else
1115 desc = "PostgreSQL unknown error";
1116
Simon Horman4a741432013-02-23 15:35:38 +09001117 set_server_check_status(check, HCHK_STATUS_L7STS, desc);
Rauf Kuliyev38b41562011-01-04 15:14:13 +01001118 }
Willy Tarreau1620ec32011-08-06 17:05:02 +02001119 break;
1120
1121 case PR_O2_REDIS_CHK:
Simon Horman4a741432013-02-23 15:35:38 +09001122 if (!done && check->bi->i < 7)
Hervé COMMOWICKec032d62011-08-05 16:23:48 +02001123 goto wait_more_data;
1124
Simon Horman4a741432013-02-23 15:35:38 +09001125 if (strcmp(check->bi->data, "+PONG\r\n") == 0) {
1126 set_server_check_status(check, HCHK_STATUS_L7OKD, "Redis server is ok");
Hervé COMMOWICKec032d62011-08-05 16:23:48 +02001127 }
1128 else {
Simon Horman4a741432013-02-23 15:35:38 +09001129 set_server_check_status(check, HCHK_STATUS_L7STS, check->bi->data);
Hervé COMMOWICKec032d62011-08-05 16:23:48 +02001130 }
Willy Tarreau1620ec32011-08-06 17:05:02 +02001131 break;
1132
1133 case PR_O2_MYSQL_CHK:
Simon Horman4a741432013-02-23 15:35:38 +09001134 if (!done && check->bi->i < 5)
Willy Tarreau03938182010-03-17 21:52:07 +01001135 goto wait_more_data;
1136
Hervé COMMOWICK8776f1b2010-10-18 15:58:36 +02001137 if (s->proxy->check_len == 0) { // old mode
Simon Horman4a741432013-02-23 15:35:38 +09001138 if (*(check->bi->data + 4) != '\xff') {
Hervé COMMOWICK8776f1b2010-10-18 15:58:36 +02001139 /* We set the MySQL Version in description for information purpose
1140 * FIXME : it can be cool to use MySQL Version for other purpose,
1141 * like mark as down old MySQL server.
1142 */
Simon Horman4a741432013-02-23 15:35:38 +09001143 if (check->bi->i > 51) {
1144 desc = ltrim(check->bi->data + 5, ' ');
1145 set_server_check_status(check, HCHK_STATUS_L7OKD, desc);
Hervé COMMOWICK8776f1b2010-10-18 15:58:36 +02001146 }
1147 else {
1148 if (!done)
1149 goto wait_more_data;
1150 /* it seems we have a OK packet but without a valid length,
1151 * it must be a protocol error
1152 */
Simon Horman4a741432013-02-23 15:35:38 +09001153 set_server_check_status(check, HCHK_STATUS_L7RSP, check->bi->data);
Hervé COMMOWICK8776f1b2010-10-18 15:58:36 +02001154 }
Hervé COMMOWICK698ae002010-01-12 09:25:13 +01001155 }
1156 else {
Hervé COMMOWICK8776f1b2010-10-18 15:58:36 +02001157 /* An error message is attached in the Error packet */
Simon Horman4a741432013-02-23 15:35:38 +09001158 desc = ltrim(check->bi->data + 7, ' ');
1159 set_server_check_status(check, HCHK_STATUS_L7STS, desc);
Hervé COMMOWICK8776f1b2010-10-18 15:58:36 +02001160 }
1161 } else {
Simon Horman4a741432013-02-23 15:35:38 +09001162 unsigned int first_packet_len = ((unsigned int) *check->bi->data) +
1163 (((unsigned int) *(check->bi->data + 1)) << 8) +
1164 (((unsigned int) *(check->bi->data + 2)) << 16);
Hervé COMMOWICK8776f1b2010-10-18 15:58:36 +02001165
Simon Horman4a741432013-02-23 15:35:38 +09001166 if (check->bi->i == first_packet_len + 4) {
Hervé COMMOWICK8776f1b2010-10-18 15:58:36 +02001167 /* MySQL Error packet always begin with field_count = 0xff */
Simon Horman4a741432013-02-23 15:35:38 +09001168 if (*(check->bi->data + 4) != '\xff') {
Hervé COMMOWICK8776f1b2010-10-18 15:58:36 +02001169 /* We have only one MySQL packet and it is a Handshake Initialization packet
1170 * but we need to have a second packet to know if it is alright
1171 */
Simon Horman4a741432013-02-23 15:35:38 +09001172 if (!done && check->bi->i < first_packet_len + 5)
Hervé COMMOWICK8776f1b2010-10-18 15:58:36 +02001173 goto wait_more_data;
1174 }
1175 else {
1176 /* We have only one packet and it is an Error packet,
1177 * an error message is attached, so we can display it
1178 */
Simon Horman4a741432013-02-23 15:35:38 +09001179 desc = &check->bi->data[7];
Hervé COMMOWICK8776f1b2010-10-18 15:58:36 +02001180 //Warning("onlyoneERR: %s\n", desc);
Simon Horman4a741432013-02-23 15:35:38 +09001181 set_server_check_status(check, HCHK_STATUS_L7STS, desc);
Hervé COMMOWICK8776f1b2010-10-18 15:58:36 +02001182 }
Simon Horman4a741432013-02-23 15:35:38 +09001183 } else if (check->bi->i > first_packet_len + 4) {
1184 unsigned int second_packet_len = ((unsigned int) *(check->bi->data + first_packet_len + 4)) +
1185 (((unsigned int) *(check->bi->data + first_packet_len + 5)) << 8) +
1186 (((unsigned int) *(check->bi->data + first_packet_len + 6)) << 16);
Hervé COMMOWICK8776f1b2010-10-18 15:58:36 +02001187
Simon Horman4a741432013-02-23 15:35:38 +09001188 if (check->bi->i == first_packet_len + 4 + second_packet_len + 4 ) {
Hervé COMMOWICK8776f1b2010-10-18 15:58:36 +02001189 /* We have 2 packets and that's good */
1190 /* Check if the second packet is a MySQL Error packet or not */
Simon Horman4a741432013-02-23 15:35:38 +09001191 if (*(check->bi->data + first_packet_len + 8) != '\xff') {
Hervé COMMOWICK8776f1b2010-10-18 15:58:36 +02001192 /* No error packet */
1193 /* We set the MySQL Version in description for information purpose */
Simon Horman4a741432013-02-23 15:35:38 +09001194 desc = &check->bi->data[5];
Hervé COMMOWICK8776f1b2010-10-18 15:58:36 +02001195 //Warning("2packetOK: %s\n", desc);
Simon Horman4a741432013-02-23 15:35:38 +09001196 set_server_check_status(check, HCHK_STATUS_L7OKD, desc);
Hervé COMMOWICK8776f1b2010-10-18 15:58:36 +02001197 }
1198 else {
1199 /* An error message is attached in the Error packet
1200 * so we can display it ! :)
1201 */
Simon Horman4a741432013-02-23 15:35:38 +09001202 desc = &check->bi->data[first_packet_len+11];
Hervé COMMOWICK8776f1b2010-10-18 15:58:36 +02001203 //Warning("2packetERR: %s\n", desc);
Simon Horman4a741432013-02-23 15:35:38 +09001204 set_server_check_status(check, HCHK_STATUS_L7STS, desc);
Hervé COMMOWICK8776f1b2010-10-18 15:58:36 +02001205 }
1206 }
1207 }
1208 else {
Willy Tarreau03938182010-03-17 21:52:07 +01001209 if (!done)
1210 goto wait_more_data;
Hervé COMMOWICK8776f1b2010-10-18 15:58:36 +02001211 /* it seems we have a Handshake Initialization packet but without a valid length,
Hervé COMMOWICK698ae002010-01-12 09:25:13 +01001212 * it must be a protocol error
1213 */
Simon Horman4a741432013-02-23 15:35:38 +09001214 desc = &check->bi->data[5];
Hervé COMMOWICK8776f1b2010-10-18 15:58:36 +02001215 //Warning("protoerr: %s\n", desc);
Simon Horman4a741432013-02-23 15:35:38 +09001216 set_server_check_status(check, HCHK_STATUS_L7RSP, desc);
Hervé COMMOWICK698ae002010-01-12 09:25:13 +01001217 }
1218 }
Willy Tarreau1620ec32011-08-06 17:05:02 +02001219 break;
1220
1221 case PR_O2_LDAP_CHK:
Simon Horman4a741432013-02-23 15:35:38 +09001222 if (!done && check->bi->i < 14)
Gabor Lekenyb4c81e42010-09-29 18:17:05 +02001223 goto wait_more_data;
1224
1225 /* Check if the server speaks LDAP (ASN.1/BER)
1226 * http://en.wikipedia.org/wiki/Basic_Encoding_Rules
1227 * http://tools.ietf.org/html/rfc4511
1228 */
1229
1230 /* http://tools.ietf.org/html/rfc4511#section-4.1.1
1231 * LDAPMessage: 0x30: SEQUENCE
1232 */
Simon Horman4a741432013-02-23 15:35:38 +09001233 if ((check->bi->i < 14) || (*(check->bi->data) != '\x30')) {
1234 set_server_check_status(check, HCHK_STATUS_L7RSP, "Not LDAPv3 protocol");
Gabor Lekenyb4c81e42010-09-29 18:17:05 +02001235 }
1236 else {
1237 /* size of LDAPMessage */
Simon Horman4a741432013-02-23 15:35:38 +09001238 msglen = (*(check->bi->data + 1) & 0x80) ? (*(check->bi->data + 1) & 0x7f) : 0;
Gabor Lekenyb4c81e42010-09-29 18:17:05 +02001239
1240 /* http://tools.ietf.org/html/rfc4511#section-4.2.2
1241 * messageID: 0x02 0x01 0x01: INTEGER 1
1242 * protocolOp: 0x61: bindResponse
1243 */
1244 if ((msglen > 2) ||
Simon Horman4a741432013-02-23 15:35:38 +09001245 (memcmp(check->bi->data + 2 + msglen, "\x02\x01\x01\x61", 4) != 0)) {
1246 set_server_check_status(check, HCHK_STATUS_L7RSP, "Not LDAPv3 protocol");
Gabor Lekenyb4c81e42010-09-29 18:17:05 +02001247
1248 goto out_wakeup;
1249 }
1250
1251 /* size of bindResponse */
Simon Horman4a741432013-02-23 15:35:38 +09001252 msglen += (*(check->bi->data + msglen + 6) & 0x80) ? (*(check->bi->data + msglen + 6) & 0x7f) : 0;
Gabor Lekenyb4c81e42010-09-29 18:17:05 +02001253
1254 /* http://tools.ietf.org/html/rfc4511#section-4.1.9
1255 * ldapResult: 0x0a 0x01: ENUMERATION
1256 */
1257 if ((msglen > 4) ||
Simon Horman4a741432013-02-23 15:35:38 +09001258 (memcmp(check->bi->data + 7 + msglen, "\x0a\x01", 2) != 0)) {
1259 set_server_check_status(check, HCHK_STATUS_L7RSP, "Not LDAPv3 protocol");
Gabor Lekenyb4c81e42010-09-29 18:17:05 +02001260
1261 goto out_wakeup;
1262 }
1263
1264 /* http://tools.ietf.org/html/rfc4511#section-4.1.9
1265 * resultCode
1266 */
Simon Horman4a741432013-02-23 15:35:38 +09001267 check->code = *(check->bi->data + msglen + 9);
1268 if (check->code) {
1269 set_server_check_status(check, HCHK_STATUS_L7STS, "See RFC: http://tools.ietf.org/html/rfc4511#section-4.1.9");
Gabor Lekenyb4c81e42010-09-29 18:17:05 +02001270 } else {
Simon Horman4a741432013-02-23 15:35:38 +09001271 set_server_check_status(check, HCHK_STATUS_L7OKD, "Success");
Gabor Lekenyb4c81e42010-09-29 18:17:05 +02001272 }
1273 }
Willy Tarreau1620ec32011-08-06 17:05:02 +02001274 break;
1275
1276 default:
Willy Tarreau06559ac2013-12-05 01:53:08 +01001277 /* for other checks (eg: pure TCP), delegate to the main task */
Willy Tarreau1620ec32011-08-06 17:05:02 +02001278 break;
1279 } /* switch */
Willy Tarreau83749182007-04-15 20:56:27 +02001280
Willy Tarreauc7dd71a2007-11-30 08:33:21 +01001281 out_wakeup:
Willy Tarreau25e2ab52013-12-04 11:17:05 +01001282 /* collect possible new errors */
1283 if (conn->flags & CO_FL_ERROR)
1284 chk_report_conn_err(conn, 0, 0);
Willy Tarreaubaaee002006-06-26 02:48:02 +02001285
Nick Chalk57b1bf72010-03-16 15:50:46 +00001286 /* Reset the check buffer... */
Simon Horman4a741432013-02-23 15:35:38 +09001287 *check->bi->data = '\0';
1288 check->bi->i = 0;
Nick Chalk57b1bf72010-03-16 15:50:46 +00001289
Willy Tarreaufd29cc52012-11-23 09:18:20 +01001290 /* Close the connection... We absolutely want to perform a hard close
1291 * and reset the connection if some data are pending, otherwise we end
1292 * up with many TIME_WAITs and eat all the source port range quickly.
1293 * To avoid sending RSTs all the time, we first try to drain pending
1294 * data.
1295 */
Willy Tarreaub4017d02015-03-12 23:11:26 +01001296 __conn_data_stop_both(conn);
1297 conn_data_shutw_hard(conn);
Willy Tarreau2b57cb82013-06-10 19:56:38 +02001298
Willy Tarreau25e2ab52013-12-04 11:17:05 +01001299 /* OK, let's not stay here forever */
Willy Tarreau6aaa1b82013-12-11 17:09:34 +01001300 if (check->result == CHK_RES_FAILED)
Willy Tarreau25e2ab52013-12-04 11:17:05 +01001301 conn->flags |= CO_FL_ERROR;
1302
Willy Tarreaufdccded2008-08-29 18:19:04 +02001303 task_wakeup(t, TASK_WOKEN_IO);
Willy Tarreau3267d362012-08-17 23:53:56 +02001304 return;
Willy Tarreau03938182010-03-17 21:52:07 +01001305
1306 wait_more_data:
Willy Tarreauf817e9f2014-01-10 16:58:45 +01001307 __conn_data_want_recv(conn);
Willy Tarreaubaaee002006-06-26 02:48:02 +02001308}
1309
Willy Tarreaufb56aab2012-09-28 14:40:02 +02001310/*
1311 * This function is used only for server health-checks. It handles connection
1312 * status updates including errors. If necessary, it wakes the check task up.
1313 * It always returns 0.
1314 */
1315static int wake_srv_chk(struct connection *conn)
Willy Tarreau20bea422012-07-06 12:00:49 +02001316{
Simon Horman4a741432013-02-23 15:35:38 +09001317 struct check *check = conn->owner;
Willy Tarreau20bea422012-07-06 12:00:49 +02001318
Willy Tarreau6c560da2012-11-24 11:14:45 +01001319 if (unlikely(conn->flags & CO_FL_ERROR)) {
Willy Tarreau02b0f582013-12-03 15:42:33 +01001320 /* We may get error reports bypassing the I/O handlers, typically
1321 * the case when sending a pure TCP check which fails, then the I/O
1322 * handlers above are not called. This is completely handled by the
Willy Tarreau25e2ab52013-12-04 11:17:05 +01001323 * main processing task so let's simply wake it up. If we get here,
1324 * we expect errno to still be valid.
1325 */
1326 chk_report_conn_err(conn, errno, 0);
1327
Willy Tarreau2d351b62013-12-05 02:36:25 +01001328 __conn_data_stop_both(conn);
1329 task_wakeup(check->task, TASK_WOKEN_IO);
1330 }
Willy Tarreau3be293f2014-02-05 18:31:24 +01001331 else if (!(conn->flags & (CO_FL_DATA_RD_ENA|CO_FL_DATA_WR_ENA|CO_FL_HANDSHAKE))) {
1332 /* we may get here if only a connection probe was required : we
1333 * don't have any data to send nor anything expected in response,
1334 * so the completion of the connection establishment is enough.
1335 */
1336 task_wakeup(check->task, TASK_WOKEN_IO);
1337 }
Willy Tarreau2d351b62013-12-05 02:36:25 +01001338
Willy Tarreau6aaa1b82013-12-11 17:09:34 +01001339 if (check->result != CHK_RES_UNKNOWN) {
Willy Tarreau25e2ab52013-12-04 11:17:05 +01001340 /* We're here because nobody wants to handle the error, so we
1341 * sure want to abort the hard way.
Willy Tarreau02b0f582013-12-03 15:42:33 +01001342 */
Willy Tarreaud85c4852015-03-13 00:40:28 +01001343 conn_sock_drain(conn);
Willy Tarreauf79c8172013-10-21 16:30:56 +02001344 conn_force_close(conn);
Willy Tarreau2d351b62013-12-05 02:36:25 +01001345 }
Willy Tarreau3267d362012-08-17 23:53:56 +02001346 return 0;
Willy Tarreau20bea422012-07-06 12:00:49 +02001347}
1348
Willy Tarreaufb56aab2012-09-28 14:40:02 +02001349struct data_cb check_conn_cb = {
1350 .recv = event_srv_chk_r,
1351 .send = event_srv_chk_w,
1352 .wake = wake_srv_chk,
1353};
1354
Willy Tarreaubaaee002006-06-26 02:48:02 +02001355/*
Willy Tarreau2e993902011-10-31 11:53:20 +01001356 * updates the server's weight during a warmup stage. Once the final weight is
1357 * reached, the task automatically stops. Note that any server status change
1358 * must have updated s->last_change accordingly.
1359 */
1360static struct task *server_warmup(struct task *t)
1361{
1362 struct server *s = t->context;
1363
1364 /* by default, plan on stopping the task */
1365 t->expire = TICK_ETERNITY;
Willy Tarreau20125212014-05-13 19:44:56 +02001366 if ((s->admin & SRV_ADMF_MAINT) ||
Willy Tarreau892337c2014-05-13 23:41:20 +02001367 (s->state != SRV_ST_STARTING))
Willy Tarreau2e993902011-10-31 11:53:20 +01001368 return t;
1369
Willy Tarreau892337c2014-05-13 23:41:20 +02001370 /* recalculate the weights and update the state */
Willy Tarreau004e0452013-11-21 11:22:01 +01001371 server_recalc_eweight(s);
Willy Tarreau2e993902011-10-31 11:53:20 +01001372
1373 /* probably that we can refill this server with a bit more connections */
Willy Tarreau4aac7db2014-05-16 11:48:10 +02001374 pendconn_grab_from_px(s);
Willy Tarreau2e993902011-10-31 11:53:20 +01001375
1376 /* get back there in 1 second or 1/20th of the slowstart interval,
1377 * whichever is greater, resulting in small 5% steps.
1378 */
Willy Tarreau892337c2014-05-13 23:41:20 +02001379 if (s->state == SRV_ST_STARTING)
Willy Tarreau2e993902011-10-31 11:53:20 +01001380 t->expire = tick_add(now_ms, MS_TO_TICKS(MAX(1000, s->slowstart / 20)));
1381 return t;
1382}
1383
1384/*
Simon Horman98637e52014-06-20 12:30:16 +09001385 * establish a server health-check that makes use of a connection.
Simon Hormanb00d17a2014-06-13 16:18:16 +09001386 *
1387 * It can return one of :
1388 * - SN_ERR_NONE if everything's OK and tcpcheck_main() was not called
1389 * - SN_ERR_UP if if everything's OK and tcpcheck_main() was called
1390 * - SN_ERR_SRVTO if there are no more servers
1391 * - SN_ERR_SRVCL if the connection was refused by the server
1392 * - SN_ERR_PRXCOND if the connection has been limited by the proxy (maxconn)
1393 * - SN_ERR_RESOURCE if a system resource is lacking (eg: fd limits, ports, ...)
1394 * - SN_ERR_INTERNAL for any other purely internal errors
1395 * Additionnally, in the case of SN_ERR_RESOURCE, an emergency log will be emitted.
1396 * Note that we try to prevent the network stack from sending the ACK during the
1397 * connect() when a pure TCP check is used (without PROXY protocol).
1398 */
Simon Horman98637e52014-06-20 12:30:16 +09001399static int connect_conn_chk(struct task *t)
Simon Hormanb00d17a2014-06-13 16:18:16 +09001400{
1401 struct check *check = t->context;
1402 struct server *s = check->server;
1403 struct connection *conn = check->conn;
1404 struct protocol *proto;
1405 int ret;
Willy Tarreauf3d34822014-12-08 12:11:28 +01001406 int quickack;
Simon Hormanb00d17a2014-06-13 16:18:16 +09001407
1408 /* tcpcheck send/expect initialisation */
1409 if (check->type == PR_O2_TCPCHK_CHK)
1410 check->current_step = NULL;
1411
1412 /* prepare the check buffer.
1413 * This should not be used if check is the secondary agent check
1414 * of a server as s->proxy->check_req will relate to the
1415 * configuration of the primary check. Similarly, tcp-check uses
1416 * its own strings.
1417 */
1418 if (check->type && check->type != PR_O2_TCPCHK_CHK && !(check->state & CHK_ST_AGENT)) {
1419 bo_putblk(check->bo, s->proxy->check_req, s->proxy->check_len);
1420
1421 /* we want to check if this host replies to HTTP or SSLv3 requests
1422 * so we'll send the request, and won't wake the checker up now.
1423 */
1424 if ((check->type) == PR_O2_SSL3_CHK) {
1425 /* SSL requires that we put Unix time in the request */
1426 int gmt_time = htonl(date.tv_sec);
1427 memcpy(check->bo->data + 11, &gmt_time, 4);
1428 }
1429 else if ((check->type) == PR_O2_HTTP_CHK) {
1430 if (s->proxy->options2 & PR_O2_CHK_SNDST)
1431 bo_putblk(check->bo, trash.str, httpchk_build_status_header(s, trash.str, trash.size));
Cyril Bonté32602d22015-01-30 00:07:07 +01001432 /* prevent HTTP keep-alive when "http-check expect" is used */
1433 if (s->proxy->options2 & PR_O2_EXP_TYPE)
1434 bo_putstr(check->bo, "Connection: close\r\n");
Simon Hormanb00d17a2014-06-13 16:18:16 +09001435 bo_putstr(check->bo, "\r\n");
1436 *check->bo->p = '\0'; /* to make gdb output easier to read */
1437 }
1438 }
1439
1440 /* prepare a new connection */
1441 conn_init(conn);
Simon Hormanb00d17a2014-06-13 16:18:16 +09001442
Simon Horman41f58762015-01-30 11:22:56 +09001443 if (is_addr(&check->addr)) {
Simon Hormanb00d17a2014-06-13 16:18:16 +09001444 /* we'll connect to the check addr specified on the server */
Simon Horman41f58762015-01-30 11:22:56 +09001445 conn->addr.to = check->addr;
Simon Hormanb00d17a2014-06-13 16:18:16 +09001446 }
1447 else {
1448 /* we'll connect to the addr on the server */
1449 conn->addr.to = s->addr;
Simon Hormanb00d17a2014-06-13 16:18:16 +09001450 }
1451
1452 if (check->port) {
1453 set_host_port(&conn->addr.to, check->port);
1454 }
1455
Thierry FOURNIERbb2ae642015-01-14 11:31:49 +01001456 proto = protocol_by_family(conn->addr.to.ss_family);
1457
1458 conn_prepare(conn, proto, check->xprt);
1459 conn_attach(conn, check, &check_conn_cb);
1460 conn->target = &s->obj_type;
1461
1462 /* no client address */
1463 clear_addr(&conn->addr.from);
1464
Willy Tarreauf3d34822014-12-08 12:11:28 +01001465 /* only plain tcp-check supports quick ACK */
1466 quickack = check->type == 0 || check->type == PR_O2_TCPCHK_CHK;
1467
Simon Hormane16c1b32015-01-30 11:22:57 +09001468 if (check->type == PR_O2_TCPCHK_CHK && !LIST_ISEMPTY(check->tcpcheck_rules)) {
1469 struct tcpcheck_rule *r = (struct tcpcheck_rule *) check->tcpcheck_rules->n;
Simon Hormanb00d17a2014-06-13 16:18:16 +09001470 /* if first step is a 'connect', then tcpcheck_main must run it */
1471 if (r->action == TCPCHK_ACT_CONNECT) {
1472 tcpcheck_main(conn);
1473 return SN_ERR_UP;
1474 }
Willy Tarreauf3d34822014-12-08 12:11:28 +01001475 if (r->action == TCPCHK_ACT_EXPECT)
1476 quickack = 0;
Simon Hormanb00d17a2014-06-13 16:18:16 +09001477 }
1478
1479 ret = SN_ERR_INTERNAL;
1480 if (proto->connect)
Willy Tarreauf3d34822014-12-08 12:11:28 +01001481 ret = proto->connect(conn, check->type, quickack ? 2 : 0);
Simon Hormanb00d17a2014-06-13 16:18:16 +09001482 conn->flags |= CO_FL_WAKE_DATA;
1483 if (s->check.send_proxy) {
1484 conn->send_proxy_ofs = 1;
1485 conn->flags |= CO_FL_SEND_PROXY;
1486 }
1487
1488 return ret;
1489}
1490
Simon Horman98637e52014-06-20 12:30:16 +09001491static struct list pid_list = LIST_HEAD_INIT(pid_list);
1492static struct pool_head *pool2_pid_list;
1493
1494void block_sigchld(void)
1495{
1496 sigset_t set;
1497 sigemptyset(&set);
1498 sigaddset(&set, SIGCHLD);
1499 assert(sigprocmask(SIG_SETMASK, &set, NULL) == 0);
1500}
1501
1502void unblock_sigchld(void)
1503{
1504 sigset_t set;
1505 sigemptyset(&set);
1506 assert(sigprocmask(SIG_SETMASK, &set, NULL) == 0);
1507}
1508
1509/* Call with SIGCHLD blocked */
1510static struct pid_list *pid_list_add(pid_t pid, struct task *t)
1511{
1512 struct pid_list *elem;
1513 struct check *check = t->context;
1514
1515 elem = pool_alloc2(pool2_pid_list);
1516 if (!elem)
1517 return NULL;
1518 elem->pid = pid;
1519 elem->t = t;
1520 elem->exited = 0;
1521 check->curpid = elem;
1522 LIST_INIT(&elem->list);
1523 LIST_ADD(&pid_list, &elem->list);
1524 return elem;
1525}
1526
1527/* Blocks blocks and then unblocks SIGCHLD */
1528static void pid_list_del(struct pid_list *elem)
1529{
1530 struct check *check;
1531
1532 if (!elem)
1533 return;
1534
1535 block_sigchld();
1536 LIST_DEL(&elem->list);
1537 unblock_sigchld();
1538 if (!elem->exited)
1539 kill(elem->pid, SIGTERM);
1540
1541 check = elem->t->context;
1542 check->curpid = NULL;
1543 pool_free2(pool2_pid_list, elem);
1544}
1545
1546/* Called from inside SIGCHLD handler, SIGCHLD is blocked */
1547static void pid_list_expire(pid_t pid, int status)
1548{
1549 struct pid_list *elem;
1550
1551 list_for_each_entry(elem, &pid_list, list) {
1552 if (elem->pid == pid) {
1553 elem->t->expire = now_ms;
1554 elem->status = status;
1555 elem->exited = 1;
Cyril Bonté9dbcfab2014-08-07 01:55:39 +02001556 task_wakeup(elem->t, TASK_WOKEN_IO);
Simon Horman98637e52014-06-20 12:30:16 +09001557 return;
1558 }
1559 }
1560}
1561
1562static void sigchld_handler(int signal)
1563{
1564 pid_t pid;
1565 int status;
1566 while ((pid = waitpid(0, &status, WNOHANG)) > 0)
1567 pid_list_expire(pid, status);
1568}
1569
1570static int init_pid_list(void) {
1571 struct sigaction action = {
1572 .sa_handler = sigchld_handler,
1573 .sa_flags = SA_NOCLDSTOP
1574 };
1575
1576 if (pool2_pid_list != NULL)
1577 /* Nothing to do */
1578 return 0;
1579
1580 if (sigaction(SIGCHLD, &action, NULL)) {
1581 Alert("Failed to set signal handler for external health checks: %s. Aborting.\n",
1582 strerror(errno));
1583 return 1;
1584 }
1585
1586 pool2_pid_list = create_pool("pid_list", sizeof(struct pid_list), MEM_F_SHARED);
1587 if (pool2_pid_list == NULL) {
1588 Alert("Failed to allocate memory pool for external health checks: %s. Aborting.\n",
1589 strerror(errno));
1590 return 1;
1591 }
1592
1593 return 0;
1594}
1595
Cyril Bontéac92a062014-12-27 22:28:38 +01001596/* helper macro to set an environment variable and jump to a specific label on failure. */
1597#define EXTCHK_SETENV(check, envidx, value, fail) { if (extchk_setenv(check, envidx, value)) goto fail; }
Cyril Bonté9ede66b2014-12-02 21:21:36 +01001598
1599/*
Cyril Bontéac92a062014-12-27 22:28:38 +01001600 * helper function to allocate enough memory to store an environment variable.
1601 * It will also check that the environment variable is updatable, and silently
1602 * fail if not.
Cyril Bonté9ede66b2014-12-02 21:21:36 +01001603 */
Cyril Bontéac92a062014-12-27 22:28:38 +01001604static int extchk_setenv(struct check *check, int idx, const char *value)
Cyril Bonté9ede66b2014-12-02 21:21:36 +01001605{
1606 int len, ret;
Cyril Bontéac92a062014-12-27 22:28:38 +01001607 char *envname;
1608 int vmaxlen;
Cyril Bonté9ede66b2014-12-02 21:21:36 +01001609
Cyril Bontéac92a062014-12-27 22:28:38 +01001610 if (idx < 0 || idx >= EXTCHK_SIZE) {
1611 Alert("Illegal environment variable index %d. Aborting.\n", idx);
1612 return 1;
Cyril Bonté9ede66b2014-12-02 21:21:36 +01001613 }
Cyril Bontéac92a062014-12-27 22:28:38 +01001614
1615 envname = extcheck_envs[idx].name;
1616 vmaxlen = extcheck_envs[idx].vmaxlen;
1617
1618 /* Check if the environment variable is already set, and silently reject
1619 * the update if this one is not updatable. */
1620 if ((vmaxlen == EXTCHK_SIZE_EVAL_INIT) && (check->envp[idx]))
1621 return 0;
1622
Cyril Bonté9ede66b2014-12-02 21:21:36 +01001623 /* Instead of sending NOT_USED, sending an empty value is preferable */
1624 if (strcmp(value, "NOT_USED") == 0) {
1625 value = "";
1626 }
Cyril Bontéac92a062014-12-27 22:28:38 +01001627
1628 len = strlen(envname) + 1;
1629 if (vmaxlen == EXTCHK_SIZE_EVAL_INIT)
1630 len += strlen(value);
1631 else
1632 len += vmaxlen;
1633
1634 if (!check->envp[idx])
1635 check->envp[idx] = malloc(len + 1);
1636
1637 if (!check->envp[idx]) {
Cyril Bonté9ede66b2014-12-02 21:21:36 +01001638 Alert("Failed to allocate memory for the environment variable '%s'. Aborting.\n", envname);
1639 return 1;
1640 }
Cyril Bontéac92a062014-12-27 22:28:38 +01001641 ret = snprintf(check->envp[idx], len + 1, "%s=%s", envname, value);
Cyril Bonté9ede66b2014-12-02 21:21:36 +01001642 if (ret < 0) {
1643 Alert("Failed to store the environment variable '%s'. Reason : %s. Aborting.\n", envname, strerror(errno));
1644 return 1;
1645 }
Cyril Bontéac92a062014-12-27 22:28:38 +01001646 else if (ret > len) {
Cyril Bonté9ede66b2014-12-02 21:21:36 +01001647 Alert("Environment variable '%s' was truncated. Aborting.\n", envname);
1648 return 1;
1649 }
Cyril Bonté9ede66b2014-12-02 21:21:36 +01001650 return 0;
1651}
Simon Horman98637e52014-06-20 12:30:16 +09001652
1653static int prepare_external_check(struct check *check)
1654{
1655 struct server *s = check->server;
1656 struct proxy *px = s->proxy;
1657 struct listener *listener = NULL, *l;
1658 int i;
Simon Horman98637e52014-06-20 12:30:16 +09001659 const char *path = px->check_path ? px->check_path : DEF_CHECK_PATH;
Cyril Bonté9ede66b2014-12-02 21:21:36 +01001660 char buf[256];
Simon Horman98637e52014-06-20 12:30:16 +09001661
1662 list_for_each_entry(l, &px->conf.listeners, by_fe)
1663 /* Use the first INET, INET6 or UNIX listener */
1664 if (l->addr.ss_family == AF_INET ||
1665 l->addr.ss_family == AF_INET6 ||
1666 l->addr.ss_family == AF_UNIX) {
1667 listener = l;
1668 break;
1669 }
1670
Simon Horman98637e52014-06-20 12:30:16 +09001671 check->curpid = NULL;
Cyril Bontéac92a062014-12-27 22:28:38 +01001672 check->envp = calloc((EXTCHK_SIZE + 1), sizeof(char *));
1673 if (!check->envp) {
1674 Alert("Failed to allocate memory for environment variables. Aborting\n");
1675 goto err;
1676 }
Simon Horman98637e52014-06-20 12:30:16 +09001677
Cyril Bontéac92a062014-12-27 22:28:38 +01001678 check->argv = calloc(6, sizeof(char *));
1679 if (!check->argv) {
1680 Alert("Starting [%s:%s] check: out of memory.\n", px->id, s->id);
Simon Horman98637e52014-06-20 12:30:16 +09001681 goto err;
Cyril Bontéac92a062014-12-27 22:28:38 +01001682 }
Simon Horman98637e52014-06-20 12:30:16 +09001683
1684 check->argv[0] = px->check_command;
1685
Cyril Bonté777be862014-12-02 21:21:35 +01001686 if (!listener) {
1687 check->argv[1] = strdup("NOT_USED");
1688 check->argv[2] = strdup("NOT_USED");
1689 }
1690 else if (listener->addr.ss_family == AF_INET ||
Simon Horman98637e52014-06-20 12:30:16 +09001691 listener->addr.ss_family == AF_INET6) {
Cyril Bonté9ede66b2014-12-02 21:21:36 +01001692 addr_to_str(&listener->addr, buf, sizeof(buf));
1693 check->argv[1] = strdup(buf);
1694 port_to_str(&listener->addr, buf, sizeof(buf));
1695 check->argv[2] = strdup(buf);
Cyril Bonté777be862014-12-02 21:21:35 +01001696 }
1697 else if (listener->addr.ss_family == AF_UNIX) {
Simon Horman98637e52014-06-20 12:30:16 +09001698 const struct sockaddr_un *un;
1699
1700 un = (struct sockaddr_un *)&listener->addr;
1701 check->argv[1] = strdup(un->sun_path);
1702 check->argv[2] = strdup("NOT_USED");
Cyril Bonté777be862014-12-02 21:21:35 +01001703 }
1704 else {
Cyril Bontéac92a062014-12-27 22:28:38 +01001705 Alert("Starting [%s:%s] check: unsupported address family.\n", px->id, s->id);
Simon Horman98637e52014-06-20 12:30:16 +09001706 goto err;
1707 }
1708
Cyril Bonté9ede66b2014-12-02 21:21:36 +01001709 addr_to_str(&s->addr, buf, sizeof(buf));
1710 check->argv[3] = strdup(buf);
1711 port_to_str(&s->addr, buf, sizeof(buf));
1712 check->argv[4] = strdup(buf);
Simon Horman98637e52014-06-20 12:30:16 +09001713
Cyril Bontéac92a062014-12-27 22:28:38 +01001714 for (i = 0; i < 5; i++) {
1715 if (!check->argv[i]) {
1716 Alert("Starting [%s:%s] check: out of memory.\n", px->id, s->id);
Simon Horman98637e52014-06-20 12:30:16 +09001717 goto err;
Cyril Bontéac92a062014-12-27 22:28:38 +01001718 }
1719 }
Simon Horman98637e52014-06-20 12:30:16 +09001720
Cyril Bontéac92a062014-12-27 22:28:38 +01001721 EXTCHK_SETENV(check, EXTCHK_PATH, path, err);
Cyril Bonté9ede66b2014-12-02 21:21:36 +01001722 /* Add proxy environment variables */
Cyril Bontéac92a062014-12-27 22:28:38 +01001723 EXTCHK_SETENV(check, EXTCHK_HAPROXY_PROXY_NAME, px->id, err);
1724 EXTCHK_SETENV(check, EXTCHK_HAPROXY_PROXY_ID, ultoa_r(px->uuid, buf, sizeof(buf)), err);
1725 EXTCHK_SETENV(check, EXTCHK_HAPROXY_PROXY_ADDR, check->argv[1], err);
1726 EXTCHK_SETENV(check, EXTCHK_HAPROXY_PROXY_PORT, check->argv[2], err);
Cyril Bonté9ede66b2014-12-02 21:21:36 +01001727 /* Add server environment variables */
Cyril Bontéac92a062014-12-27 22:28:38 +01001728 EXTCHK_SETENV(check, EXTCHK_HAPROXY_SERVER_NAME, s->id, err);
1729 EXTCHK_SETENV(check, EXTCHK_HAPROXY_SERVER_ID, ultoa_r(s->puid, buf, sizeof(buf)), err);
1730 EXTCHK_SETENV(check, EXTCHK_HAPROXY_SERVER_ADDR, check->argv[3], err);
1731 EXTCHK_SETENV(check, EXTCHK_HAPROXY_SERVER_PORT, check->argv[4], err);
1732 EXTCHK_SETENV(check, EXTCHK_HAPROXY_SERVER_MAXCONN, ultoa_r(s->maxconn, buf, sizeof(buf)), err);
1733 EXTCHK_SETENV(check, EXTCHK_HAPROXY_SERVER_CURCONN, ultoa_r(s->cur_sess, buf, sizeof(buf)), err);
1734
1735 /* Ensure that we don't leave any hole in check->envp */
1736 for (i = 0; i < EXTCHK_SIZE; i++)
1737 if (!check->envp[i])
1738 EXTCHK_SETENV(check, i, "", err);
Cyril Bonté9ede66b2014-12-02 21:21:36 +01001739
Cyril Bonté99c5bf52014-08-07 01:55:38 +02001740 return 1;
Simon Horman98637e52014-06-20 12:30:16 +09001741err:
1742 if (check->envp) {
Cyril Bontéac92a062014-12-27 22:28:38 +01001743 for (i = 0; i < EXTCHK_SIZE; i++)
Cyril Bonté9ede66b2014-12-02 21:21:36 +01001744 free(check->envp[i]);
Simon Horman98637e52014-06-20 12:30:16 +09001745 free(check->envp);
1746 check->envp = NULL;
1747 }
1748
1749 if (check->argv) {
1750 for (i = 1; i < 5; i++)
1751 free(check->argv[i]);
1752 free(check->argv);
1753 check->argv = NULL;
1754 }
Cyril Bonté99c5bf52014-08-07 01:55:38 +02001755 return 0;
Simon Horman98637e52014-06-20 12:30:16 +09001756}
1757
Simon Hormanb00d17a2014-06-13 16:18:16 +09001758/*
Simon Horman98637e52014-06-20 12:30:16 +09001759 * establish a server health-check that makes use of a process.
1760 *
1761 * It can return one of :
1762 * - SN_ERR_NONE if everything's OK
1763 * - SN_ERR_SRVTO if there are no more servers
1764 * - SN_ERR_SRVCL if the connection was refused by the server
1765 * - SN_ERR_PRXCOND if the connection has been limited by the proxy (maxconn)
1766 * - SN_ERR_RESOURCE if a system resource is lacking (eg: fd limits, ports, ...)
1767 * - SN_ERR_INTERNAL for any other purely internal errors
1768 * Additionnally, in the case of SN_ERR_RESOURCE, an emergency log will be emitted.
1769 *
1770 * Blocks and then unblocks SIGCHLD
1771 */
1772static int connect_proc_chk(struct task *t)
1773{
Cyril Bontéac92a062014-12-27 22:28:38 +01001774 char buf[256];
Simon Horman98637e52014-06-20 12:30:16 +09001775 struct check *check = t->context;
1776 struct server *s = check->server;
1777 struct proxy *px = s->proxy;
1778 int status;
1779 pid_t pid;
1780
Simon Horman98637e52014-06-20 12:30:16 +09001781 status = SN_ERR_RESOURCE;
1782
1783 block_sigchld();
1784
1785 pid = fork();
1786 if (pid < 0) {
1787 Alert("Failed to fork process for external health check: %s. Aborting.\n",
1788 strerror(errno));
1789 set_server_check_status(check, HCHK_STATUS_SOCKERR, strerror(errno));
1790 goto out;
1791 }
1792 if (pid == 0) {
1793 /* Child */
1794 extern char **environ;
1795 environ = check->envp;
Cyril Bontéac92a062014-12-27 22:28:38 +01001796 extchk_setenv(check, EXTCHK_HAPROXY_SERVER_CURCONN, ultoa_r(s->cur_sess, buf, sizeof(buf)));
Simon Horman98637e52014-06-20 12:30:16 +09001797 execvp(px->check_command, check->argv);
1798 Alert("Failed to exec process for external health check: %s. Aborting.\n",
1799 strerror(errno));
1800 exit(-1);
1801 }
1802
1803 /* Parent */
1804 if (check->result == CHK_RES_UNKNOWN) {
1805 if (pid_list_add(pid, t) != NULL) {
1806 t->expire = tick_add(now_ms, MS_TO_TICKS(check->inter));
1807
1808 if (px->timeout.check && px->timeout.connect) {
1809 int t_con = tick_add(now_ms, px->timeout.connect);
1810 t->expire = tick_first(t->expire, t_con);
1811 }
1812 status = SN_ERR_NONE;
1813 goto out;
1814 }
1815 else {
1816 set_server_check_status(check, HCHK_STATUS_SOCKERR, strerror(errno));
1817 }
1818 kill(pid, SIGTERM); /* process creation error */
1819 }
1820 else
1821 set_server_check_status(check, HCHK_STATUS_SOCKERR, strerror(errno));
1822
1823out:
1824 unblock_sigchld();
1825 return status;
1826}
1827
1828/*
Simon Horman98637e52014-06-20 12:30:16 +09001829 * manages a server health-check that uses a process. Returns
Willy Tarreaubaaee002006-06-26 02:48:02 +02001830 * the time the task accepts to wait, or TIME_ETERNITY for infinity.
1831 */
Simon Horman98637e52014-06-20 12:30:16 +09001832static struct task *process_chk_proc(struct task *t)
1833{
1834 struct check *check = t->context;
1835 struct server *s = check->server;
1836 struct connection *conn = check->conn;
1837 int rv;
1838 int ret;
1839 int expired = tick_is_expired(t->expire, now_ms);
1840
1841 if (!(check->state & CHK_ST_INPROGRESS)) {
1842 /* no check currently running */
1843 if (!expired) /* woke up too early */
1844 return t;
1845
1846 /* we don't send any health-checks when the proxy is
1847 * stopped, the server should not be checked or the check
1848 * is disabled.
1849 */
1850 if (((check->state & (CHK_ST_ENABLED | CHK_ST_PAUSED)) != CHK_ST_ENABLED) ||
1851 s->proxy->state == PR_STSTOPPED)
1852 goto reschedule;
1853
1854 /* we'll initiate a new check */
1855 set_server_check_status(check, HCHK_STATUS_START, NULL);
1856
1857 check->state |= CHK_ST_INPROGRESS;
1858
Simon Hormandbf70192015-01-30 11:22:53 +09001859 ret = connect_proc_chk(t);
Simon Horman98637e52014-06-20 12:30:16 +09001860 switch (ret) {
1861 case SN_ERR_UP:
1862 return t;
1863 case SN_ERR_NONE:
1864 /* we allow up to min(inter, timeout.connect) for a connection
1865 * to establish but only when timeout.check is set
1866 * as it may be to short for a full check otherwise
1867 */
1868 t->expire = tick_add(now_ms, MS_TO_TICKS(check->inter));
1869
1870 if (s->proxy->timeout.check && s->proxy->timeout.connect) {
1871 int t_con = tick_add(now_ms, s->proxy->timeout.connect);
1872 t->expire = tick_first(t->expire, t_con);
1873 }
1874
1875 goto reschedule;
1876
1877 case SN_ERR_SRVTO: /* ETIMEDOUT */
1878 case SN_ERR_SRVCL: /* ECONNREFUSED, ENETUNREACH, ... */
1879 conn->flags |= CO_FL_ERROR;
1880 chk_report_conn_err(conn, errno, 0);
1881 break;
1882 case SN_ERR_PRXCOND:
1883 case SN_ERR_RESOURCE:
1884 case SN_ERR_INTERNAL:
1885 conn->flags |= CO_FL_ERROR;
1886 chk_report_conn_err(conn, 0, 0);
1887 break;
1888 }
1889
1890 /* here, we have seen a synchronous error, no fd was allocated */
1891
1892 check->state &= ~CHK_ST_INPROGRESS;
1893 check_notify_failure(check);
1894
1895 /* we allow up to min(inter, timeout.connect) for a connection
1896 * to establish but only when timeout.check is set
1897 * as it may be to short for a full check otherwise
1898 */
1899 while (tick_is_expired(t->expire, now_ms)) {
1900 int t_con;
1901
1902 t_con = tick_add(t->expire, s->proxy->timeout.connect);
1903 t->expire = tick_add(t->expire, MS_TO_TICKS(check->inter));
1904
1905 if (s->proxy->timeout.check)
1906 t->expire = tick_first(t->expire, t_con);
1907 }
1908 }
1909 else {
1910 /* there was a test running.
1911 * First, let's check whether there was an uncaught error,
1912 * which can happen on connect timeout or error.
1913 */
1914 if (check->result == CHK_RES_UNKNOWN) {
1915 /* good connection is enough for pure TCP check */
1916 struct pid_list *elem = check->curpid;
1917 int status = HCHK_STATUS_UNKNOWN;
1918
1919 if (elem->exited) {
1920 status = elem->status; /* Save in case the process exits between use below */
1921 if (!WIFEXITED(status))
1922 check->code = -1;
1923 else
1924 check->code = WEXITSTATUS(status);
1925 if (!WIFEXITED(status) || WEXITSTATUS(status))
1926 status = HCHK_STATUS_PROCERR;
1927 else
1928 status = HCHK_STATUS_PROCOK;
1929 } else if (expired) {
1930 status = HCHK_STATUS_PROCTOUT;
Willy Tarreaudc3d1902014-07-08 00:56:27 +02001931 Warning("kill %d\n", (int)elem->pid);
Simon Horman98637e52014-06-20 12:30:16 +09001932 kill(elem->pid, SIGTERM);
1933 }
1934 set_server_check_status(check, status, NULL);
1935 }
1936
1937 if (check->result == CHK_RES_FAILED) {
1938 /* a failure or timeout detected */
1939 check_notify_failure(check);
1940 }
1941 else if (check->result == CHK_RES_CONDPASS) {
1942 /* check is OK but asks for stopping mode */
1943 check_notify_stopping(check);
1944 }
1945 else if (check->result == CHK_RES_PASSED) {
1946 /* a success was detected */
1947 check_notify_success(check);
1948 }
1949 check->state &= ~CHK_ST_INPROGRESS;
1950
1951 pid_list_del(check->curpid);
1952
1953 rv = 0;
1954 if (global.spread_checks > 0) {
1955 rv = srv_getinter(check) * global.spread_checks / 100;
1956 rv -= (int) (2 * rv * (rand() / (RAND_MAX + 1.0)));
1957 }
1958 t->expire = tick_add(now_ms, MS_TO_TICKS(srv_getinter(check) + rv));
1959 }
1960
1961 reschedule:
1962 while (tick_is_expired(t->expire, now_ms))
1963 t->expire = tick_add(t->expire, MS_TO_TICKS(check->inter));
1964 return t;
1965}
1966
1967/*
1968 * manages a server health-check that uses a connection. Returns
1969 * the time the task accepts to wait, or TIME_ETERNITY for infinity.
1970 */
1971static struct task *process_chk_conn(struct task *t)
Willy Tarreaubaaee002006-06-26 02:48:02 +02001972{
Simon Horman4a741432013-02-23 15:35:38 +09001973 struct check *check = t->context;
1974 struct server *s = check->server;
1975 struct connection *conn = check->conn;
Krzysztof Oledzkib304dc72007-10-14 23:40:01 +02001976 int rv;
Willy Tarreaufb56aab2012-09-28 14:40:02 +02001977 int ret;
Willy Tarreauacbdc7a2012-11-23 14:02:10 +01001978 int expired = tick_is_expired(t->expire, now_ms);
Willy Tarreaubaaee002006-06-26 02:48:02 +02001979
Willy Tarreau2c115e52013-12-11 19:41:16 +01001980 if (!(check->state & CHK_ST_INPROGRESS)) {
Willy Tarreau5a78f362012-11-23 12:47:05 +01001981 /* no check currently running */
Willy Tarreauacbdc7a2012-11-23 14:02:10 +01001982 if (!expired) /* woke up too early */
Willy Tarreau26c25062009-03-08 09:38:41 +01001983 return t;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001984
Simon Horman671b6f02013-11-25 10:46:39 +09001985 /* we don't send any health-checks when the proxy is
1986 * stopped, the server should not be checked or the check
1987 * is disabled.
Willy Tarreaubaaee002006-06-26 02:48:02 +02001988 */
Willy Tarreau0d924cc2013-12-11 21:26:24 +01001989 if (((check->state & (CHK_ST_ENABLED | CHK_ST_PAUSED)) != CHK_ST_ENABLED) ||
Willy Tarreau33a08db2013-12-11 21:03:31 +01001990 s->proxy->state == PR_STSTOPPED)
Willy Tarreau5a78f362012-11-23 12:47:05 +01001991 goto reschedule;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001992
1993 /* we'll initiate a new check */
Simon Horman4a741432013-02-23 15:35:38 +09001994 set_server_check_status(check, HCHK_STATUS_START, NULL);
Willy Tarreau1ae1b7b2012-09-28 15:28:30 +02001995
Willy Tarreau2c115e52013-12-11 19:41:16 +01001996 check->state |= CHK_ST_INPROGRESS;
Simon Horman4a741432013-02-23 15:35:38 +09001997 check->bi->p = check->bi->data;
1998 check->bi->i = 0;
1999 check->bo->p = check->bo->data;
2000 check->bo->o = 0;
Willy Tarreau1ae1b7b2012-09-28 15:28:30 +02002001
Simon Hormandbf70192015-01-30 11:22:53 +09002002 ret = connect_conn_chk(t);
Willy Tarreaufb56aab2012-09-28 14:40:02 +02002003 switch (ret) {
Simon Hormanb00d17a2014-06-13 16:18:16 +09002004 case SN_ERR_UP:
2005 return t;
Willy Tarreaufb56aab2012-09-28 14:40:02 +02002006 case SN_ERR_NONE:
Willy Tarreaufb56aab2012-09-28 14:40:02 +02002007 /* we allow up to min(inter, timeout.connect) for a connection
2008 * to establish but only when timeout.check is set
2009 * as it may be to short for a full check otherwise
2010 */
Simon Horman4a741432013-02-23 15:35:38 +09002011 t->expire = tick_add(now_ms, MS_TO_TICKS(check->inter));
Krzysztof Piotr Oledzki09605412009-09-23 22:09:24 +02002012
Willy Tarreaufb56aab2012-09-28 14:40:02 +02002013 if (s->proxy->timeout.check && s->proxy->timeout.connect) {
2014 int t_con = tick_add(now_ms, s->proxy->timeout.connect);
2015 t->expire = tick_first(t->expire, t_con);
Willy Tarreaubaaee002006-06-26 02:48:02 +02002016 }
Willy Tarreau06559ac2013-12-05 01:53:08 +01002017
2018 if (check->type)
2019 conn_data_want_recv(conn); /* prepare for reading a possible reply */
2020
Willy Tarreau5a78f362012-11-23 12:47:05 +01002021 goto reschedule;
2022
2023 case SN_ERR_SRVTO: /* ETIMEDOUT */
2024 case SN_ERR_SRVCL: /* ECONNREFUSED, ENETUNREACH, ... */
Willy Tarreau4bd07de2014-01-24 16:10:57 +01002025 conn->flags |= CO_FL_ERROR;
2026 chk_report_conn_err(conn, errno, 0);
Willy Tarreau5a78f362012-11-23 12:47:05 +01002027 break;
2028 case SN_ERR_PRXCOND:
2029 case SN_ERR_RESOURCE:
2030 case SN_ERR_INTERNAL:
Willy Tarreau4bd07de2014-01-24 16:10:57 +01002031 conn->flags |= CO_FL_ERROR;
2032 chk_report_conn_err(conn, 0, 0);
Willy Tarreau5a78f362012-11-23 12:47:05 +01002033 break;
Willy Tarreaubaaee002006-06-26 02:48:02 +02002034 }
2035
Willy Tarreau5a78f362012-11-23 12:47:05 +01002036 /* here, we have seen a synchronous error, no fd was allocated */
Willy Tarreau6b0a8502012-11-23 08:51:32 +01002037
Willy Tarreau2c115e52013-12-11 19:41:16 +01002038 check->state &= ~CHK_ST_INPROGRESS;
Willy Tarreau4eec5472014-05-20 22:32:27 +02002039 check_notify_failure(check);
Willy Tarreaubaaee002006-06-26 02:48:02 +02002040
Krzysztof Piotr Oledzki5259dfe2008-01-21 01:54:06 +01002041 /* we allow up to min(inter, timeout.connect) for a connection
2042 * to establish but only when timeout.check is set
2043 * as it may be to short for a full check otherwise
2044 */
Willy Tarreau0c303ee2008-07-07 00:09:58 +02002045 while (tick_is_expired(t->expire, now_ms)) {
2046 int t_con;
Krzysztof Piotr Oledzki5259dfe2008-01-21 01:54:06 +01002047
Willy Tarreau0c303ee2008-07-07 00:09:58 +02002048 t_con = tick_add(t->expire, s->proxy->timeout.connect);
Simon Horman4a741432013-02-23 15:35:38 +09002049 t->expire = tick_add(t->expire, MS_TO_TICKS(check->inter));
Krzysztof Piotr Oledzki5259dfe2008-01-21 01:54:06 +01002050
Willy Tarreau0c303ee2008-07-07 00:09:58 +02002051 if (s->proxy->timeout.check)
2052 t->expire = tick_first(t->expire, t_con);
Krzysztof Piotr Oledzki5259dfe2008-01-21 01:54:06 +01002053 }
Willy Tarreaubaaee002006-06-26 02:48:02 +02002054 }
2055 else {
Willy Tarreauf1503172012-09-28 19:39:36 +02002056 /* there was a test running.
2057 * First, let's check whether there was an uncaught error,
2058 * which can happen on connect timeout or error.
2059 */
Simon Hormanccaabcd2014-06-20 12:29:47 +09002060 if (check->result == CHK_RES_UNKNOWN) {
Willy Tarreau25e2ab52013-12-04 11:17:05 +01002061 /* good connection is enough for pure TCP check */
2062 if ((conn->flags & CO_FL_CONNECTED) && !check->type) {
Simon Horman4a741432013-02-23 15:35:38 +09002063 if (check->use_ssl)
2064 set_server_check_status(check, HCHK_STATUS_L6OK, NULL);
Willy Tarreauf1503172012-09-28 19:39:36 +02002065 else
Simon Horman4a741432013-02-23 15:35:38 +09002066 set_server_check_status(check, HCHK_STATUS_L4OK, NULL);
Willy Tarreauacbdc7a2012-11-23 14:02:10 +01002067 }
Willy Tarreau25e2ab52013-12-04 11:17:05 +01002068 else if ((conn->flags & CO_FL_ERROR) || expired) {
2069 chk_report_conn_err(conn, 0, expired);
Willy Tarreauf1503172012-09-28 19:39:36 +02002070 }
Willy Tarreau74fa7fb2012-11-23 14:43:49 +01002071 else
2072 goto out_wait; /* timeout not reached, wait again */
Willy Tarreauf1503172012-09-28 19:39:36 +02002073 }
2074
Willy Tarreau74fa7fb2012-11-23 14:43:49 +01002075 /* check complete or aborted */
Willy Tarreau5ba04f62013-02-12 15:23:12 +01002076 if (conn->xprt) {
2077 /* The check was aborted and the connection was not yet closed.
2078 * This can happen upon timeout, or when an external event such
2079 * as a failed response coupled with "observe layer7" caused the
2080 * server state to be suddenly changed.
2081 */
Willy Tarreaud85c4852015-03-13 00:40:28 +01002082 conn_sock_drain(conn);
Willy Tarreauf79c8172013-10-21 16:30:56 +02002083 conn_force_close(conn);
Willy Tarreau5ba04f62013-02-12 15:23:12 +01002084 }
2085
Willy Tarreauaf549582014-05-16 17:37:50 +02002086 if (check->result == CHK_RES_FAILED) {
2087 /* a failure or timeout detected */
Willy Tarreau4eec5472014-05-20 22:32:27 +02002088 check_notify_failure(check);
Willy Tarreauaf549582014-05-16 17:37:50 +02002089 }
Willy Tarreaudb58b792014-05-21 13:57:23 +02002090 else if (check->result == CHK_RES_CONDPASS) {
2091 /* check is OK but asks for stopping mode */
2092 check_notify_stopping(check);
Willy Tarreauaf549582014-05-16 17:37:50 +02002093 }
Willy Tarreau3e048382014-05-21 10:30:54 +02002094 else if (check->result == CHK_RES_PASSED) {
2095 /* a success was detected */
2096 check_notify_success(check);
Willy Tarreaubaaee002006-06-26 02:48:02 +02002097 }
Willy Tarreau2c115e52013-12-11 19:41:16 +01002098 check->state &= ~CHK_ST_INPROGRESS;
Krzysztof Oledzkib304dc72007-10-14 23:40:01 +02002099
Willy Tarreau74fa7fb2012-11-23 14:43:49 +01002100 rv = 0;
2101 if (global.spread_checks > 0) {
Simon Horman4a741432013-02-23 15:35:38 +09002102 rv = srv_getinter(check) * global.spread_checks / 100;
Willy Tarreau74fa7fb2012-11-23 14:43:49 +01002103 rv -= (int) (2 * rv * (rand() / (RAND_MAX + 1.0)));
Willy Tarreaubaaee002006-06-26 02:48:02 +02002104 }
Simon Horman4a741432013-02-23 15:35:38 +09002105 t->expire = tick_add(now_ms, MS_TO_TICKS(srv_getinter(check) + rv));
Willy Tarreaubaaee002006-06-26 02:48:02 +02002106 }
Willy Tarreau5a78f362012-11-23 12:47:05 +01002107
2108 reschedule:
2109 while (tick_is_expired(t->expire, now_ms))
Simon Horman4a741432013-02-23 15:35:38 +09002110 t->expire = tick_add(t->expire, MS_TO_TICKS(check->inter));
Willy Tarreau74fa7fb2012-11-23 14:43:49 +01002111 out_wait:
Willy Tarreau26c25062009-03-08 09:38:41 +01002112 return t;
Willy Tarreaubaaee002006-06-26 02:48:02 +02002113}
2114
Simon Horman98637e52014-06-20 12:30:16 +09002115/*
2116 * manages a server health-check. Returns
2117 * the time the task accepts to wait, or TIME_ETERNITY for infinity.
2118 */
2119static struct task *process_chk(struct task *t)
2120{
2121 struct check *check = t->context;
2122
2123 if (check->type == PR_O2_EXT_CHK)
2124 return process_chk_proc(t);
2125 return process_chk_conn(t);
2126}
2127
Simon Horman5c942422013-11-25 10:46:32 +09002128static int start_check_task(struct check *check, int mininter,
2129 int nbcheck, int srvpos)
2130{
2131 struct task *t;
2132 /* task for the check */
2133 if ((t = task_new()) == NULL) {
2134 Alert("Starting [%s:%s] check: out of memory.\n",
2135 check->server->proxy->id, check->server->id);
2136 return 0;
2137 }
2138
2139 check->task = t;
2140 t->process = process_chk;
2141 t->context = check;
2142
Willy Tarreau1746eec2014-04-25 10:46:47 +02002143 if (mininter < srv_getinter(check))
2144 mininter = srv_getinter(check);
2145
2146 if (global.max_spread_checks && mininter > global.max_spread_checks)
2147 mininter = global.max_spread_checks;
2148
Simon Horman5c942422013-11-25 10:46:32 +09002149 /* check this every ms */
Willy Tarreau1746eec2014-04-25 10:46:47 +02002150 t->expire = tick_add(now_ms, MS_TO_TICKS(mininter * srvpos / nbcheck));
Simon Horman5c942422013-11-25 10:46:32 +09002151 check->start = now;
2152 task_queue(t);
2153
2154 return 1;
2155}
2156
Krzysztof Oledzkib304dc72007-10-14 23:40:01 +02002157/*
2158 * Start health-check.
2159 * Returns 0 if OK, -1 if error, and prints the error in this case.
2160 */
2161int start_checks() {
2162
2163 struct proxy *px;
2164 struct server *s;
2165 struct task *t;
Simon Horman4a741432013-02-23 15:35:38 +09002166 int nbcheck=0, mininter=0, srvpos=0;
Krzysztof Oledzkib304dc72007-10-14 23:40:01 +02002167
Willy Tarreau2c43a1e2007-10-14 23:05:39 +02002168 /* 1- count the checkers to run simultaneously.
2169 * We also determine the minimum interval among all of those which
2170 * have an interval larger than SRV_CHK_INTER_THRES. This interval
2171 * will be used to spread their start-up date. Those which have
Jamie Gloudon801a0a32012-08-25 00:18:33 -04002172 * a shorter interval will start independently and will not dictate
Willy Tarreau2c43a1e2007-10-14 23:05:39 +02002173 * too short an interval for all others.
2174 */
Krzysztof Oledzkib304dc72007-10-14 23:40:01 +02002175 for (px = proxy; px; px = px->next) {
2176 for (s = px->srv; s; s = s->next) {
Willy Tarreaue7b73482013-11-21 11:50:50 +01002177 if (s->slowstart) {
2178 if ((t = task_new()) == NULL) {
2179 Alert("Starting [%s:%s] check: out of memory.\n", px->id, s->id);
2180 return -1;
2181 }
2182 /* We need a warmup task that will be called when the server
2183 * state switches from down to up.
2184 */
2185 s->warmup = t;
2186 t->process = server_warmup;
2187 t->context = s;
2188 t->expire = TICK_ETERNITY;
2189 }
2190
Willy Tarreaud8514a22013-12-11 21:10:14 +01002191 if (s->check.state & CHK_ST_CONFIGURED) {
2192 nbcheck++;
2193 if ((srv_getinter(&s->check) >= SRV_CHK_INTER_THRES) &&
2194 (!mininter || mininter > srv_getinter(&s->check)))
2195 mininter = srv_getinter(&s->check);
2196 }
Willy Tarreau15f39102013-12-11 20:41:18 +01002197
Willy Tarreaud8514a22013-12-11 21:10:14 +01002198 if (s->agent.state & CHK_ST_CONFIGURED) {
2199 nbcheck++;
2200 if ((srv_getinter(&s->agent) >= SRV_CHK_INTER_THRES) &&
2201 (!mininter || mininter > srv_getinter(&s->agent)))
2202 mininter = srv_getinter(&s->agent);
2203 }
Krzysztof Oledzkib304dc72007-10-14 23:40:01 +02002204 }
2205 }
2206
Simon Horman4a741432013-02-23 15:35:38 +09002207 if (!nbcheck)
Krzysztof Oledzkib304dc72007-10-14 23:40:01 +02002208 return 0;
2209
2210 srand((unsigned)time(NULL));
2211
2212 /*
2213 * 2- start them as far as possible from each others. For this, we will
2214 * start them after their interval set to the min interval divided by
2215 * the number of servers, weighted by the server's position in the list.
2216 */
2217 for (px = proxy; px; px = px->next) {
Simon Horman98637e52014-06-20 12:30:16 +09002218 if ((px->options2 & PR_O2_CHK_ANY) == PR_O2_EXT_CHK) {
2219 if (init_pid_list()) {
2220 Alert("Starting [%s] check: out of memory.\n", px->id);
2221 return -1;
2222 }
2223 }
2224
Krzysztof Oledzkib304dc72007-10-14 23:40:01 +02002225 for (s = px->srv; s; s = s->next) {
Simon Hormand60d6912013-11-25 10:46:36 +09002226 /* A task for the main check */
Willy Tarreauff5ae352013-12-11 20:36:34 +01002227 if (s->check.state & CHK_ST_CONFIGURED) {
Cyril Bonté99c5bf52014-08-07 01:55:38 +02002228 if (s->check.type == PR_O2_EXT_CHK) {
2229 if (!prepare_external_check(&s->check))
2230 return -1;
2231 }
Simon Hormand60d6912013-11-25 10:46:36 +09002232 if (!start_check_task(&s->check, mininter, nbcheck, srvpos))
2233 return -1;
2234 srvpos++;
2235 }
Krzysztof Oledzkib304dc72007-10-14 23:40:01 +02002236
Simon Hormand60d6912013-11-25 10:46:36 +09002237 /* A task for a auxiliary agent check */
Willy Tarreauff5ae352013-12-11 20:36:34 +01002238 if (s->agent.state & CHK_ST_CONFIGURED) {
Simon Hormand60d6912013-11-25 10:46:36 +09002239 if (!start_check_task(&s->agent, mininter, nbcheck, srvpos)) {
2240 return -1;
2241 }
2242 srvpos++;
2243 }
Krzysztof Oledzkib304dc72007-10-14 23:40:01 +02002244 }
2245 }
2246 return 0;
2247}
Willy Tarreaubaaee002006-06-26 02:48:02 +02002248
2249/*
Willy Tarreau5b3a2022012-09-28 15:01:02 +02002250 * Perform content verification check on data in s->check.buffer buffer.
Willy Tarreaubd741542010-03-16 18:46:54 +01002251 * The buffer MUST be terminated by a null byte before calling this function.
2252 * Sets server status appropriately. The caller is responsible for ensuring
2253 * that the buffer contains at least 13 characters. If <done> is zero, we may
2254 * return 0 to indicate that data is required to decide of a match.
2255 */
2256static int httpchk_expect(struct server *s, int done)
2257{
2258 static char status_msg[] = "HTTP status check returned code <000>";
2259 char status_code[] = "000";
2260 char *contentptr;
2261 int crlf;
2262 int ret;
2263
2264 switch (s->proxy->options2 & PR_O2_EXP_TYPE) {
2265 case PR_O2_EXP_STS:
2266 case PR_O2_EXP_RSTS:
Willy Tarreau1ae1b7b2012-09-28 15:28:30 +02002267 memcpy(status_code, s->check.bi->data + 9, 3);
2268 memcpy(status_msg + strlen(status_msg) - 4, s->check.bi->data + 9, 3);
Willy Tarreaubd741542010-03-16 18:46:54 +01002269
2270 if ((s->proxy->options2 & PR_O2_EXP_TYPE) == PR_O2_EXP_STS)
2271 ret = strncmp(s->proxy->expect_str, status_code, 3) == 0;
2272 else
Thierry FOURNIER09af0d62014-06-18 11:35:54 +02002273 ret = regex_exec(s->proxy->expect_regex, status_code);
Willy Tarreaubd741542010-03-16 18:46:54 +01002274
2275 /* we necessarily have the response, so there are no partial failures */
2276 if (s->proxy->options2 & PR_O2_EXP_INV)
2277 ret = !ret;
2278
Simon Horman4a741432013-02-23 15:35:38 +09002279 set_server_check_status(&s->check, ret ? HCHK_STATUS_L7OKD : HCHK_STATUS_L7STS, status_msg);
Willy Tarreaubd741542010-03-16 18:46:54 +01002280 break;
2281
2282 case PR_O2_EXP_STR:
2283 case PR_O2_EXP_RSTR:
2284 /* very simple response parser: ignore CR and only count consecutive LFs,
2285 * stop with contentptr pointing to first char after the double CRLF or
2286 * to '\0' if crlf < 2.
2287 */
2288 crlf = 0;
Willy Tarreau1ae1b7b2012-09-28 15:28:30 +02002289 for (contentptr = s->check.bi->data; *contentptr; contentptr++) {
Willy Tarreaubd741542010-03-16 18:46:54 +01002290 if (crlf >= 2)
2291 break;
2292 if (*contentptr == '\r')
2293 continue;
2294 else if (*contentptr == '\n')
2295 crlf++;
2296 else
2297 crlf = 0;
2298 }
2299
2300 /* Check that response contains a body... */
2301 if (crlf < 2) {
2302 if (!done)
2303 return 0;
2304
Simon Horman4a741432013-02-23 15:35:38 +09002305 set_server_check_status(&s->check, HCHK_STATUS_L7RSP,
Willy Tarreaubd741542010-03-16 18:46:54 +01002306 "HTTP content check could not find a response body");
2307 return 1;
2308 }
2309
2310 /* Check that response body is not empty... */
2311 if (*contentptr == '\0') {
Willy Tarreaua164fb52011-04-13 09:32:41 +02002312 if (!done)
2313 return 0;
2314
Simon Horman4a741432013-02-23 15:35:38 +09002315 set_server_check_status(&s->check, HCHK_STATUS_L7RSP,
Willy Tarreaubd741542010-03-16 18:46:54 +01002316 "HTTP content check found empty response body");
2317 return 1;
2318 }
2319
2320 /* Check the response content against the supplied string
2321 * or regex... */
2322 if ((s->proxy->options2 & PR_O2_EXP_TYPE) == PR_O2_EXP_STR)
2323 ret = strstr(contentptr, s->proxy->expect_str) != NULL;
2324 else
Thierry FOURNIER09af0d62014-06-18 11:35:54 +02002325 ret = regex_exec(s->proxy->expect_regex, contentptr);
Willy Tarreaubd741542010-03-16 18:46:54 +01002326
2327 /* if we don't match, we may need to wait more */
2328 if (!ret && !done)
2329 return 0;
2330
2331 if (ret) {
2332 /* content matched */
2333 if (s->proxy->options2 & PR_O2_EXP_INV)
Simon Horman4a741432013-02-23 15:35:38 +09002334 set_server_check_status(&s->check, HCHK_STATUS_L7RSP,
Willy Tarreaubd741542010-03-16 18:46:54 +01002335 "HTTP check matched unwanted content");
2336 else
Simon Horman4a741432013-02-23 15:35:38 +09002337 set_server_check_status(&s->check, HCHK_STATUS_L7OKD,
Willy Tarreaubd741542010-03-16 18:46:54 +01002338 "HTTP content check matched");
2339 }
2340 else {
2341 if (s->proxy->options2 & PR_O2_EXP_INV)
Simon Horman4a741432013-02-23 15:35:38 +09002342 set_server_check_status(&s->check, HCHK_STATUS_L7OKD,
Willy Tarreaubd741542010-03-16 18:46:54 +01002343 "HTTP check did not match unwanted content");
2344 else
Simon Horman4a741432013-02-23 15:35:38 +09002345 set_server_check_status(&s->check, HCHK_STATUS_L7RSP,
Willy Tarreaubd741542010-03-16 18:46:54 +01002346 "HTTP content check did not match");
2347 }
2348 break;
2349 }
2350 return 1;
2351}
2352
Baptiste Assmann5ecb77f2013-10-06 23:24:13 +02002353/*
2354 * return the id of a step in a send/expect session
2355 */
Simon Hormane16c1b32015-01-30 11:22:57 +09002356static int tcpcheck_get_step_id(struct check *check)
Baptiste Assmann5ecb77f2013-10-06 23:24:13 +02002357{
2358 struct tcpcheck_rule *cur = NULL, *next = NULL;
2359 int i = 0;
2360
Willy Tarreau213c6782014-10-02 14:51:02 +02002361 /* not even started anything yet => step 0 = initial connect */
Simon Hormane16c1b32015-01-30 11:22:57 +09002362 if (check->current_step)
Willy Tarreau213c6782014-10-02 14:51:02 +02002363 return 0;
2364
Simon Hormane16c1b32015-01-30 11:22:57 +09002365 cur = check->last_started_step;
Baptiste Assmann5ecb77f2013-10-06 23:24:13 +02002366
2367 /* no step => first step */
2368 if (cur == NULL)
2369 return 1;
2370
2371 /* increment i until current step */
Simon Hormane16c1b32015-01-30 11:22:57 +09002372 list_for_each_entry(next, check->tcpcheck_rules, list) {
Baptiste Assmann5ecb77f2013-10-06 23:24:13 +02002373 if (next->list.p == &cur->list)
2374 break;
2375 ++i;
2376 }
2377
2378 return i;
2379}
2380
2381static void tcpcheck_main(struct connection *conn)
2382{
2383 char *contentptr;
Willy Tarreauf3d34822014-12-08 12:11:28 +01002384 struct tcpcheck_rule *cur, *next;
Baptiste Assmann5ecb77f2013-10-06 23:24:13 +02002385 int done = 0, ret = 0;
Baptiste Assmann5ecb77f2013-10-06 23:24:13 +02002386 struct check *check = conn->owner;
2387 struct server *s = check->server;
2388 struct task *t = check->task;
Simon Hormane16c1b32015-01-30 11:22:57 +09002389 struct list *head = check->tcpcheck_rules;
Baptiste Assmann5ecb77f2013-10-06 23:24:13 +02002390
Willy Tarreauef953952014-10-02 14:30:14 +02002391 /* here, we know that the check is complete or that it failed */
2392 if (check->result != CHK_RES_UNKNOWN)
2393 goto out_end_tcpcheck;
2394
2395 /* We have 4 possibilities here :
2396 * 1. we've not yet attempted step 1, and step 1 is a connect, so no
2397 * connection attempt was made yet ;
2398 * 2. we've not yet attempted step 1, and step 1 is a not connect or
2399 * does not exist (no rule), so a connection attempt was made
2400 * before coming here.
2401 * 3. we're coming back after having started with step 1, so we may
2402 * be waiting for a connection attempt to complete.
2403 * 4. the connection + handshake are complete
2404 *
2405 * #2 and #3 are quite similar, we want both the connection and the
2406 * handshake to complete before going any further. Thus we must always
2407 * wait for a connection to complete unless we're before and existing
2408 * step 1.
Baptiste Assmann69e273f2013-12-11 00:52:19 +01002409 */
Willy Tarreauef953952014-10-02 14:30:14 +02002410 if ((!(conn->flags & CO_FL_CONNECTED) || (conn->flags & CO_FL_HANDSHAKE)) &&
2411 (check->current_step || LIST_ISEMPTY(head))) {
Baptiste Assmann5ecb77f2013-10-06 23:24:13 +02002412 /* we allow up to min(inter, timeout.connect) for a connection
2413 * to establish but only when timeout.check is set
2414 * as it may be to short for a full check otherwise
2415 */
2416 while (tick_is_expired(t->expire, now_ms)) {
2417 int t_con;
2418
2419 t_con = tick_add(t->expire, s->proxy->timeout.connect);
2420 t->expire = tick_add(t->expire, MS_TO_TICKS(check->inter));
2421
2422 if (s->proxy->timeout.check)
2423 t->expire = tick_first(t->expire, t_con);
2424 }
2425 return;
2426 }
2427
Willy Tarreauef953952014-10-02 14:30:14 +02002428 /* special case: option tcp-check with no rule, a connect is enough */
2429 if (LIST_ISEMPTY(head)) {
2430 set_server_check_status(check, HCHK_STATUS_L4OK, NULL);
Baptiste Assmann5ecb77f2013-10-06 23:24:13 +02002431 goto out_end_tcpcheck;
Willy Tarreauef953952014-10-02 14:30:14 +02002432 }
Baptiste Assmann5ecb77f2013-10-06 23:24:13 +02002433
Willy Tarreau213c6782014-10-02 14:51:02 +02002434 /* no step means first step initialisation */
Baptiste Assmann5ecb77f2013-10-06 23:24:13 +02002435 if (check->current_step == NULL) {
Willy Tarreau213c6782014-10-02 14:51:02 +02002436 check->last_started_step = NULL;
Baptiste Assmann5ecb77f2013-10-06 23:24:13 +02002437 check->bo->p = check->bo->data;
2438 check->bo->o = 0;
2439 check->bi->p = check->bi->data;
2440 check->bi->i = 0;
2441 cur = check->current_step = LIST_ELEM(head->n, struct tcpcheck_rule *, list);
2442 t->expire = tick_add(now_ms, MS_TO_TICKS(check->inter));
2443 if (s->proxy->timeout.check)
2444 t->expire = tick_add_ifset(now_ms, s->proxy->timeout.check);
2445 }
2446 /* keep on processing step */
2447 else {
2448 cur = check->current_step;
2449 }
2450
Willy Tarreaufbe0edf2013-12-06 16:54:31 +01002451 /* It's only the rules which will enable send/recv */
2452 __conn_data_stop_both(conn);
2453
Willy Tarreauabca5b62013-12-06 14:19:25 +01002454 while (1) {
Willy Tarreaufbe0edf2013-12-06 16:54:31 +01002455 /* we have to try to flush the output buffer before reading, at the end,
2456 * or if we're about to send a string that does not fit in the remaining space.
2457 */
2458 if (check->bo->o &&
2459 (&cur->list == head ||
2460 check->current_step->action != TCPCHK_ACT_SEND ||
2461 check->current_step->string_len >= buffer_total_space(check->bo))) {
2462
Willy Tarreau1049b1f2014-02-02 01:51:17 +01002463 if (conn->xprt->snd_buf(conn, check->bo, 0) <= 0) {
Willy Tarreaufbe0edf2013-12-06 16:54:31 +01002464 if (conn->flags & CO_FL_ERROR) {
2465 chk_report_conn_err(conn, errno, 0);
2466 __conn_data_stop_both(conn);
2467 goto out_end_tcpcheck;
2468 }
2469 goto out_need_io;
Willy Tarreauabca5b62013-12-06 14:19:25 +01002470 }
Willy Tarreauabca5b62013-12-06 14:19:25 +01002471 }
2472
Willy Tarreaufbe0edf2013-12-06 16:54:31 +01002473 /* did we reach the end ? If so, let's check that everything was sent */
2474 if (&cur->list == head) {
2475 if (check->bo->o)
2476 goto out_need_io;
Willy Tarreauabca5b62013-12-06 14:19:25 +01002477 break;
Willy Tarreaufbe0edf2013-12-06 16:54:31 +01002478 }
Willy Tarreauabca5b62013-12-06 14:19:25 +01002479
Willy Tarreauf3d34822014-12-08 12:11:28 +01002480 /* have 'next' point to the next rule or NULL if we're on the last one */
2481 next = (struct tcpcheck_rule *)cur->list.n;
2482 if (&next->list == head)
2483 next = NULL;
2484
Baptiste Assmann69e273f2013-12-11 00:52:19 +01002485 if (check->current_step->action == TCPCHK_ACT_CONNECT) {
2486 struct protocol *proto;
2487 struct xprt_ops *xprt;
2488
2489 /* mark the step as started */
2490 check->last_started_step = check->current_step;
2491 /* first, shut existing connection */
2492 conn_force_close(conn);
2493
2494 /* prepare new connection */
2495 /* initialization */
2496 conn_init(conn);
2497 conn_attach(conn, check, &check_conn_cb);
2498 conn->target = &s->obj_type;
2499
2500 /* no client address */
2501 clear_addr(&conn->addr.from);
2502
Simon Horman41f58762015-01-30 11:22:56 +09002503 if (is_addr(&check->addr)) {
Baptiste Assmann69e273f2013-12-11 00:52:19 +01002504 /* we'll connect to the check addr specified on the server */
Simon Horman41f58762015-01-30 11:22:56 +09002505 conn->addr.to = check->addr;
Willy Tarreau640556c2014-05-09 23:38:15 +02002506 }
2507 else {
Baptiste Assmann69e273f2013-12-11 00:52:19 +01002508 /* we'll connect to the addr on the server */
2509 conn->addr.to = s->addr;
Willy Tarreau640556c2014-05-09 23:38:15 +02002510 }
Thierry FOURNIERbb2ae642015-01-14 11:31:49 +01002511 proto = protocol_by_family(conn->addr.to.ss_family);
Baptiste Assmann69e273f2013-12-11 00:52:19 +01002512
2513 /* port */
2514 if (check->current_step->port)
2515 set_host_port(&conn->addr.to, check->current_step->port);
2516 else if (check->port)
2517 set_host_port(&conn->addr.to, check->port);
2518
2519#ifdef USE_OPENSSL
2520 if (check->current_step->conn_opts & TCPCHK_OPT_SSL) {
2521 xprt = &ssl_sock;
Baptiste Assmann69e273f2013-12-11 00:52:19 +01002522 }
2523 else {
2524 xprt = &raw_sock;
2525 }
2526#else /* USE_OPENSSL */
2527 xprt = &raw_sock;
2528#endif /* USE_OPENSSL */
2529 conn_prepare(conn, proto, xprt);
2530
2531 ret = SN_ERR_INTERNAL;
2532 if (proto->connect)
Willy Tarreauf3d34822014-12-08 12:11:28 +01002533 ret = proto->connect(conn,
2534 1 /* I/O polling is always needed */,
2535 (next && next->action == TCPCHK_ACT_EXPECT) ? 0 : 2);
Baptiste Assmann69e273f2013-12-11 00:52:19 +01002536 conn->flags |= CO_FL_WAKE_DATA;
2537 if (check->current_step->conn_opts & TCPCHK_OPT_SEND_PROXY) {
2538 conn->send_proxy_ofs = 1;
2539 conn->flags |= CO_FL_SEND_PROXY;
2540 }
2541
2542 /* It can return one of :
2543 * - SN_ERR_NONE if everything's OK
2544 * - SN_ERR_SRVTO if there are no more servers
2545 * - SN_ERR_SRVCL if the connection was refused by the server
2546 * - SN_ERR_PRXCOND if the connection has been limited by the proxy (maxconn)
2547 * - SN_ERR_RESOURCE if a system resource is lacking (eg: fd limits, ports, ...)
2548 * - SN_ERR_INTERNAL for any other purely internal errors
2549 * Additionnally, in the case of SN_ERR_RESOURCE, an emergency log will be emitted.
2550 * Note that we try to prevent the network stack from sending the ACK during the
2551 * connect() when a pure TCP check is used (without PROXY protocol).
2552 */
2553 switch (ret) {
2554 case SN_ERR_NONE:
2555 /* we allow up to min(inter, timeout.connect) for a connection
2556 * to establish but only when timeout.check is set
2557 * as it may be to short for a full check otherwise
2558 */
2559 t->expire = tick_add(now_ms, MS_TO_TICKS(check->inter));
2560
2561 if (s->proxy->timeout.check && s->proxy->timeout.connect) {
2562 int t_con = tick_add(now_ms, s->proxy->timeout.connect);
2563 t->expire = tick_first(t->expire, t_con);
2564 }
2565 break;
2566 case SN_ERR_SRVTO: /* ETIMEDOUT */
2567 case SN_ERR_SRVCL: /* ECONNREFUSED, ENETUNREACH, ... */
2568 chunk_printf(&trash, "TCPCHK error establishing connection at step %d: %s",
Simon Hormane16c1b32015-01-30 11:22:57 +09002569 tcpcheck_get_step_id(check), strerror(errno));
Baptiste Assmann69e273f2013-12-11 00:52:19 +01002570 set_server_check_status(check, HCHK_STATUS_L4CON, trash.str);
2571 goto out_end_tcpcheck;
2572 case SN_ERR_PRXCOND:
2573 case SN_ERR_RESOURCE:
2574 case SN_ERR_INTERNAL:
2575 chunk_printf(&trash, "TCPCHK error establishing connection at step %d",
Simon Hormane16c1b32015-01-30 11:22:57 +09002576 tcpcheck_get_step_id(check));
Baptiste Assmann69e273f2013-12-11 00:52:19 +01002577 set_server_check_status(check, HCHK_STATUS_SOCKERR, trash.str);
2578 goto out_end_tcpcheck;
2579 }
2580
2581 /* allow next rule */
2582 cur = (struct tcpcheck_rule *)cur->list.n;
2583 check->current_step = cur;
2584
2585 /* don't do anything until the connection is established */
2586 if (!(conn->flags & CO_FL_CONNECTED)) {
2587 /* update expire time, should be done by process_chk */
2588 /* we allow up to min(inter, timeout.connect) for a connection
2589 * to establish but only when timeout.check is set
2590 * as it may be to short for a full check otherwise
2591 */
2592 while (tick_is_expired(t->expire, now_ms)) {
2593 int t_con;
2594
2595 t_con = tick_add(t->expire, s->proxy->timeout.connect);
2596 t->expire = tick_add(t->expire, MS_TO_TICKS(check->inter));
2597
2598 if (s->proxy->timeout.check)
2599 t->expire = tick_first(t->expire, t_con);
2600 }
2601 return;
2602 }
2603
2604 } /* end 'connect' */
2605 else if (check->current_step->action == TCPCHK_ACT_SEND) {
2606 /* mark the step as started */
2607 check->last_started_step = check->current_step;
2608
Baptiste Assmann5ecb77f2013-10-06 23:24:13 +02002609 /* reset the read buffer */
2610 if (*check->bi->data != '\0') {
2611 *check->bi->data = '\0';
2612 check->bi->i = 0;
2613 }
2614
2615 if (conn->flags & (CO_FL_SOCK_WR_SH | CO_FL_DATA_WR_SH)) {
2616 conn->flags |= CO_FL_ERROR;
2617 chk_report_conn_err(conn, 0, 0);
2618 goto out_end_tcpcheck;
2619 }
2620
Willy Tarreauabca5b62013-12-06 14:19:25 +01002621 if (check->current_step->string_len >= check->bo->size) {
2622 chunk_printf(&trash, "tcp-check send : string too large (%d) for buffer size (%d) at step %d",
2623 check->current_step->string_len, check->bo->size,
Simon Hormane16c1b32015-01-30 11:22:57 +09002624 tcpcheck_get_step_id(check));
Willy Tarreauabca5b62013-12-06 14:19:25 +01002625 set_server_check_status(check, HCHK_STATUS_L7RSP, trash.str);
2626 goto out_end_tcpcheck;
2627 }
Baptiste Assmann5ecb77f2013-10-06 23:24:13 +02002628
Willy Tarreaufbe0edf2013-12-06 16:54:31 +01002629 /* do not try to send if there is no space */
2630 if (check->current_step->string_len >= buffer_total_space(check->bo))
2631 continue;
2632
Baptiste Assmann5ecb77f2013-10-06 23:24:13 +02002633 bo_putblk(check->bo, check->current_step->string, check->current_step->string_len);
2634 *check->bo->p = '\0'; /* to make gdb output easier to read */
2635
Willy Tarreauabca5b62013-12-06 14:19:25 +01002636 /* go to next rule and try to send */
Baptiste Assmann5ecb77f2013-10-06 23:24:13 +02002637 cur = (struct tcpcheck_rule *)cur->list.n;
2638 check->current_step = cur;
Baptiste Assmann5ecb77f2013-10-06 23:24:13 +02002639 } /* end 'send' */
Willy Tarreau98aec9f2013-12-06 16:16:41 +01002640 else if (check->current_step->action == TCPCHK_ACT_EXPECT) {
Willy Tarreau6aaa1b82013-12-11 17:09:34 +01002641 if (unlikely(check->result == CHK_RES_FAILED))
Baptiste Assmann5ecb77f2013-10-06 23:24:13 +02002642 goto out_end_tcpcheck;
2643
Willy Tarreau310987a2014-01-22 19:46:33 +01002644 if (conn->xprt->rcv_buf(conn, check->bi, check->bi->size) <= 0) {
Willy Tarreaufbe0edf2013-12-06 16:54:31 +01002645 if (conn->flags & (CO_FL_ERROR | CO_FL_SOCK_RD_SH | CO_FL_DATA_RD_SH)) {
2646 done = 1;
2647 if ((conn->flags & CO_FL_ERROR) && !check->bi->i) {
2648 /* Report network errors only if we got no other data. Otherwise
2649 * we'll let the upper layers decide whether the response is OK
2650 * or not. It is very common that an RST sent by the server is
2651 * reported as an error just after the last data chunk.
2652 */
2653 chk_report_conn_err(conn, errno, 0);
2654 goto out_end_tcpcheck;
2655 }
Baptiste Assmann5ecb77f2013-10-06 23:24:13 +02002656 }
Willy Tarreaufbe0edf2013-12-06 16:54:31 +01002657 else
2658 goto out_need_io;
Baptiste Assmann5ecb77f2013-10-06 23:24:13 +02002659 }
2660
Baptiste Assmann69e273f2013-12-11 00:52:19 +01002661 /* mark the step as started */
2662 check->last_started_step = check->current_step;
2663
2664
Baptiste Assmann5ecb77f2013-10-06 23:24:13 +02002665 /* Intermediate or complete response received.
2666 * Terminate string in check->bi->data buffer.
2667 */
2668 if (check->bi->i < check->bi->size) {
2669 check->bi->data[check->bi->i] = '\0';
2670 }
2671 else {
2672 check->bi->data[check->bi->i - 1] = '\0';
2673 done = 1; /* buffer full, don't wait for more data */
2674 }
2675
2676 contentptr = check->bi->data;
Baptiste Assmann5ecb77f2013-10-06 23:24:13 +02002677
2678 /* Check that response body is not empty... */
Willy Tarreauec6b0122014-05-13 17:57:29 +02002679 if (!check->bi->i) {
Baptiste Assmann5ecb77f2013-10-06 23:24:13 +02002680 if (!done)
Willy Tarreaufbe0edf2013-12-06 16:54:31 +01002681 continue;
Baptiste Assmann5ecb77f2013-10-06 23:24:13 +02002682
2683 /* empty response */
2684 chunk_printf(&trash, "TCPCHK got an empty response at step %d",
Simon Hormane16c1b32015-01-30 11:22:57 +09002685 tcpcheck_get_step_id(check));
Baptiste Assmann5ecb77f2013-10-06 23:24:13 +02002686 set_server_check_status(check, HCHK_STATUS_L7RSP, trash.str);
2687
2688 goto out_end_tcpcheck;
2689 }
2690
2691 if (!done && (cur->string != NULL) && (check->bi->i < cur->string_len) )
Willy Tarreaua970c282013-12-06 12:47:19 +01002692 continue; /* try to read more */
Baptiste Assmann5ecb77f2013-10-06 23:24:13 +02002693
Willy Tarreaua970c282013-12-06 12:47:19 +01002694 tcpcheck_expect:
Baptiste Assmann5ecb77f2013-10-06 23:24:13 +02002695 if (cur->string != NULL)
Willy Tarreauec6b0122014-05-13 17:57:29 +02002696 ret = my_memmem(contentptr, check->bi->i, cur->string, cur->string_len) != NULL;
Baptiste Assmann5ecb77f2013-10-06 23:24:13 +02002697 else if (cur->expect_regex != NULL)
Thierry FOURNIER09af0d62014-06-18 11:35:54 +02002698 ret = regex_exec(cur->expect_regex, contentptr);
Baptiste Assmann5ecb77f2013-10-06 23:24:13 +02002699
2700 if (!ret && !done)
Willy Tarreaua970c282013-12-06 12:47:19 +01002701 continue; /* try to read more */
Baptiste Assmann5ecb77f2013-10-06 23:24:13 +02002702
2703 /* matched */
2704 if (ret) {
2705 /* matched but we did not want to => ERROR */
2706 if (cur->inverse) {
2707 /* we were looking for a string */
2708 if (cur->string != NULL) {
2709 chunk_printf(&trash, "TCPCHK matched unwanted content '%s' at step %d",
Simon Hormane16c1b32015-01-30 11:22:57 +09002710 cur->string, tcpcheck_get_step_id(check));
Baptiste Assmann5ecb77f2013-10-06 23:24:13 +02002711 }
2712 else {
2713 /* we were looking for a regex */
2714 chunk_printf(&trash, "TCPCHK matched unwanted content (regex) at step %d",
Simon Hormane16c1b32015-01-30 11:22:57 +09002715 tcpcheck_get_step_id(check));
Baptiste Assmann5ecb77f2013-10-06 23:24:13 +02002716 }
2717 set_server_check_status(check, HCHK_STATUS_L7RSP, trash.str);
2718 goto out_end_tcpcheck;
2719 }
2720 /* matched and was supposed to => OK, next step */
2721 else {
2722 cur = (struct tcpcheck_rule*)cur->list.n;
2723 check->current_step = cur;
Willy Tarreau98aec9f2013-12-06 16:16:41 +01002724 if (check->current_step->action == TCPCHK_ACT_EXPECT)
Baptiste Assmann5ecb77f2013-10-06 23:24:13 +02002725 goto tcpcheck_expect;
2726 __conn_data_stop_recv(conn);
2727 }
2728 }
2729 else {
2730 /* not matched */
2731 /* not matched and was not supposed to => OK, next step */
2732 if (cur->inverse) {
2733 cur = (struct tcpcheck_rule*)cur->list.n;
2734 check->current_step = cur;
Willy Tarreau98aec9f2013-12-06 16:16:41 +01002735 if (check->current_step->action == TCPCHK_ACT_EXPECT)
Baptiste Assmann5ecb77f2013-10-06 23:24:13 +02002736 goto tcpcheck_expect;
2737 __conn_data_stop_recv(conn);
2738 }
2739 /* not matched but was supposed to => ERROR */
2740 else {
2741 /* we were looking for a string */
2742 if (cur->string != NULL) {
2743 chunk_printf(&trash, "TCPCHK did not match content '%s' at step %d",
Simon Hormane16c1b32015-01-30 11:22:57 +09002744 cur->string, tcpcheck_get_step_id(check));
Baptiste Assmann5ecb77f2013-10-06 23:24:13 +02002745 }
2746 else {
2747 /* we were looking for a regex */
2748 chunk_printf(&trash, "TCPCHK did not match content (regex) at step %d",
Simon Hormane16c1b32015-01-30 11:22:57 +09002749 tcpcheck_get_step_id(check));
Baptiste Assmann5ecb77f2013-10-06 23:24:13 +02002750 }
2751 set_server_check_status(check, HCHK_STATUS_L7RSP, trash.str);
2752 goto out_end_tcpcheck;
2753 }
2754 }
2755 } /* end expect */
2756 } /* end loop over double chained step list */
2757
2758 set_server_check_status(check, HCHK_STATUS_L7OKD, "(tcp-check)");
2759 goto out_end_tcpcheck;
2760
Willy Tarreaufbe0edf2013-12-06 16:54:31 +01002761 out_need_io:
2762 if (check->bo->o)
2763 __conn_data_want_send(conn);
2764
2765 if (check->current_step->action == TCPCHK_ACT_EXPECT)
2766 __conn_data_want_recv(conn);
Baptiste Assmann5ecb77f2013-10-06 23:24:13 +02002767 return;
2768
2769 out_end_tcpcheck:
2770 /* collect possible new errors */
2771 if (conn->flags & CO_FL_ERROR)
2772 chk_report_conn_err(conn, 0, 0);
2773
Baptiste Assmann69e273f2013-12-11 00:52:19 +01002774 /* cleanup before leaving */
Baptiste Assmann5ecb77f2013-10-06 23:24:13 +02002775 check->current_step = NULL;
2776
Willy Tarreau6aaa1b82013-12-11 17:09:34 +01002777 if (check->result == CHK_RES_FAILED)
Baptiste Assmann5ecb77f2013-10-06 23:24:13 +02002778 conn->flags |= CO_FL_ERROR;
2779
2780 __conn_data_stop_both(conn);
Baptiste Assmann5ecb77f2013-10-06 23:24:13 +02002781
2782 return;
2783}
2784
Simon Hormanb1900d52015-01-30 11:22:54 +09002785const char *init_check(struct check *check, int type)
2786{
2787 check->type = type;
2788
2789 /* Allocate buffer for requests... */
2790 if ((check->bi = calloc(sizeof(struct buffer) + global.tune.chksize, sizeof(char))) == NULL) {
2791 return "out of memory while allocating check buffer";
2792 }
2793 check->bi->size = global.tune.chksize;
2794
2795 /* Allocate buffer for responses... */
2796 if ((check->bo = calloc(sizeof(struct buffer) + global.tune.chksize, sizeof(char))) == NULL) {
2797 return "out of memory while allocating check buffer";
2798 }
2799 check->bo->size = global.tune.chksize;
2800
2801 /* Allocate buffer for partial results... */
2802 if ((check->conn = calloc(1, sizeof(struct connection))) == NULL) {
2803 return "out of memory while allocating check connection";
2804 }
2805
2806 check->conn->t.sock.fd = -1; /* no agent in progress yet */
2807
2808 return NULL;
2809}
2810
Simon Hormanbfb5d332015-01-30 11:22:55 +09002811void free_check(struct check *check)
2812{
2813 free(check->bi);
2814 free(check->bo);
2815 free(check->conn);
2816}
2817
Simon Horman0ba0e4a2015-01-30 11:23:00 +09002818void email_alert_free(struct email_alert *alert)
2819{
2820 struct tcpcheck_rule *rule, *back;
2821
2822 if (!alert)
2823 return;
2824
2825 list_for_each_entry_safe(rule, back, &alert->tcpcheck_rules, list)
2826 free(rule);
2827 free(alert);
2828}
2829
2830static struct task *process_email_alert(struct task *t)
2831{
2832 struct check *check = t->context;
2833 struct email_alertq *q;
2834
2835 q = container_of(check, typeof(*q), check);
2836
2837 if (!(check->state & CHK_ST_ENABLED)) {
2838 if (LIST_ISEMPTY(&q->email_alerts)) {
2839 /* All alerts processed, delete check */
2840 task_delete(t);
2841 task_free(t);
2842 check->task = NULL;
2843 return NULL;
2844 } else {
2845 struct email_alert *alert;
2846
2847 alert = LIST_NEXT(&q->email_alerts, typeof(alert), list);
2848 check->tcpcheck_rules = &alert->tcpcheck_rules;
2849 LIST_DEL(&alert->list);
2850
2851 check->state |= CHK_ST_ENABLED;
2852 }
2853
2854 }
2855
2856 process_chk(t);
2857
2858 if (!(check->state & CHK_ST_INPROGRESS) && check->tcpcheck_rules) {
2859 struct email_alert *alert;
2860
2861 alert = container_of(check->tcpcheck_rules, typeof(*alert), tcpcheck_rules);
2862 email_alert_free(alert);
2863
2864 check->tcpcheck_rules = NULL;
2865 check->state &= ~CHK_ST_ENABLED;
2866 }
2867 return t;
2868}
2869
2870static int init_email_alert_checks(struct server *s)
2871{
2872 int i;
2873 struct mailer *mailer;
2874 const char *err_str;
2875 struct proxy *p = s->proxy;
2876
2877 if (p->email_alert.queues)
2878 /* Already initialised, nothing to do */
2879 return 1;
2880
2881 p->email_alert.queues = calloc(p->email_alert.mailers.m->count, sizeof *p->email_alert.queues);
2882 if (!p->email_alert.queues) {
2883 err_str = "out of memory while allocating checks array";
2884 goto error_alert;
2885 }
2886
2887 for (i = 0, mailer = p->email_alert.mailers.m->mailer_list;
2888 i < p->email_alert.mailers.m->count; i++, mailer = mailer->next) {
2889 struct email_alertq *q = &p->email_alert.queues[i];
2890 struct check *check = &q->check;
2891
2892
2893 LIST_INIT(&q->email_alerts);
2894
2895 check->inter = DEF_CHKINTR; /* XXX: Would like to Skip to the next alert, if any, ASAP.
2896 * But need enough time so that timeouts don't occur
2897 * during tcp check procssing. For now just us an arbitrary default. */
2898 check->rise = DEF_AGENT_RISETIME;
2899 check->fall = DEF_AGENT_FALLTIME;
2900 err_str = init_check(check, PR_O2_TCPCHK_CHK);
2901 if (err_str) {
2902 goto error_free;
2903 }
2904
2905 check->xprt = mailer->xprt;
2906 if (!get_host_port(&mailer->addr))
2907 /* Default to submission port */
2908 check->port = 587;
Simon Horman0ba0e4a2015-01-30 11:23:00 +09002909 check->addr = mailer->addr;
2910 check->server = s;
2911 }
2912
2913 return 1;
2914
2915error_free:
2916 while (i-- > 1)
2917 task_free(p->email_alert.queues[i].check.task);
2918 free(p->email_alert.queues);
2919 p->email_alert.queues = NULL;
2920error_alert:
2921 Alert("Email alert [%s] could not be initialised: %s\n", p->id, err_str);
2922 return 0;
2923}
2924
2925
2926static int add_tcpcheck_expect_str(struct list *list, const char *str)
2927{
2928 struct tcpcheck_rule *tcpcheck;
2929
2930 tcpcheck = calloc(1, sizeof *tcpcheck);
2931 if (!tcpcheck)
2932 return 0;
2933
2934 tcpcheck->action = TCPCHK_ACT_EXPECT;
2935 tcpcheck->string = strdup(str);
2936 if (!tcpcheck->string) {
2937 free(tcpcheck);
2938 return 0;
2939 }
2940
2941 LIST_ADDQ(list, &tcpcheck->list);
2942 return 1;
2943}
2944
2945static int add_tcpcheck_send_strs(struct list *list, const char * const *strs)
2946{
2947 struct tcpcheck_rule *tcpcheck;
2948 int i;
2949
2950 tcpcheck = calloc(1, sizeof *tcpcheck);
2951 if (!tcpcheck)
2952 return 0;
2953
2954 tcpcheck->action = TCPCHK_ACT_SEND;
2955
2956 tcpcheck->string_len = 0;
2957 for (i = 0; strs[i]; i++)
2958 tcpcheck->string_len += strlen(strs[i]);
2959
2960 tcpcheck->string = malloc(tcpcheck->string_len + 1);
2961 if (!tcpcheck->string) {
2962 free(tcpcheck);
2963 return 0;
2964 }
2965 tcpcheck->string[0] = '\0';
2966
2967 for (i = 0; strs[i]; i++)
2968 strcat(tcpcheck->string, strs[i]);
2969
2970 LIST_ADDQ(list, &tcpcheck->list);
2971 return 1;
2972}
2973
2974static int enqueue_one_email_alert(struct email_alertq *q, const char *msg)
2975{
2976 struct email_alert *alert = NULL;
2977 struct tcpcheck_rule *tcpcheck;
2978 struct check *check = &q->check;
2979 struct proxy *p = check->server->proxy;
2980
2981 alert = calloc(1, sizeof *alert);
2982 if (!alert) {
2983 goto error;
2984 }
2985 LIST_INIT(&alert->tcpcheck_rules);
2986
2987 tcpcheck = calloc(1, sizeof *tcpcheck);
2988 if (!tcpcheck)
2989 goto error;
2990 tcpcheck->action = TCPCHK_ACT_CONNECT;
2991 LIST_ADDQ(&alert->tcpcheck_rules, &tcpcheck->list);
2992
2993 if (!add_tcpcheck_expect_str(&alert->tcpcheck_rules, "220 "))
2994 goto error;
2995
2996 {
2997 const char * const strs[4] = { "EHLO ", p->email_alert.myhostname, "\r\n" };
2998 if (!add_tcpcheck_send_strs(&alert->tcpcheck_rules, strs))
2999 goto error;
3000 }
3001
3002 if (!add_tcpcheck_expect_str(&alert->tcpcheck_rules, "250 "))
3003 goto error;
3004
3005 {
3006 const char * const strs[4] = { "MAIL FROM:<", p->email_alert.from, ">\r\n" };
3007 if (!add_tcpcheck_send_strs(&alert->tcpcheck_rules, strs))
3008 goto error;
3009 }
3010
3011 if (!add_tcpcheck_expect_str(&alert->tcpcheck_rules, "250 "))
3012 goto error;
3013
3014 {
3015 const char * const strs[4] = { "RCPT TO:<", p->email_alert.to, ">\r\n" };
3016 if (!add_tcpcheck_send_strs(&alert->tcpcheck_rules, strs))
3017 goto error;
3018 }
3019
3020 if (!add_tcpcheck_expect_str(&alert->tcpcheck_rules, "250 "))
3021 goto error;
3022
3023 {
3024 const char * const strs[2] = { "DATA\r\n" };
3025 if (!add_tcpcheck_send_strs(&alert->tcpcheck_rules, strs))
3026 goto error;
3027 }
3028
3029 if (!add_tcpcheck_expect_str(&alert->tcpcheck_rules, "354 "))
3030 goto error;
3031
3032 {
3033 struct tm tm;
3034 char datestr[48];
3035 const char * const strs[18] = {
3036 "From: ", p->email_alert.from, "\n",
3037 "To: ", p->email_alert.to, "\n",
3038 "Date: ", datestr, "\n",
3039 "Subject: [HAproxy Alert] ", msg, "\n",
3040 "\n",
3041 msg, "\n",
3042 ".\r\n",
3043 "\r\n",
3044 NULL
3045 };
3046
3047 get_localtime(date.tv_sec, &tm);
3048
3049 if (strftime(datestr, sizeof(datestr), "%a, %d %b %Y %T %z (%Z)", &tm) == 0) {
3050 goto error;
3051 }
3052
3053 if (!add_tcpcheck_send_strs(&alert->tcpcheck_rules, strs))
3054 goto error;
3055 }
3056
3057 if (!add_tcpcheck_expect_str(&alert->tcpcheck_rules, "250 "))
3058 goto error;
3059
3060 {
3061 const char * const strs[2] = { "QUIT\r\n" };
3062 if (!add_tcpcheck_send_strs(&alert->tcpcheck_rules, strs))
3063 goto error;
3064 }
3065
3066 if (!add_tcpcheck_expect_str(&alert->tcpcheck_rules, "221 "))
3067 goto error;
3068
3069 if (!check->task) {
3070 struct task *t;
3071
3072 if ((t = task_new()) == NULL)
3073 goto error;
3074
3075 check->task = t;
3076 t->process = process_email_alert;
3077 t->context = check;
3078
3079 /* check this in one ms */
3080 t->expire = tick_add(now_ms, MS_TO_TICKS(1));
3081 check->start = now;
3082 task_queue(t);
3083 }
3084
3085 LIST_ADDQ(&q->email_alerts, &alert->list);
3086
3087 return 1;
3088
3089error:
3090 email_alert_free(alert);
3091 return 0;
3092}
3093
3094static void enqueue_email_alert(struct proxy *p, const char *msg)
3095{
3096 int i;
3097 struct mailer *mailer;
3098
3099 for (i = 0, mailer = p->email_alert.mailers.m->mailer_list;
3100 i < p->email_alert.mailers.m->count; i++, mailer = mailer->next) {
3101 if (!enqueue_one_email_alert(&p->email_alert.queues[i], msg)) {
3102 Alert("Email alert [%s] could not be enqueued: out of memory\n", p->id);
3103 return;
3104 }
3105 }
3106
3107 return;
3108}
3109
3110/*
3111 * Send email alert if configured.
3112 */
Simon Horman64e34162015-02-06 11:11:57 +09003113void send_email_alert(struct server *s, int level, const char *format, ...)
Simon Horman0ba0e4a2015-01-30 11:23:00 +09003114{
3115 va_list argp;
3116 char buf[1024];
3117 int len;
3118 struct proxy *p = s->proxy;
3119
Simon Horman64e34162015-02-06 11:11:57 +09003120 if (!p->email_alert.mailers.m || level > p->email_alert.level ||
3121 format == NULL || !init_email_alert_checks(s))
Simon Horman0ba0e4a2015-01-30 11:23:00 +09003122 return;
3123
3124 va_start(argp, format);
3125 len = vsnprintf(buf, sizeof(buf), format, argp);
3126 va_end(argp);
3127
3128 if (len < 0) {
3129 Alert("Email alert [%s] could format message\n", p->id);
3130 return;
3131 }
3132
3133 enqueue_email_alert(p, buf);
3134}
3135
Baptiste Assmann5ecb77f2013-10-06 23:24:13 +02003136
Willy Tarreaubd741542010-03-16 18:46:54 +01003137/*
Willy Tarreaubaaee002006-06-26 02:48:02 +02003138 * Local variables:
3139 * c-indent-level: 8
3140 * c-basic-offset: 8
3141 * End:
3142 */