blob: 89e5eeeb35a6d98f01a5422ab50e6c50b50cdcd3 [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;
Joseph Lynch514061c2015-01-15 17:52:59 -0800497 char addr[46];
498 char port[6];
Willy Tarreauef781042010-01-27 11:53:01 +0100499 const char *srv_hlt_st[7] = { "DOWN", "DOWN %d/%d",
500 "UP %d/%d", "UP",
501 "NOLB %d/%d", "NOLB",
502 "no check" };
503
504 memcpy(buffer + hlen, "X-Haproxy-Server-State: ", 24);
505 hlen += 24;
506
Willy Tarreauff5ae352013-12-11 20:36:34 +0100507 if (!(s->check.state & CHK_ST_ENABLED))
508 sv_state = 6;
Willy Tarreau892337c2014-05-13 23:41:20 +0200509 else if (s->state != SRV_ST_STOPPED) {
Simon Horman58c32972013-11-25 10:46:38 +0900510 if (s->check.health == s->check.rise + s->check.fall - 1)
Willy Tarreauef781042010-01-27 11:53:01 +0100511 sv_state = 3; /* UP */
512 else
513 sv_state = 2; /* going down */
514
Willy Tarreau892337c2014-05-13 23:41:20 +0200515 if (s->state == SRV_ST_STOPPING)
Willy Tarreauef781042010-01-27 11:53:01 +0100516 sv_state += 2;
517 } else {
Simon Horman125d0992013-02-24 17:23:38 +0900518 if (s->check.health)
Willy Tarreauef781042010-01-27 11:53:01 +0100519 sv_state = 1; /* going up */
520 else
521 sv_state = 0; /* DOWN */
522 }
523
Willy Tarreaua1dab552014-04-14 15:04:54 +0200524 hlen += snprintf(buffer + hlen, size - hlen,
Willy Tarreauef781042010-01-27 11:53:01 +0100525 srv_hlt_st[sv_state],
Willy Tarreau892337c2014-05-13 23:41:20 +0200526 (s->state != SRV_ST_STOPPED) ? (s->check.health - s->check.rise + 1) : (s->check.health),
527 (s->state != SRV_ST_STOPPED) ? (s->check.fall) : (s->check.rise));
Willy Tarreauef781042010-01-27 11:53:01 +0100528
Joseph Lynch514061c2015-01-15 17:52:59 -0800529 addr_to_str(&s->addr, addr, sizeof(addr));
530 port_to_str(&s->addr, port, sizeof(port));
531
532 hlen += snprintf(buffer + hlen, size - hlen, "; address=%s; port=%s; name=%s/%s; node=%s; weight=%d/%d; scur=%d/%d; qcur=%d",
533 addr, port, s->proxy->id, s->id,
Willy Tarreauef781042010-01-27 11:53:01 +0100534 global.node,
535 (s->eweight * s->proxy->lbprm.wmult + s->proxy->lbprm.wdiv - 1) / s->proxy->lbprm.wdiv,
536 (s->proxy->lbprm.tot_weight * s->proxy->lbprm.wmult + s->proxy->lbprm.wdiv - 1) / s->proxy->lbprm.wdiv,
537 s->cur_sess, s->proxy->beconn - s->proxy->nbpend,
538 s->nbpend);
539
Willy Tarreau892337c2014-05-13 23:41:20 +0200540 if ((s->state == SRV_ST_STARTING) &&
Willy Tarreauef781042010-01-27 11:53:01 +0100541 now.tv_sec < s->last_change + s->slowstart &&
542 now.tv_sec >= s->last_change) {
543 ratio = MAX(1, 100 * (now.tv_sec - s->last_change) / s->slowstart);
Willy Tarreaua1dab552014-04-14 15:04:54 +0200544 hlen += snprintf(buffer + hlen, size - hlen, "; throttle=%d%%", ratio);
Willy Tarreauef781042010-01-27 11:53:01 +0100545 }
546
547 buffer[hlen++] = '\r';
548 buffer[hlen++] = '\n';
549
550 return hlen;
551}
552
Willy Tarreau20a18342013-12-05 00:31:46 +0100553/* Check the connection. If an error has already been reported or the socket is
554 * closed, keep errno intact as it is supposed to contain the valid error code.
555 * If no error is reported, check the socket's error queue using getsockopt().
556 * Warning, this must be done only once when returning from poll, and never
557 * after an I/O error was attempted, otherwise the error queue might contain
558 * inconsistent errors. If an error is detected, the CO_FL_ERROR is set on the
559 * socket. Returns non-zero if an error was reported, zero if everything is
560 * clean (including a properly closed socket).
561 */
562static int retrieve_errno_from_socket(struct connection *conn)
563{
564 int skerr;
565 socklen_t lskerr = sizeof(skerr);
566
567 if (conn->flags & CO_FL_ERROR && ((errno && errno != EAGAIN) || !conn->ctrl))
568 return 1;
569
Willy Tarreau3c728722014-01-23 13:50:42 +0100570 if (!conn_ctrl_ready(conn))
Willy Tarreau20a18342013-12-05 00:31:46 +0100571 return 0;
572
573 if (getsockopt(conn->t.sock.fd, SOL_SOCKET, SO_ERROR, &skerr, &lskerr) == 0)
574 errno = skerr;
575
576 if (errno == EAGAIN)
577 errno = 0;
578
579 if (!errno) {
580 /* we could not retrieve an error, that does not mean there is
581 * none. Just don't change anything and only report the prior
582 * error if any.
583 */
584 if (conn->flags & CO_FL_ERROR)
585 return 1;
586 else
587 return 0;
588 }
589
590 conn->flags |= CO_FL_ERROR | CO_FL_SOCK_WR_SH | CO_FL_SOCK_RD_SH;
591 return 1;
592}
593
Willy Tarreau25e2ab52013-12-04 11:17:05 +0100594/* Try to collect as much information as possible on the connection status,
595 * and adjust the server status accordingly. It may make use of <errno_bck>
596 * if non-null when the caller is absolutely certain of its validity (eg:
597 * checked just after a syscall). If the caller doesn't have a valid errno,
598 * it can pass zero, and retrieve_errno_from_socket() will be called to try
599 * to extract errno from the socket. If no error is reported, it will consider
600 * the <expired> flag. This is intended to be used when a connection error was
601 * reported in conn->flags or when a timeout was reported in <expired>. The
602 * function takes care of not updating a server status which was already set.
603 * All situations where at least one of <expired> or CO_FL_ERROR are set
604 * produce a status.
605 */
606static void chk_report_conn_err(struct connection *conn, int errno_bck, int expired)
607{
608 struct check *check = conn->owner;
609 const char *err_msg;
Baptiste Assmann5ecb77f2013-10-06 23:24:13 +0200610 struct chunk *chk;
Willy Tarreau213c6782014-10-02 14:51:02 +0200611 int step;
Willy Tarreau25e2ab52013-12-04 11:17:05 +0100612
Willy Tarreau6aaa1b82013-12-11 17:09:34 +0100613 if (check->result != CHK_RES_UNKNOWN)
Willy Tarreau25e2ab52013-12-04 11:17:05 +0100614 return;
615
616 errno = errno_bck;
617 if (!errno || errno == EAGAIN)
618 retrieve_errno_from_socket(conn);
619
620 if (!(conn->flags & CO_FL_ERROR) && !expired)
621 return;
622
623 /* we'll try to build a meaningful error message depending on the
624 * context of the error possibly present in conn->err_code, and the
625 * socket error possibly collected above. This is useful to know the
626 * exact step of the L6 layer (eg: SSL handshake).
627 */
Baptiste Assmann5ecb77f2013-10-06 23:24:13 +0200628 chk = get_trash_chunk();
629
630 if (check->type == PR_O2_TCPCHK_CHK) {
Simon Hormane16c1b32015-01-30 11:22:57 +0900631 step = tcpcheck_get_step_id(check);
Willy Tarreau213c6782014-10-02 14:51:02 +0200632 if (!step)
633 chunk_printf(chk, " at initial connection step of tcp-check");
634 else {
635 chunk_printf(chk, " at step %d of tcp-check", step);
636 /* we were looking for a string */
637 if (check->last_started_step && check->last_started_step->action == TCPCHK_ACT_CONNECT) {
638 if (check->last_started_step->port)
639 chunk_appendf(chk, " (connect port %d)" ,check->last_started_step->port);
640 else
641 chunk_appendf(chk, " (connect)");
642 }
643 else if (check->last_started_step && check->last_started_step->action == TCPCHK_ACT_EXPECT) {
644 if (check->last_started_step->string)
645 chunk_appendf(chk, " (string '%s')", check->last_started_step->string);
646 else if (check->last_started_step->expect_regex)
647 chunk_appendf(chk, " (expect regex)");
648 }
649 else if (check->last_started_step && check->last_started_step->action == TCPCHK_ACT_SEND) {
650 chunk_appendf(chk, " (send)");
651 }
Baptiste Assmann5ecb77f2013-10-06 23:24:13 +0200652 }
653 }
654
Willy Tarreau25e2ab52013-12-04 11:17:05 +0100655 if (conn->err_code) {
656 if (errno && errno != EAGAIN)
Baptiste Assmann5ecb77f2013-10-06 23:24:13 +0200657 chunk_printf(&trash, "%s (%s)%s", conn_err_code_str(conn), strerror(errno), chk->str);
Willy Tarreau25e2ab52013-12-04 11:17:05 +0100658 else
Baptiste Assmann5ecb77f2013-10-06 23:24:13 +0200659 chunk_printf(&trash, "%s%s", conn_err_code_str(conn), chk->str);
Willy Tarreau25e2ab52013-12-04 11:17:05 +0100660 err_msg = trash.str;
661 }
662 else {
663 if (errno && errno != EAGAIN) {
Baptiste Assmann5ecb77f2013-10-06 23:24:13 +0200664 chunk_printf(&trash, "%s%s", strerror(errno), chk->str);
Willy Tarreau25e2ab52013-12-04 11:17:05 +0100665 err_msg = trash.str;
666 }
667 else {
Baptiste Assmann5ecb77f2013-10-06 23:24:13 +0200668 err_msg = chk->str;
Willy Tarreau25e2ab52013-12-04 11:17:05 +0100669 }
670 }
671
672 if ((conn->flags & (CO_FL_CONNECTED|CO_FL_WAIT_L4_CONN)) == CO_FL_WAIT_L4_CONN) {
673 /* L4 not established (yet) */
674 if (conn->flags & CO_FL_ERROR)
675 set_server_check_status(check, HCHK_STATUS_L4CON, err_msg);
676 else if (expired)
677 set_server_check_status(check, HCHK_STATUS_L4TOUT, err_msg);
678 }
679 else if ((conn->flags & (CO_FL_CONNECTED|CO_FL_WAIT_L6_CONN)) == CO_FL_WAIT_L6_CONN) {
680 /* L6 not established (yet) */
681 if (conn->flags & CO_FL_ERROR)
682 set_server_check_status(check, HCHK_STATUS_L6RSP, err_msg);
683 else if (expired)
684 set_server_check_status(check, HCHK_STATUS_L6TOUT, err_msg);
685 }
686 else if (conn->flags & CO_FL_ERROR) {
687 /* I/O error after connection was established and before we could diagnose */
688 set_server_check_status(check, HCHK_STATUS_SOCKERR, err_msg);
689 }
690 else if (expired) {
691 /* connection established but expired check */
692 if (check->type == PR_O2_SSL3_CHK)
693 set_server_check_status(check, HCHK_STATUS_L6TOUT, err_msg);
694 else /* HTTP, SMTP, ... */
695 set_server_check_status(check, HCHK_STATUS_L7TOUT, err_msg);
696 }
697
698 return;
699}
700
Willy Tarreaubaaee002006-06-26 02:48:02 +0200701/*
702 * This function is used only for server health-checks. It handles
Krzysztof Piotr Oledzki213014e2009-09-27 15:50:02 +0200703 * the connection acknowledgement. If the proxy requires L7 health-checks,
704 * it sends the request. In other cases, it calls set_server_check_status()
Simon Horman4a741432013-02-23 15:35:38 +0900705 * to set check->status, check->duration and check->result.
Willy Tarreaubaaee002006-06-26 02:48:02 +0200706 */
Willy Tarreaufb56aab2012-09-28 14:40:02 +0200707static void event_srv_chk_w(struct connection *conn)
Willy Tarreaubaaee002006-06-26 02:48:02 +0200708{
Simon Horman4a741432013-02-23 15:35:38 +0900709 struct check *check = conn->owner;
710 struct server *s = check->server;
Simon Horman4a741432013-02-23 15:35:38 +0900711 struct task *t = check->task;
Willy Tarreaufb56aab2012-09-28 14:40:02 +0200712
Willy Tarreau6aaa1b82013-12-11 17:09:34 +0100713 if (unlikely(check->result == CHK_RES_FAILED))
Willy Tarreau25e2ab52013-12-04 11:17:05 +0100714 goto out_wakeup;
715
Willy Tarreau310987a2014-01-22 19:46:33 +0100716 if (conn->flags & CO_FL_HANDSHAKE)
Willy Tarreau25e2ab52013-12-04 11:17:05 +0100717 return;
718
Willy Tarreau20a18342013-12-05 00:31:46 +0100719 if (retrieve_errno_from_socket(conn)) {
Willy Tarreau25e2ab52013-12-04 11:17:05 +0100720 chk_report_conn_err(conn, errno, 0);
Willy Tarreau20a18342013-12-05 00:31:46 +0100721 __conn_data_stop_both(conn);
722 goto out_wakeup;
723 }
Krzysztof Piotr Oledzki6492db52010-01-02 22:03:01 +0100724
Willy Tarreau25e2ab52013-12-04 11:17:05 +0100725 if (conn->flags & (CO_FL_SOCK_WR_SH | CO_FL_DATA_WR_SH)) {
Willy Tarreau20a18342013-12-05 00:31:46 +0100726 /* if the output is closed, we can't do anything */
727 conn->flags |= CO_FL_ERROR;
Willy Tarreau25e2ab52013-12-04 11:17:05 +0100728 chk_report_conn_err(conn, 0, 0);
Willy Tarreau20a18342013-12-05 00:31:46 +0100729 goto out_wakeup;
Krzysztof Piotr Oledzki09605412009-09-23 22:09:24 +0200730 }
Willy Tarreau6996e152007-04-30 14:37:43 +0200731
Willy Tarreau06559ac2013-12-05 01:53:08 +0100732 /* here, we know that the connection is established. That's enough for
733 * a pure TCP check.
734 */
735 if (!check->type)
736 goto out_wakeup;
737
Baptiste Assmann5ecb77f2013-10-06 23:24:13 +0200738 if (check->type == PR_O2_TCPCHK_CHK) {
739 tcpcheck_main(conn);
740 return;
741 }
742
Willy Tarreau25e2ab52013-12-04 11:17:05 +0100743 if (check->bo->o) {
Willy Tarreau1049b1f2014-02-02 01:51:17 +0100744 conn->xprt->snd_buf(conn, check->bo, 0);
Willy Tarreau25e2ab52013-12-04 11:17:05 +0100745 if (conn->flags & CO_FL_ERROR) {
746 chk_report_conn_err(conn, errno, 0);
747 __conn_data_stop_both(conn);
748 goto out_wakeup;
Willy Tarreaubaaee002006-06-26 02:48:02 +0200749 }
Willy Tarreau25e2ab52013-12-04 11:17:05 +0100750 if (check->bo->o)
751 return;
752 }
Willy Tarreau6996e152007-04-30 14:37:43 +0200753
Willy Tarreau25e2ab52013-12-04 11:17:05 +0100754 /* full request sent, we allow up to <timeout.check> if nonzero for a response */
755 if (s->proxy->timeout.check) {
756 t->expire = tick_add_ifset(now_ms, s->proxy->timeout.check);
757 task_queue(t);
Willy Tarreaubaaee002006-06-26 02:48:02 +0200758 }
Willy Tarreau25e2ab52013-12-04 11:17:05 +0100759 goto out_nowake;
760
Willy Tarreau83749182007-04-15 20:56:27 +0200761 out_wakeup:
Willy Tarreaufdccded2008-08-29 18:19:04 +0200762 task_wakeup(t, TASK_WOKEN_IO);
Willy Tarreau83749182007-04-15 20:56:27 +0200763 out_nowake:
Willy Tarreaufb56aab2012-09-28 14:40:02 +0200764 __conn_data_stop_send(conn); /* nothing more to write */
Willy Tarreaubaaee002006-06-26 02:48:02 +0200765}
766
Willy Tarreaubaaee002006-06-26 02:48:02 +0200767/*
Willy Tarreauf3c69202006-07-09 16:42:34 +0200768 * This function is used only for server health-checks. It handles the server's
Hervé COMMOWICK8776f1b2010-10-18 15:58:36 +0200769 * reply to an HTTP request, SSL HELLO or MySQL client Auth. It calls
Simon Horman4a741432013-02-23 15:35:38 +0900770 * set_server_check_status() to update check->status, check->duration
771 * and check->result.
Krzysztof Piotr Oledzki213014e2009-09-27 15:50:02 +0200772
773 * The set_server_check_status function is called with HCHK_STATUS_L7OKD if
774 * an HTTP server replies HTTP 2xx or 3xx (valid responses), if an SMTP server
775 * returns 2xx, HCHK_STATUS_L6OK if an SSL server returns at least 5 bytes in
776 * response to an SSL HELLO (the principle is that this is enough to
777 * distinguish between an SSL server and a pure TCP relay). All other cases will
778 * call it with a proper error status like HCHK_STATUS_L7STS, HCHK_STATUS_L6RSP,
779 * etc.
Willy Tarreaubaaee002006-06-26 02:48:02 +0200780 */
Willy Tarreaufb56aab2012-09-28 14:40:02 +0200781static void event_srv_chk_r(struct connection *conn)
Willy Tarreaubaaee002006-06-26 02:48:02 +0200782{
Simon Horman4a741432013-02-23 15:35:38 +0900783 struct check *check = conn->owner;
784 struct server *s = check->server;
785 struct task *t = check->task;
Krzysztof Piotr Oledzkif7089f52009-10-10 21:06:49 +0200786 char *desc;
Willy Tarreau03938182010-03-17 21:52:07 +0100787 int done;
Gabor Lekenyb4c81e42010-09-29 18:17:05 +0200788 unsigned short msglen;
Willy Tarreau83749182007-04-15 20:56:27 +0200789
Willy Tarreau6aaa1b82013-12-11 17:09:34 +0100790 if (unlikely(check->result == CHK_RES_FAILED))
Willy Tarreau83749182007-04-15 20:56:27 +0200791 goto out_wakeup;
Willy Tarreau83749182007-04-15 20:56:27 +0200792
Willy Tarreau310987a2014-01-22 19:46:33 +0100793 if (conn->flags & CO_FL_HANDSHAKE)
Willy Tarreaufb56aab2012-09-28 14:40:02 +0200794 return;
Baptiste Assmann5ecb77f2013-10-06 23:24:13 +0200795
796 if (check->type == PR_O2_TCPCHK_CHK) {
797 tcpcheck_main(conn);
798 return;
799 }
Willy Tarreaufb56aab2012-09-28 14:40:02 +0200800
Willy Tarreau83749182007-04-15 20:56:27 +0200801 /* Warning! Linux returns EAGAIN on SO_ERROR if data are still available
802 * but the connection was closed on the remote end. Fortunately, recv still
803 * works correctly and we don't need to do the getsockopt() on linux.
804 */
Nick Chalk57b1bf72010-03-16 15:50:46 +0000805
806 /* Set buffer to point to the end of the data already read, and check
807 * that there is free space remaining. If the buffer is full, proceed
808 * with running the checks without attempting another socket read.
809 */
Nick Chalk57b1bf72010-03-16 15:50:46 +0000810
Willy Tarreau03938182010-03-17 21:52:07 +0100811 done = 0;
Nick Chalk57b1bf72010-03-16 15:50:46 +0000812
Simon Horman4a741432013-02-23 15:35:38 +0900813 conn->xprt->rcv_buf(conn, check->bi, check->bi->size);
Willy Tarreauf1503172012-09-28 19:39:36 +0200814 if (conn->flags & (CO_FL_ERROR | CO_FL_SOCK_RD_SH | CO_FL_DATA_RD_SH)) {
Willy Tarreau03938182010-03-17 21:52:07 +0100815 done = 1;
Simon Horman4a741432013-02-23 15:35:38 +0900816 if ((conn->flags & CO_FL_ERROR) && !check->bi->i) {
Willy Tarreauf1503172012-09-28 19:39:36 +0200817 /* Report network errors only if we got no other data. Otherwise
818 * we'll let the upper layers decide whether the response is OK
819 * or not. It is very common that an RST sent by the server is
820 * reported as an error just after the last data chunk.
821 */
Willy Tarreau25e2ab52013-12-04 11:17:05 +0100822 chk_report_conn_err(conn, errno, 0);
Willy Tarreauc1a07962010-03-16 20:55:43 +0100823 goto out_wakeup;
824 }
Willy Tarreaubaaee002006-06-26 02:48:02 +0200825 }
826
Willy Tarreau25e2ab52013-12-04 11:17:05 +0100827
Willy Tarreau03938182010-03-17 21:52:07 +0100828 /* Intermediate or complete response received.
Simon Horman4a741432013-02-23 15:35:38 +0900829 * Terminate string in check->bi->data buffer.
Willy Tarreau03938182010-03-17 21:52:07 +0100830 */
Simon Horman4a741432013-02-23 15:35:38 +0900831 if (check->bi->i < check->bi->size)
832 check->bi->data[check->bi->i] = '\0';
Willy Tarreau03938182010-03-17 21:52:07 +0100833 else {
Simon Horman4a741432013-02-23 15:35:38 +0900834 check->bi->data[check->bi->i - 1] = '\0';
Willy Tarreau03938182010-03-17 21:52:07 +0100835 done = 1; /* buffer full, don't wait for more data */
836 }
Krzysztof Piotr Oledzkif7089f52009-10-10 21:06:49 +0200837
Nick Chalk57b1bf72010-03-16 15:50:46 +0000838 /* Run the checks... */
Simon Horman4a741432013-02-23 15:35:38 +0900839 switch (check->type) {
Willy Tarreau1620ec32011-08-06 17:05:02 +0200840 case PR_O2_HTTP_CHK:
Simon Horman4a741432013-02-23 15:35:38 +0900841 if (!done && check->bi->i < strlen("HTTP/1.0 000\r"))
Willy Tarreau03938182010-03-17 21:52:07 +0100842 goto wait_more_data;
843
Willy Tarreauc7dd71a2007-11-30 08:33:21 +0100844 /* Check if the server speaks HTTP 1.X */
Simon Horman4a741432013-02-23 15:35:38 +0900845 if ((check->bi->i < strlen("HTTP/1.0 000\r")) ||
846 (memcmp(check->bi->data, "HTTP/1.", 7) != 0 ||
847 (*(check->bi->data + 12) != ' ' && *(check->bi->data + 12) != '\r')) ||
848 !isdigit((unsigned char) *(check->bi->data + 9)) || !isdigit((unsigned char) *(check->bi->data + 10)) ||
849 !isdigit((unsigned char) *(check->bi->data + 11))) {
850 cut_crlf(check->bi->data);
851 set_server_check_status(check, HCHK_STATUS_L7RSP, check->bi->data);
Krzysztof Piotr Oledzkif7089f52009-10-10 21:06:49 +0200852
Willy Tarreauc7dd71a2007-11-30 08:33:21 +0100853 goto out_wakeup;
854 }
855
Simon Horman4a741432013-02-23 15:35:38 +0900856 check->code = str2uic(check->bi->data + 9);
857 desc = ltrim(check->bi->data + 12, ' ');
Nick Chalk57b1bf72010-03-16 15:50:46 +0000858
Willy Tarreaubd741542010-03-16 18:46:54 +0100859 if ((s->proxy->options & PR_O_DISABLE404) &&
Willy Tarreau892337c2014-05-13 23:41:20 +0200860 (s->state != SRV_ST_STOPPED) && (check->code == 404)) {
Nick Chalk57b1bf72010-03-16 15:50:46 +0000861 /* 404 may be accepted as "stopping" only if the server was up */
862 cut_crlf(desc);
Simon Horman4a741432013-02-23 15:35:38 +0900863 set_server_check_status(check, HCHK_STATUS_L7OKCD, desc);
Nick Chalk57b1bf72010-03-16 15:50:46 +0000864 }
Willy Tarreaubd741542010-03-16 18:46:54 +0100865 else if (s->proxy->options2 & PR_O2_EXP_TYPE) {
866 /* Run content verification check... We know we have at least 13 chars */
867 if (!httpchk_expect(s, done))
868 goto wait_more_data;
869 }
870 /* check the reply : HTTP/1.X 2xx and 3xx are OK */
Simon Horman4a741432013-02-23 15:35:38 +0900871 else if (*(check->bi->data + 9) == '2' || *(check->bi->data + 9) == '3') {
Willy Tarreaubd741542010-03-16 18:46:54 +0100872 cut_crlf(desc);
Simon Horman4a741432013-02-23 15:35:38 +0900873 set_server_check_status(check, HCHK_STATUS_L7OKD, desc);
Willy Tarreaubd741542010-03-16 18:46:54 +0100874 }
Nick Chalk57b1bf72010-03-16 15:50:46 +0000875 else {
876 cut_crlf(desc);
Simon Horman4a741432013-02-23 15:35:38 +0900877 set_server_check_status(check, HCHK_STATUS_L7STS, desc);
Nick Chalk57b1bf72010-03-16 15:50:46 +0000878 }
Willy Tarreau1620ec32011-08-06 17:05:02 +0200879 break;
880
881 case PR_O2_SSL3_CHK:
Simon Horman4a741432013-02-23 15:35:38 +0900882 if (!done && check->bi->i < 5)
Willy Tarreau03938182010-03-17 21:52:07 +0100883 goto wait_more_data;
884
Willy Tarreauc7dd71a2007-11-30 08:33:21 +0100885 /* Check for SSLv3 alert or handshake */
Simon Horman4a741432013-02-23 15:35:38 +0900886 if ((check->bi->i >= 5) && (*check->bi->data == 0x15 || *check->bi->data == 0x16))
887 set_server_check_status(check, HCHK_STATUS_L6OK, NULL);
Krzysztof Piotr Oledzki213014e2009-09-27 15:50:02 +0200888 else
Simon Horman4a741432013-02-23 15:35:38 +0900889 set_server_check_status(check, HCHK_STATUS_L6RSP, NULL);
Willy Tarreau1620ec32011-08-06 17:05:02 +0200890 break;
891
892 case PR_O2_SMTP_CHK:
Simon Horman4a741432013-02-23 15:35:38 +0900893 if (!done && check->bi->i < strlen("000\r"))
Willy Tarreau03938182010-03-17 21:52:07 +0100894 goto wait_more_data;
895
Krzysztof Piotr Oledzki09605412009-09-23 22:09:24 +0200896 /* Check if the server speaks SMTP */
Simon Horman4a741432013-02-23 15:35:38 +0900897 if ((check->bi->i < strlen("000\r")) ||
898 (*(check->bi->data + 3) != ' ' && *(check->bi->data + 3) != '\r') ||
899 !isdigit((unsigned char) *check->bi->data) || !isdigit((unsigned char) *(check->bi->data + 1)) ||
900 !isdigit((unsigned char) *(check->bi->data + 2))) {
901 cut_crlf(check->bi->data);
902 set_server_check_status(check, HCHK_STATUS_L7RSP, check->bi->data);
Krzysztof Piotr Oledzkif7089f52009-10-10 21:06:49 +0200903
Krzysztof Piotr Oledzki09605412009-09-23 22:09:24 +0200904 goto out_wakeup;
905 }
906
Simon Horman4a741432013-02-23 15:35:38 +0900907 check->code = str2uic(check->bi->data);
Krzysztof Piotr Oledzki09605412009-09-23 22:09:24 +0200908
Simon Horman4a741432013-02-23 15:35:38 +0900909 desc = ltrim(check->bi->data + 3, ' ');
Krzysztof Piotr Oledzkif7089f52009-10-10 21:06:49 +0200910 cut_crlf(desc);
911
Willy Tarreauc7dd71a2007-11-30 08:33:21 +0100912 /* Check for SMTP code 2xx (should be 250) */
Simon Horman4a741432013-02-23 15:35:38 +0900913 if (*check->bi->data == '2')
914 set_server_check_status(check, HCHK_STATUS_L7OKD, desc);
Krzysztof Piotr Oledzki213014e2009-09-27 15:50:02 +0200915 else
Simon Horman4a741432013-02-23 15:35:38 +0900916 set_server_check_status(check, HCHK_STATUS_L7STS, desc);
Willy Tarreau1620ec32011-08-06 17:05:02 +0200917 break;
918
Simon Hormana2b9dad2013-02-12 10:45:54 +0900919 case PR_O2_LB_AGENT_CHK: {
Willy Tarreau81f5d942013-12-09 20:51:51 +0100920 int status = HCHK_STATUS_CHECKED;
921 const char *hs = NULL; /* health status */
922 const char *as = NULL; /* admin status */
923 const char *ps = NULL; /* performance status */
924 const char *err = NULL; /* first error to report */
925 const char *wrn = NULL; /* first warning to report */
926 char *cmd, *p;
Simon Hormana2b9dad2013-02-12 10:45:54 +0900927
Willy Tarreau81f5d942013-12-09 20:51:51 +0100928 /* We're getting an agent check response. The agent could
929 * have been disabled in the mean time with a long check
930 * still pending. It is important that we ignore the whole
931 * response.
932 */
933 if (!(check->server->agent.state & CHK_ST_ENABLED))
934 break;
935
936 /* The agent supports strings made of a single line ended by the
937 * first CR ('\r') or LF ('\n'). This line is composed of words
938 * delimited by spaces (' '), tabs ('\t'), or commas (','). The
939 * line may optionally contained a description of a state change
940 * after a sharp ('#'), which is only considered if a health state
941 * is announced.
942 *
943 * Words may be composed of :
944 * - a numeric weight suffixed by the percent character ('%').
945 * - a health status among "up", "down", "stopped", and "fail".
946 * - an admin status among "ready", "drain", "maint".
947 *
948 * These words may appear in any order. If multiple words of the
949 * same category appear, the last one wins.
950 */
951
Willy Tarreau9809b782013-12-11 21:40:11 +0100952 p = check->bi->data;
953 while (*p && *p != '\n' && *p != '\r')
954 p++;
955
956 if (!*p) {
957 if (!done)
958 goto wait_more_data;
Simon Hormana2b9dad2013-02-12 10:45:54 +0900959
Willy Tarreau9809b782013-12-11 21:40:11 +0100960 /* at least inform the admin that the agent is mis-behaving */
961 set_server_check_status(check, check->status, "Ignoring incomplete line from agent");
962 break;
963 }
Willy Tarreau81f5d942013-12-09 20:51:51 +0100964
Willy Tarreau9809b782013-12-11 21:40:11 +0100965 *p = 0;
Willy Tarreau81f5d942013-12-09 20:51:51 +0100966 cmd = check->bi->data;
Simon Hormana2b9dad2013-02-12 10:45:54 +0900967
Willy Tarreau81f5d942013-12-09 20:51:51 +0100968 while (*cmd) {
969 /* look for next word */
970 if (*cmd == ' ' || *cmd == '\t' || *cmd == ',') {
971 cmd++;
972 continue;
973 }
Simon Horman671b6f02013-11-25 10:46:39 +0900974
Willy Tarreau81f5d942013-12-09 20:51:51 +0100975 if (*cmd == '#') {
976 /* this is the beginning of a health status description,
977 * skip the sharp and blanks.
978 */
979 cmd++;
980 while (*cmd == '\t' || *cmd == ' ')
981 cmd++;
Simon Horman671b6f02013-11-25 10:46:39 +0900982 break;
Simon Hormana2b9dad2013-02-12 10:45:54 +0900983 }
Willy Tarreau81f5d942013-12-09 20:51:51 +0100984
985 /* find the end of the word so that we have a null-terminated
986 * word between <cmd> and <p>.
987 */
988 p = cmd + 1;
989 while (*p && *p != '\t' && *p != ' ' && *p != '\n' && *p != ',')
990 p++;
991 if (*p)
992 *p++ = 0;
993
994 /* first, health statuses */
995 if (strcasecmp(cmd, "up") == 0) {
996 check->health = check->rise + check->fall - 1;
Simon Hormana2b9dad2013-02-12 10:45:54 +0900997 status = HCHK_STATUS_L7OKD;
Willy Tarreau81f5d942013-12-09 20:51:51 +0100998 hs = cmd;
999 }
1000 else if (strcasecmp(cmd, "down") == 0) {
1001 check->health = 0;
1002 status = HCHK_STATUS_L7STS;
1003 hs = cmd;
Simon Hormana2b9dad2013-02-12 10:45:54 +09001004 }
Willy Tarreau81f5d942013-12-09 20:51:51 +01001005 else if (strcasecmp(cmd, "stopped") == 0) {
1006 check->health = 0;
1007 status = HCHK_STATUS_L7STS;
1008 hs = cmd;
1009 }
1010 else if (strcasecmp(cmd, "fail") == 0) {
1011 check->health = 0;
1012 status = HCHK_STATUS_L7STS;
1013 hs = cmd;
1014 }
1015 /* admin statuses */
1016 else if (strcasecmp(cmd, "ready") == 0) {
1017 as = cmd;
1018 }
1019 else if (strcasecmp(cmd, "drain") == 0) {
1020 as = cmd;
1021 }
1022 else if (strcasecmp(cmd, "maint") == 0) {
1023 as = cmd;
1024 }
1025 /* else try to parse a weight here and keep the last one */
1026 else if (isdigit((unsigned char)*cmd) && strchr(cmd, '%') != NULL) {
1027 ps = cmd;
1028 }
1029 else {
1030 /* keep a copy of the first error */
1031 if (!err)
1032 err = cmd;
1033 }
1034 /* skip to next word */
1035 cmd = p;
1036 }
1037 /* here, cmd points either to \0 or to the beginning of a
1038 * description. Skip possible leading spaces.
1039 */
1040 while (*cmd == ' ' || *cmd == '\n')
1041 cmd++;
1042
1043 /* First, update the admin status so that we avoid sending other
1044 * possibly useless warnings and can also update the health if
1045 * present after going back up.
1046 */
1047 if (as) {
1048 if (strcasecmp(as, "drain") == 0)
1049 srv_adm_set_drain(check->server);
1050 else if (strcasecmp(as, "maint") == 0)
1051 srv_adm_set_maint(check->server);
1052 else
1053 srv_adm_set_ready(check->server);
Simon Hormana2b9dad2013-02-12 10:45:54 +09001054 }
1055
Willy Tarreau81f5d942013-12-09 20:51:51 +01001056 /* now change weights */
1057 if (ps) {
1058 const char *msg;
1059
1060 msg = server_parse_weight_change_request(s, ps);
1061 if (!wrn || !*wrn)
1062 wrn = msg;
1063 }
1064
1065 /* and finally health status */
1066 if (hs) {
1067 /* We'll report some of the warnings and errors we have
1068 * here. Down reports are critical, we leave them untouched.
1069 * Lack of report, or report of 'UP' leaves the room for
1070 * ERR first, then WARN.
Simon Hormana2b9dad2013-02-12 10:45:54 +09001071 */
Willy Tarreau81f5d942013-12-09 20:51:51 +01001072 const char *msg = cmd;
1073 struct chunk *t;
1074
1075 if (!*msg || status == HCHK_STATUS_L7OKD) {
1076 if (err && *err)
1077 msg = err;
1078 else if (wrn && *wrn)
1079 msg = wrn;
Simon Hormana2b9dad2013-02-12 10:45:54 +09001080 }
Willy Tarreau81f5d942013-12-09 20:51:51 +01001081
1082 t = get_trash_chunk();
1083 chunk_printf(t, "via agent : %s%s%s%s",
1084 hs, *msg ? " (" : "",
1085 msg, *msg ? ")" : "");
1086
1087 set_server_check_status(check, status, t->str);
Simon Hormana2b9dad2013-02-12 10:45:54 +09001088 }
Willy Tarreau81f5d942013-12-09 20:51:51 +01001089 else if (err && *err) {
1090 /* No status change but we'd like to report something odd.
1091 * Just report the current state and copy the message.
1092 */
1093 chunk_printf(&trash, "agent reports an error : %s", err);
1094 set_server_check_status(check, status/*check->status*/, trash.str);
Simon Hormana2b9dad2013-02-12 10:45:54 +09001095
Willy Tarreau81f5d942013-12-09 20:51:51 +01001096 }
1097 else if (wrn && *wrn) {
1098 /* No status change but we'd like to report something odd.
1099 * Just report the current state and copy the message.
1100 */
1101 chunk_printf(&trash, "agent warns : %s", wrn);
1102 set_server_check_status(check, status/*check->status*/, trash.str);
1103 }
1104 else
1105 set_server_check_status(check, status, NULL);
Simon Hormana2b9dad2013-02-12 10:45:54 +09001106 break;
1107 }
1108
Willy Tarreau1620ec32011-08-06 17:05:02 +02001109 case PR_O2_PGSQL_CHK:
Simon Horman4a741432013-02-23 15:35:38 +09001110 if (!done && check->bi->i < 9)
Rauf Kuliyev38b41562011-01-04 15:14:13 +01001111 goto wait_more_data;
1112
Simon Horman4a741432013-02-23 15:35:38 +09001113 if (check->bi->data[0] == 'R') {
1114 set_server_check_status(check, HCHK_STATUS_L7OKD, "PostgreSQL server is ok");
Rauf Kuliyev38b41562011-01-04 15:14:13 +01001115 }
1116 else {
Simon Horman4a741432013-02-23 15:35:38 +09001117 if ((check->bi->data[0] == 'E') && (check->bi->data[5]!=0) && (check->bi->data[6]!=0))
1118 desc = &check->bi->data[6];
Rauf Kuliyev38b41562011-01-04 15:14:13 +01001119 else
1120 desc = "PostgreSQL unknown error";
1121
Simon Horman4a741432013-02-23 15:35:38 +09001122 set_server_check_status(check, HCHK_STATUS_L7STS, desc);
Rauf Kuliyev38b41562011-01-04 15:14:13 +01001123 }
Willy Tarreau1620ec32011-08-06 17:05:02 +02001124 break;
1125
1126 case PR_O2_REDIS_CHK:
Simon Horman4a741432013-02-23 15:35:38 +09001127 if (!done && check->bi->i < 7)
Hervé COMMOWICKec032d62011-08-05 16:23:48 +02001128 goto wait_more_data;
1129
Simon Horman4a741432013-02-23 15:35:38 +09001130 if (strcmp(check->bi->data, "+PONG\r\n") == 0) {
1131 set_server_check_status(check, HCHK_STATUS_L7OKD, "Redis server is ok");
Hervé COMMOWICKec032d62011-08-05 16:23:48 +02001132 }
1133 else {
Simon Horman4a741432013-02-23 15:35:38 +09001134 set_server_check_status(check, HCHK_STATUS_L7STS, check->bi->data);
Hervé COMMOWICKec032d62011-08-05 16:23:48 +02001135 }
Willy Tarreau1620ec32011-08-06 17:05:02 +02001136 break;
1137
1138 case PR_O2_MYSQL_CHK:
Simon Horman4a741432013-02-23 15:35:38 +09001139 if (!done && check->bi->i < 5)
Willy Tarreau03938182010-03-17 21:52:07 +01001140 goto wait_more_data;
1141
Hervé COMMOWICK8776f1b2010-10-18 15:58:36 +02001142 if (s->proxy->check_len == 0) { // old mode
Simon Horman4a741432013-02-23 15:35:38 +09001143 if (*(check->bi->data + 4) != '\xff') {
Hervé COMMOWICK8776f1b2010-10-18 15:58:36 +02001144 /* We set the MySQL Version in description for information purpose
1145 * FIXME : it can be cool to use MySQL Version for other purpose,
1146 * like mark as down old MySQL server.
1147 */
Simon Horman4a741432013-02-23 15:35:38 +09001148 if (check->bi->i > 51) {
1149 desc = ltrim(check->bi->data + 5, ' ');
1150 set_server_check_status(check, HCHK_STATUS_L7OKD, desc);
Hervé COMMOWICK8776f1b2010-10-18 15:58:36 +02001151 }
1152 else {
1153 if (!done)
1154 goto wait_more_data;
1155 /* it seems we have a OK packet but without a valid length,
1156 * it must be a protocol error
1157 */
Simon Horman4a741432013-02-23 15:35:38 +09001158 set_server_check_status(check, HCHK_STATUS_L7RSP, check->bi->data);
Hervé COMMOWICK8776f1b2010-10-18 15:58:36 +02001159 }
Hervé COMMOWICK698ae002010-01-12 09:25:13 +01001160 }
1161 else {
Hervé COMMOWICK8776f1b2010-10-18 15:58:36 +02001162 /* An error message is attached in the Error packet */
Simon Horman4a741432013-02-23 15:35:38 +09001163 desc = ltrim(check->bi->data + 7, ' ');
1164 set_server_check_status(check, HCHK_STATUS_L7STS, desc);
Hervé COMMOWICK8776f1b2010-10-18 15:58:36 +02001165 }
1166 } else {
Simon Horman4a741432013-02-23 15:35:38 +09001167 unsigned int first_packet_len = ((unsigned int) *check->bi->data) +
1168 (((unsigned int) *(check->bi->data + 1)) << 8) +
1169 (((unsigned int) *(check->bi->data + 2)) << 16);
Hervé COMMOWICK8776f1b2010-10-18 15:58:36 +02001170
Simon Horman4a741432013-02-23 15:35:38 +09001171 if (check->bi->i == first_packet_len + 4) {
Hervé COMMOWICK8776f1b2010-10-18 15:58:36 +02001172 /* MySQL Error packet always begin with field_count = 0xff */
Simon Horman4a741432013-02-23 15:35:38 +09001173 if (*(check->bi->data + 4) != '\xff') {
Hervé COMMOWICK8776f1b2010-10-18 15:58:36 +02001174 /* We have only one MySQL packet and it is a Handshake Initialization packet
1175 * but we need to have a second packet to know if it is alright
1176 */
Simon Horman4a741432013-02-23 15:35:38 +09001177 if (!done && check->bi->i < first_packet_len + 5)
Hervé COMMOWICK8776f1b2010-10-18 15:58:36 +02001178 goto wait_more_data;
1179 }
1180 else {
1181 /* We have only one packet and it is an Error packet,
1182 * an error message is attached, so we can display it
1183 */
Simon Horman4a741432013-02-23 15:35:38 +09001184 desc = &check->bi->data[7];
Hervé COMMOWICK8776f1b2010-10-18 15:58:36 +02001185 //Warning("onlyoneERR: %s\n", desc);
Simon Horman4a741432013-02-23 15:35:38 +09001186 set_server_check_status(check, HCHK_STATUS_L7STS, desc);
Hervé COMMOWICK8776f1b2010-10-18 15:58:36 +02001187 }
Simon Horman4a741432013-02-23 15:35:38 +09001188 } else if (check->bi->i > first_packet_len + 4) {
1189 unsigned int second_packet_len = ((unsigned int) *(check->bi->data + first_packet_len + 4)) +
1190 (((unsigned int) *(check->bi->data + first_packet_len + 5)) << 8) +
1191 (((unsigned int) *(check->bi->data + first_packet_len + 6)) << 16);
Hervé COMMOWICK8776f1b2010-10-18 15:58:36 +02001192
Simon Horman4a741432013-02-23 15:35:38 +09001193 if (check->bi->i == first_packet_len + 4 + second_packet_len + 4 ) {
Hervé COMMOWICK8776f1b2010-10-18 15:58:36 +02001194 /* We have 2 packets and that's good */
1195 /* Check if the second packet is a MySQL Error packet or not */
Simon Horman4a741432013-02-23 15:35:38 +09001196 if (*(check->bi->data + first_packet_len + 8) != '\xff') {
Hervé COMMOWICK8776f1b2010-10-18 15:58:36 +02001197 /* No error packet */
1198 /* We set the MySQL Version in description for information purpose */
Simon Horman4a741432013-02-23 15:35:38 +09001199 desc = &check->bi->data[5];
Hervé COMMOWICK8776f1b2010-10-18 15:58:36 +02001200 //Warning("2packetOK: %s\n", desc);
Simon Horman4a741432013-02-23 15:35:38 +09001201 set_server_check_status(check, HCHK_STATUS_L7OKD, desc);
Hervé COMMOWICK8776f1b2010-10-18 15:58:36 +02001202 }
1203 else {
1204 /* An error message is attached in the Error packet
1205 * so we can display it ! :)
1206 */
Simon Horman4a741432013-02-23 15:35:38 +09001207 desc = &check->bi->data[first_packet_len+11];
Hervé COMMOWICK8776f1b2010-10-18 15:58:36 +02001208 //Warning("2packetERR: %s\n", desc);
Simon Horman4a741432013-02-23 15:35:38 +09001209 set_server_check_status(check, HCHK_STATUS_L7STS, desc);
Hervé COMMOWICK8776f1b2010-10-18 15:58:36 +02001210 }
1211 }
1212 }
1213 else {
Willy Tarreau03938182010-03-17 21:52:07 +01001214 if (!done)
1215 goto wait_more_data;
Hervé COMMOWICK8776f1b2010-10-18 15:58:36 +02001216 /* it seems we have a Handshake Initialization packet but without a valid length,
Hervé COMMOWICK698ae002010-01-12 09:25:13 +01001217 * it must be a protocol error
1218 */
Simon Horman4a741432013-02-23 15:35:38 +09001219 desc = &check->bi->data[5];
Hervé COMMOWICK8776f1b2010-10-18 15:58:36 +02001220 //Warning("protoerr: %s\n", desc);
Simon Horman4a741432013-02-23 15:35:38 +09001221 set_server_check_status(check, HCHK_STATUS_L7RSP, desc);
Hervé COMMOWICK698ae002010-01-12 09:25:13 +01001222 }
1223 }
Willy Tarreau1620ec32011-08-06 17:05:02 +02001224 break;
1225
1226 case PR_O2_LDAP_CHK:
Simon Horman4a741432013-02-23 15:35:38 +09001227 if (!done && check->bi->i < 14)
Gabor Lekenyb4c81e42010-09-29 18:17:05 +02001228 goto wait_more_data;
1229
1230 /* Check if the server speaks LDAP (ASN.1/BER)
1231 * http://en.wikipedia.org/wiki/Basic_Encoding_Rules
1232 * http://tools.ietf.org/html/rfc4511
1233 */
1234
1235 /* http://tools.ietf.org/html/rfc4511#section-4.1.1
1236 * LDAPMessage: 0x30: SEQUENCE
1237 */
Simon Horman4a741432013-02-23 15:35:38 +09001238 if ((check->bi->i < 14) || (*(check->bi->data) != '\x30')) {
1239 set_server_check_status(check, HCHK_STATUS_L7RSP, "Not LDAPv3 protocol");
Gabor Lekenyb4c81e42010-09-29 18:17:05 +02001240 }
1241 else {
1242 /* size of LDAPMessage */
Simon Horman4a741432013-02-23 15:35:38 +09001243 msglen = (*(check->bi->data + 1) & 0x80) ? (*(check->bi->data + 1) & 0x7f) : 0;
Gabor Lekenyb4c81e42010-09-29 18:17:05 +02001244
1245 /* http://tools.ietf.org/html/rfc4511#section-4.2.2
1246 * messageID: 0x02 0x01 0x01: INTEGER 1
1247 * protocolOp: 0x61: bindResponse
1248 */
1249 if ((msglen > 2) ||
Simon Horman4a741432013-02-23 15:35:38 +09001250 (memcmp(check->bi->data + 2 + msglen, "\x02\x01\x01\x61", 4) != 0)) {
1251 set_server_check_status(check, HCHK_STATUS_L7RSP, "Not LDAPv3 protocol");
Gabor Lekenyb4c81e42010-09-29 18:17:05 +02001252
1253 goto out_wakeup;
1254 }
1255
1256 /* size of bindResponse */
Simon Horman4a741432013-02-23 15:35:38 +09001257 msglen += (*(check->bi->data + msglen + 6) & 0x80) ? (*(check->bi->data + msglen + 6) & 0x7f) : 0;
Gabor Lekenyb4c81e42010-09-29 18:17:05 +02001258
1259 /* http://tools.ietf.org/html/rfc4511#section-4.1.9
1260 * ldapResult: 0x0a 0x01: ENUMERATION
1261 */
1262 if ((msglen > 4) ||
Simon Horman4a741432013-02-23 15:35:38 +09001263 (memcmp(check->bi->data + 7 + msglen, "\x0a\x01", 2) != 0)) {
1264 set_server_check_status(check, HCHK_STATUS_L7RSP, "Not LDAPv3 protocol");
Gabor Lekenyb4c81e42010-09-29 18:17:05 +02001265
1266 goto out_wakeup;
1267 }
1268
1269 /* http://tools.ietf.org/html/rfc4511#section-4.1.9
1270 * resultCode
1271 */
Simon Horman4a741432013-02-23 15:35:38 +09001272 check->code = *(check->bi->data + msglen + 9);
1273 if (check->code) {
1274 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 +02001275 } else {
Simon Horman4a741432013-02-23 15:35:38 +09001276 set_server_check_status(check, HCHK_STATUS_L7OKD, "Success");
Gabor Lekenyb4c81e42010-09-29 18:17:05 +02001277 }
1278 }
Willy Tarreau1620ec32011-08-06 17:05:02 +02001279 break;
1280
1281 default:
Willy Tarreau06559ac2013-12-05 01:53:08 +01001282 /* for other checks (eg: pure TCP), delegate to the main task */
Willy Tarreau1620ec32011-08-06 17:05:02 +02001283 break;
1284 } /* switch */
Willy Tarreau83749182007-04-15 20:56:27 +02001285
Willy Tarreauc7dd71a2007-11-30 08:33:21 +01001286 out_wakeup:
Willy Tarreau25e2ab52013-12-04 11:17:05 +01001287 /* collect possible new errors */
1288 if (conn->flags & CO_FL_ERROR)
1289 chk_report_conn_err(conn, 0, 0);
Willy Tarreaubaaee002006-06-26 02:48:02 +02001290
Nick Chalk57b1bf72010-03-16 15:50:46 +00001291 /* Reset the check buffer... */
Simon Horman4a741432013-02-23 15:35:38 +09001292 *check->bi->data = '\0';
1293 check->bi->i = 0;
Nick Chalk57b1bf72010-03-16 15:50:46 +00001294
Willy Tarreaufd29cc52012-11-23 09:18:20 +01001295 /* Close the connection... We absolutely want to perform a hard close
1296 * and reset the connection if some data are pending, otherwise we end
1297 * up with many TIME_WAITs and eat all the source port range quickly.
1298 * To avoid sending RSTs all the time, we first try to drain pending
1299 * data.
1300 */
Willy Tarreaub4017d02015-03-12 23:11:26 +01001301 __conn_data_stop_both(conn);
1302 conn_data_shutw_hard(conn);
Willy Tarreau2b57cb82013-06-10 19:56:38 +02001303
Willy Tarreau25e2ab52013-12-04 11:17:05 +01001304 /* OK, let's not stay here forever */
Willy Tarreau6aaa1b82013-12-11 17:09:34 +01001305 if (check->result == CHK_RES_FAILED)
Willy Tarreau25e2ab52013-12-04 11:17:05 +01001306 conn->flags |= CO_FL_ERROR;
1307
Willy Tarreaufdccded2008-08-29 18:19:04 +02001308 task_wakeup(t, TASK_WOKEN_IO);
Willy Tarreau3267d362012-08-17 23:53:56 +02001309 return;
Willy Tarreau03938182010-03-17 21:52:07 +01001310
1311 wait_more_data:
Willy Tarreauf817e9f2014-01-10 16:58:45 +01001312 __conn_data_want_recv(conn);
Willy Tarreaubaaee002006-06-26 02:48:02 +02001313}
1314
Willy Tarreaufb56aab2012-09-28 14:40:02 +02001315/*
1316 * This function is used only for server health-checks. It handles connection
1317 * status updates including errors. If necessary, it wakes the check task up.
1318 * It always returns 0.
1319 */
1320static int wake_srv_chk(struct connection *conn)
Willy Tarreau20bea422012-07-06 12:00:49 +02001321{
Simon Horman4a741432013-02-23 15:35:38 +09001322 struct check *check = conn->owner;
Willy Tarreau20bea422012-07-06 12:00:49 +02001323
Willy Tarreau6c560da2012-11-24 11:14:45 +01001324 if (unlikely(conn->flags & CO_FL_ERROR)) {
Willy Tarreau02b0f582013-12-03 15:42:33 +01001325 /* We may get error reports bypassing the I/O handlers, typically
1326 * the case when sending a pure TCP check which fails, then the I/O
1327 * handlers above are not called. This is completely handled by the
Willy Tarreau25e2ab52013-12-04 11:17:05 +01001328 * main processing task so let's simply wake it up. If we get here,
1329 * we expect errno to still be valid.
1330 */
1331 chk_report_conn_err(conn, errno, 0);
1332
Willy Tarreau2d351b62013-12-05 02:36:25 +01001333 __conn_data_stop_both(conn);
1334 task_wakeup(check->task, TASK_WOKEN_IO);
1335 }
Willy Tarreau3be293f2014-02-05 18:31:24 +01001336 else if (!(conn->flags & (CO_FL_DATA_RD_ENA|CO_FL_DATA_WR_ENA|CO_FL_HANDSHAKE))) {
1337 /* we may get here if only a connection probe was required : we
1338 * don't have any data to send nor anything expected in response,
1339 * so the completion of the connection establishment is enough.
1340 */
1341 task_wakeup(check->task, TASK_WOKEN_IO);
1342 }
Willy Tarreau2d351b62013-12-05 02:36:25 +01001343
Willy Tarreau6aaa1b82013-12-11 17:09:34 +01001344 if (check->result != CHK_RES_UNKNOWN) {
Willy Tarreau25e2ab52013-12-04 11:17:05 +01001345 /* We're here because nobody wants to handle the error, so we
1346 * sure want to abort the hard way.
Willy Tarreau02b0f582013-12-03 15:42:33 +01001347 */
Willy Tarreaud85c4852015-03-13 00:40:28 +01001348 conn_sock_drain(conn);
Willy Tarreauf79c8172013-10-21 16:30:56 +02001349 conn_force_close(conn);
Willy Tarreau2d351b62013-12-05 02:36:25 +01001350 }
Willy Tarreau3267d362012-08-17 23:53:56 +02001351 return 0;
Willy Tarreau20bea422012-07-06 12:00:49 +02001352}
1353
Willy Tarreaufb56aab2012-09-28 14:40:02 +02001354struct data_cb check_conn_cb = {
1355 .recv = event_srv_chk_r,
1356 .send = event_srv_chk_w,
1357 .wake = wake_srv_chk,
1358};
1359
Willy Tarreaubaaee002006-06-26 02:48:02 +02001360/*
Willy Tarreau2e993902011-10-31 11:53:20 +01001361 * updates the server's weight during a warmup stage. Once the final weight is
1362 * reached, the task automatically stops. Note that any server status change
1363 * must have updated s->last_change accordingly.
1364 */
1365static struct task *server_warmup(struct task *t)
1366{
1367 struct server *s = t->context;
1368
1369 /* by default, plan on stopping the task */
1370 t->expire = TICK_ETERNITY;
Willy Tarreau20125212014-05-13 19:44:56 +02001371 if ((s->admin & SRV_ADMF_MAINT) ||
Willy Tarreau892337c2014-05-13 23:41:20 +02001372 (s->state != SRV_ST_STARTING))
Willy Tarreau2e993902011-10-31 11:53:20 +01001373 return t;
1374
Willy Tarreau892337c2014-05-13 23:41:20 +02001375 /* recalculate the weights and update the state */
Willy Tarreau004e0452013-11-21 11:22:01 +01001376 server_recalc_eweight(s);
Willy Tarreau2e993902011-10-31 11:53:20 +01001377
1378 /* probably that we can refill this server with a bit more connections */
Willy Tarreau4aac7db2014-05-16 11:48:10 +02001379 pendconn_grab_from_px(s);
Willy Tarreau2e993902011-10-31 11:53:20 +01001380
1381 /* get back there in 1 second or 1/20th of the slowstart interval,
1382 * whichever is greater, resulting in small 5% steps.
1383 */
Willy Tarreau892337c2014-05-13 23:41:20 +02001384 if (s->state == SRV_ST_STARTING)
Willy Tarreau2e993902011-10-31 11:53:20 +01001385 t->expire = tick_add(now_ms, MS_TO_TICKS(MAX(1000, s->slowstart / 20)));
1386 return t;
1387}
1388
1389/*
Simon Horman98637e52014-06-20 12:30:16 +09001390 * establish a server health-check that makes use of a connection.
Simon Hormanb00d17a2014-06-13 16:18:16 +09001391 *
1392 * It can return one of :
1393 * - SN_ERR_NONE if everything's OK and tcpcheck_main() was not called
1394 * - SN_ERR_UP if if everything's OK and tcpcheck_main() was called
1395 * - SN_ERR_SRVTO if there are no more servers
1396 * - SN_ERR_SRVCL if the connection was refused by the server
1397 * - SN_ERR_PRXCOND if the connection has been limited by the proxy (maxconn)
1398 * - SN_ERR_RESOURCE if a system resource is lacking (eg: fd limits, ports, ...)
1399 * - SN_ERR_INTERNAL for any other purely internal errors
1400 * Additionnally, in the case of SN_ERR_RESOURCE, an emergency log will be emitted.
1401 * Note that we try to prevent the network stack from sending the ACK during the
1402 * connect() when a pure TCP check is used (without PROXY protocol).
1403 */
Simon Horman98637e52014-06-20 12:30:16 +09001404static int connect_conn_chk(struct task *t)
Simon Hormanb00d17a2014-06-13 16:18:16 +09001405{
1406 struct check *check = t->context;
1407 struct server *s = check->server;
1408 struct connection *conn = check->conn;
1409 struct protocol *proto;
1410 int ret;
Willy Tarreauf3d34822014-12-08 12:11:28 +01001411 int quickack;
Simon Hormanb00d17a2014-06-13 16:18:16 +09001412
1413 /* tcpcheck send/expect initialisation */
1414 if (check->type == PR_O2_TCPCHK_CHK)
1415 check->current_step = NULL;
1416
1417 /* prepare the check buffer.
1418 * This should not be used if check is the secondary agent check
1419 * of a server as s->proxy->check_req will relate to the
1420 * configuration of the primary check. Similarly, tcp-check uses
1421 * its own strings.
1422 */
1423 if (check->type && check->type != PR_O2_TCPCHK_CHK && !(check->state & CHK_ST_AGENT)) {
1424 bo_putblk(check->bo, s->proxy->check_req, s->proxy->check_len);
1425
1426 /* we want to check if this host replies to HTTP or SSLv3 requests
1427 * so we'll send the request, and won't wake the checker up now.
1428 */
1429 if ((check->type) == PR_O2_SSL3_CHK) {
1430 /* SSL requires that we put Unix time in the request */
1431 int gmt_time = htonl(date.tv_sec);
1432 memcpy(check->bo->data + 11, &gmt_time, 4);
1433 }
1434 else if ((check->type) == PR_O2_HTTP_CHK) {
1435 if (s->proxy->options2 & PR_O2_CHK_SNDST)
1436 bo_putblk(check->bo, trash.str, httpchk_build_status_header(s, trash.str, trash.size));
Cyril Bonté32602d22015-01-30 00:07:07 +01001437 /* prevent HTTP keep-alive when "http-check expect" is used */
1438 if (s->proxy->options2 & PR_O2_EXP_TYPE)
1439 bo_putstr(check->bo, "Connection: close\r\n");
Simon Hormanb00d17a2014-06-13 16:18:16 +09001440 bo_putstr(check->bo, "\r\n");
1441 *check->bo->p = '\0'; /* to make gdb output easier to read */
1442 }
1443 }
1444
1445 /* prepare a new connection */
1446 conn_init(conn);
Simon Hormanb00d17a2014-06-13 16:18:16 +09001447
Simon Horman41f58762015-01-30 11:22:56 +09001448 if (is_addr(&check->addr)) {
Simon Hormanb00d17a2014-06-13 16:18:16 +09001449 /* we'll connect to the check addr specified on the server */
Simon Horman41f58762015-01-30 11:22:56 +09001450 conn->addr.to = check->addr;
Simon Hormanb00d17a2014-06-13 16:18:16 +09001451 }
1452 else {
1453 /* we'll connect to the addr on the server */
1454 conn->addr.to = s->addr;
Simon Hormanb00d17a2014-06-13 16:18:16 +09001455 }
1456
1457 if (check->port) {
1458 set_host_port(&conn->addr.to, check->port);
1459 }
1460
Thierry FOURNIERbb2ae642015-01-14 11:31:49 +01001461 proto = protocol_by_family(conn->addr.to.ss_family);
1462
1463 conn_prepare(conn, proto, check->xprt);
1464 conn_attach(conn, check, &check_conn_cb);
1465 conn->target = &s->obj_type;
1466
1467 /* no client address */
1468 clear_addr(&conn->addr.from);
1469
Willy Tarreauf3d34822014-12-08 12:11:28 +01001470 /* only plain tcp-check supports quick ACK */
1471 quickack = check->type == 0 || check->type == PR_O2_TCPCHK_CHK;
1472
Simon Hormane16c1b32015-01-30 11:22:57 +09001473 if (check->type == PR_O2_TCPCHK_CHK && !LIST_ISEMPTY(check->tcpcheck_rules)) {
1474 struct tcpcheck_rule *r = (struct tcpcheck_rule *) check->tcpcheck_rules->n;
Simon Hormanb00d17a2014-06-13 16:18:16 +09001475 /* if first step is a 'connect', then tcpcheck_main must run it */
1476 if (r->action == TCPCHK_ACT_CONNECT) {
1477 tcpcheck_main(conn);
1478 return SN_ERR_UP;
1479 }
Willy Tarreauf3d34822014-12-08 12:11:28 +01001480 if (r->action == TCPCHK_ACT_EXPECT)
1481 quickack = 0;
Simon Hormanb00d17a2014-06-13 16:18:16 +09001482 }
1483
1484 ret = SN_ERR_INTERNAL;
1485 if (proto->connect)
Willy Tarreauf3d34822014-12-08 12:11:28 +01001486 ret = proto->connect(conn, check->type, quickack ? 2 : 0);
Simon Hormanb00d17a2014-06-13 16:18:16 +09001487 conn->flags |= CO_FL_WAKE_DATA;
1488 if (s->check.send_proxy) {
1489 conn->send_proxy_ofs = 1;
1490 conn->flags |= CO_FL_SEND_PROXY;
1491 }
1492
1493 return ret;
1494}
1495
Simon Horman98637e52014-06-20 12:30:16 +09001496static struct list pid_list = LIST_HEAD_INIT(pid_list);
1497static struct pool_head *pool2_pid_list;
1498
1499void block_sigchld(void)
1500{
1501 sigset_t set;
1502 sigemptyset(&set);
1503 sigaddset(&set, SIGCHLD);
1504 assert(sigprocmask(SIG_SETMASK, &set, NULL) == 0);
1505}
1506
1507void unblock_sigchld(void)
1508{
1509 sigset_t set;
1510 sigemptyset(&set);
1511 assert(sigprocmask(SIG_SETMASK, &set, NULL) == 0);
1512}
1513
1514/* Call with SIGCHLD blocked */
1515static struct pid_list *pid_list_add(pid_t pid, struct task *t)
1516{
1517 struct pid_list *elem;
1518 struct check *check = t->context;
1519
1520 elem = pool_alloc2(pool2_pid_list);
1521 if (!elem)
1522 return NULL;
1523 elem->pid = pid;
1524 elem->t = t;
1525 elem->exited = 0;
1526 check->curpid = elem;
1527 LIST_INIT(&elem->list);
1528 LIST_ADD(&pid_list, &elem->list);
1529 return elem;
1530}
1531
1532/* Blocks blocks and then unblocks SIGCHLD */
1533static void pid_list_del(struct pid_list *elem)
1534{
1535 struct check *check;
1536
1537 if (!elem)
1538 return;
1539
1540 block_sigchld();
1541 LIST_DEL(&elem->list);
1542 unblock_sigchld();
1543 if (!elem->exited)
1544 kill(elem->pid, SIGTERM);
1545
1546 check = elem->t->context;
1547 check->curpid = NULL;
1548 pool_free2(pool2_pid_list, elem);
1549}
1550
1551/* Called from inside SIGCHLD handler, SIGCHLD is blocked */
1552static void pid_list_expire(pid_t pid, int status)
1553{
1554 struct pid_list *elem;
1555
1556 list_for_each_entry(elem, &pid_list, list) {
1557 if (elem->pid == pid) {
1558 elem->t->expire = now_ms;
1559 elem->status = status;
1560 elem->exited = 1;
Cyril Bonté9dbcfab2014-08-07 01:55:39 +02001561 task_wakeup(elem->t, TASK_WOKEN_IO);
Simon Horman98637e52014-06-20 12:30:16 +09001562 return;
1563 }
1564 }
1565}
1566
1567static void sigchld_handler(int signal)
1568{
1569 pid_t pid;
1570 int status;
1571 while ((pid = waitpid(0, &status, WNOHANG)) > 0)
1572 pid_list_expire(pid, status);
1573}
1574
1575static int init_pid_list(void) {
1576 struct sigaction action = {
1577 .sa_handler = sigchld_handler,
1578 .sa_flags = SA_NOCLDSTOP
1579 };
1580
1581 if (pool2_pid_list != NULL)
1582 /* Nothing to do */
1583 return 0;
1584
1585 if (sigaction(SIGCHLD, &action, NULL)) {
1586 Alert("Failed to set signal handler for external health checks: %s. Aborting.\n",
1587 strerror(errno));
1588 return 1;
1589 }
1590
1591 pool2_pid_list = create_pool("pid_list", sizeof(struct pid_list), MEM_F_SHARED);
1592 if (pool2_pid_list == NULL) {
1593 Alert("Failed to allocate memory pool for external health checks: %s. Aborting.\n",
1594 strerror(errno));
1595 return 1;
1596 }
1597
1598 return 0;
1599}
1600
Cyril Bontéac92a062014-12-27 22:28:38 +01001601/* helper macro to set an environment variable and jump to a specific label on failure. */
1602#define EXTCHK_SETENV(check, envidx, value, fail) { if (extchk_setenv(check, envidx, value)) goto fail; }
Cyril Bonté9ede66b2014-12-02 21:21:36 +01001603
1604/*
Cyril Bontéac92a062014-12-27 22:28:38 +01001605 * helper function to allocate enough memory to store an environment variable.
1606 * It will also check that the environment variable is updatable, and silently
1607 * fail if not.
Cyril Bonté9ede66b2014-12-02 21:21:36 +01001608 */
Cyril Bontéac92a062014-12-27 22:28:38 +01001609static int extchk_setenv(struct check *check, int idx, const char *value)
Cyril Bonté9ede66b2014-12-02 21:21:36 +01001610{
1611 int len, ret;
Cyril Bontéac92a062014-12-27 22:28:38 +01001612 char *envname;
1613 int vmaxlen;
Cyril Bonté9ede66b2014-12-02 21:21:36 +01001614
Cyril Bontéac92a062014-12-27 22:28:38 +01001615 if (idx < 0 || idx >= EXTCHK_SIZE) {
1616 Alert("Illegal environment variable index %d. Aborting.\n", idx);
1617 return 1;
Cyril Bonté9ede66b2014-12-02 21:21:36 +01001618 }
Cyril Bontéac92a062014-12-27 22:28:38 +01001619
1620 envname = extcheck_envs[idx].name;
1621 vmaxlen = extcheck_envs[idx].vmaxlen;
1622
1623 /* Check if the environment variable is already set, and silently reject
1624 * the update if this one is not updatable. */
1625 if ((vmaxlen == EXTCHK_SIZE_EVAL_INIT) && (check->envp[idx]))
1626 return 0;
1627
Cyril Bonté9ede66b2014-12-02 21:21:36 +01001628 /* Instead of sending NOT_USED, sending an empty value is preferable */
1629 if (strcmp(value, "NOT_USED") == 0) {
1630 value = "";
1631 }
Cyril Bontéac92a062014-12-27 22:28:38 +01001632
1633 len = strlen(envname) + 1;
1634 if (vmaxlen == EXTCHK_SIZE_EVAL_INIT)
1635 len += strlen(value);
1636 else
1637 len += vmaxlen;
1638
1639 if (!check->envp[idx])
1640 check->envp[idx] = malloc(len + 1);
1641
1642 if (!check->envp[idx]) {
Cyril Bonté9ede66b2014-12-02 21:21:36 +01001643 Alert("Failed to allocate memory for the environment variable '%s'. Aborting.\n", envname);
1644 return 1;
1645 }
Cyril Bontéac92a062014-12-27 22:28:38 +01001646 ret = snprintf(check->envp[idx], len + 1, "%s=%s", envname, value);
Cyril Bonté9ede66b2014-12-02 21:21:36 +01001647 if (ret < 0) {
1648 Alert("Failed to store the environment variable '%s'. Reason : %s. Aborting.\n", envname, strerror(errno));
1649 return 1;
1650 }
Cyril Bontéac92a062014-12-27 22:28:38 +01001651 else if (ret > len) {
Cyril Bonté9ede66b2014-12-02 21:21:36 +01001652 Alert("Environment variable '%s' was truncated. Aborting.\n", envname);
1653 return 1;
1654 }
Cyril Bonté9ede66b2014-12-02 21:21:36 +01001655 return 0;
1656}
Simon Horman98637e52014-06-20 12:30:16 +09001657
1658static int prepare_external_check(struct check *check)
1659{
1660 struct server *s = check->server;
1661 struct proxy *px = s->proxy;
1662 struct listener *listener = NULL, *l;
1663 int i;
Simon Horman98637e52014-06-20 12:30:16 +09001664 const char *path = px->check_path ? px->check_path : DEF_CHECK_PATH;
Cyril Bonté9ede66b2014-12-02 21:21:36 +01001665 char buf[256];
Simon Horman98637e52014-06-20 12:30:16 +09001666
1667 list_for_each_entry(l, &px->conf.listeners, by_fe)
1668 /* Use the first INET, INET6 or UNIX listener */
1669 if (l->addr.ss_family == AF_INET ||
1670 l->addr.ss_family == AF_INET6 ||
1671 l->addr.ss_family == AF_UNIX) {
1672 listener = l;
1673 break;
1674 }
1675
Simon Horman98637e52014-06-20 12:30:16 +09001676 check->curpid = NULL;
Cyril Bontéac92a062014-12-27 22:28:38 +01001677 check->envp = calloc((EXTCHK_SIZE + 1), sizeof(char *));
1678 if (!check->envp) {
1679 Alert("Failed to allocate memory for environment variables. Aborting\n");
1680 goto err;
1681 }
Simon Horman98637e52014-06-20 12:30:16 +09001682
Cyril Bontéac92a062014-12-27 22:28:38 +01001683 check->argv = calloc(6, sizeof(char *));
1684 if (!check->argv) {
1685 Alert("Starting [%s:%s] check: out of memory.\n", px->id, s->id);
Simon Horman98637e52014-06-20 12:30:16 +09001686 goto err;
Cyril Bontéac92a062014-12-27 22:28:38 +01001687 }
Simon Horman98637e52014-06-20 12:30:16 +09001688
1689 check->argv[0] = px->check_command;
1690
Cyril Bonté777be862014-12-02 21:21:35 +01001691 if (!listener) {
1692 check->argv[1] = strdup("NOT_USED");
1693 check->argv[2] = strdup("NOT_USED");
1694 }
1695 else if (listener->addr.ss_family == AF_INET ||
Simon Horman98637e52014-06-20 12:30:16 +09001696 listener->addr.ss_family == AF_INET6) {
Cyril Bonté9ede66b2014-12-02 21:21:36 +01001697 addr_to_str(&listener->addr, buf, sizeof(buf));
1698 check->argv[1] = strdup(buf);
1699 port_to_str(&listener->addr, buf, sizeof(buf));
1700 check->argv[2] = strdup(buf);
Cyril Bonté777be862014-12-02 21:21:35 +01001701 }
1702 else if (listener->addr.ss_family == AF_UNIX) {
Simon Horman98637e52014-06-20 12:30:16 +09001703 const struct sockaddr_un *un;
1704
1705 un = (struct sockaddr_un *)&listener->addr;
1706 check->argv[1] = strdup(un->sun_path);
1707 check->argv[2] = strdup("NOT_USED");
Cyril Bonté777be862014-12-02 21:21:35 +01001708 }
1709 else {
Cyril Bontéac92a062014-12-27 22:28:38 +01001710 Alert("Starting [%s:%s] check: unsupported address family.\n", px->id, s->id);
Simon Horman98637e52014-06-20 12:30:16 +09001711 goto err;
1712 }
1713
Cyril Bonté9ede66b2014-12-02 21:21:36 +01001714 addr_to_str(&s->addr, buf, sizeof(buf));
1715 check->argv[3] = strdup(buf);
1716 port_to_str(&s->addr, buf, sizeof(buf));
1717 check->argv[4] = strdup(buf);
Simon Horman98637e52014-06-20 12:30:16 +09001718
Cyril Bontéac92a062014-12-27 22:28:38 +01001719 for (i = 0; i < 5; i++) {
1720 if (!check->argv[i]) {
1721 Alert("Starting [%s:%s] check: out of memory.\n", px->id, s->id);
Simon Horman98637e52014-06-20 12:30:16 +09001722 goto err;
Cyril Bontéac92a062014-12-27 22:28:38 +01001723 }
1724 }
Simon Horman98637e52014-06-20 12:30:16 +09001725
Cyril Bontéac92a062014-12-27 22:28:38 +01001726 EXTCHK_SETENV(check, EXTCHK_PATH, path, err);
Cyril Bonté9ede66b2014-12-02 21:21:36 +01001727 /* Add proxy environment variables */
Cyril Bontéac92a062014-12-27 22:28:38 +01001728 EXTCHK_SETENV(check, EXTCHK_HAPROXY_PROXY_NAME, px->id, err);
1729 EXTCHK_SETENV(check, EXTCHK_HAPROXY_PROXY_ID, ultoa_r(px->uuid, buf, sizeof(buf)), err);
1730 EXTCHK_SETENV(check, EXTCHK_HAPROXY_PROXY_ADDR, check->argv[1], err);
1731 EXTCHK_SETENV(check, EXTCHK_HAPROXY_PROXY_PORT, check->argv[2], err);
Cyril Bonté9ede66b2014-12-02 21:21:36 +01001732 /* Add server environment variables */
Cyril Bontéac92a062014-12-27 22:28:38 +01001733 EXTCHK_SETENV(check, EXTCHK_HAPROXY_SERVER_NAME, s->id, err);
1734 EXTCHK_SETENV(check, EXTCHK_HAPROXY_SERVER_ID, ultoa_r(s->puid, buf, sizeof(buf)), err);
1735 EXTCHK_SETENV(check, EXTCHK_HAPROXY_SERVER_ADDR, check->argv[3], err);
1736 EXTCHK_SETENV(check, EXTCHK_HAPROXY_SERVER_PORT, check->argv[4], err);
1737 EXTCHK_SETENV(check, EXTCHK_HAPROXY_SERVER_MAXCONN, ultoa_r(s->maxconn, buf, sizeof(buf)), err);
1738 EXTCHK_SETENV(check, EXTCHK_HAPROXY_SERVER_CURCONN, ultoa_r(s->cur_sess, buf, sizeof(buf)), err);
1739
1740 /* Ensure that we don't leave any hole in check->envp */
1741 for (i = 0; i < EXTCHK_SIZE; i++)
1742 if (!check->envp[i])
1743 EXTCHK_SETENV(check, i, "", err);
Cyril Bonté9ede66b2014-12-02 21:21:36 +01001744
Cyril Bonté99c5bf52014-08-07 01:55:38 +02001745 return 1;
Simon Horman98637e52014-06-20 12:30:16 +09001746err:
1747 if (check->envp) {
Cyril Bontéac92a062014-12-27 22:28:38 +01001748 for (i = 0; i < EXTCHK_SIZE; i++)
Cyril Bonté9ede66b2014-12-02 21:21:36 +01001749 free(check->envp[i]);
Simon Horman98637e52014-06-20 12:30:16 +09001750 free(check->envp);
1751 check->envp = NULL;
1752 }
1753
1754 if (check->argv) {
1755 for (i = 1; i < 5; i++)
1756 free(check->argv[i]);
1757 free(check->argv);
1758 check->argv = NULL;
1759 }
Cyril Bonté99c5bf52014-08-07 01:55:38 +02001760 return 0;
Simon Horman98637e52014-06-20 12:30:16 +09001761}
1762
Simon Hormanb00d17a2014-06-13 16:18:16 +09001763/*
Simon Horman98637e52014-06-20 12:30:16 +09001764 * establish a server health-check that makes use of a process.
1765 *
1766 * It can return one of :
1767 * - SN_ERR_NONE if everything's OK
1768 * - SN_ERR_SRVTO if there are no more servers
1769 * - SN_ERR_SRVCL if the connection was refused by the server
1770 * - SN_ERR_PRXCOND if the connection has been limited by the proxy (maxconn)
1771 * - SN_ERR_RESOURCE if a system resource is lacking (eg: fd limits, ports, ...)
1772 * - SN_ERR_INTERNAL for any other purely internal errors
1773 * Additionnally, in the case of SN_ERR_RESOURCE, an emergency log will be emitted.
1774 *
1775 * Blocks and then unblocks SIGCHLD
1776 */
1777static int connect_proc_chk(struct task *t)
1778{
Cyril Bontéac92a062014-12-27 22:28:38 +01001779 char buf[256];
Simon Horman98637e52014-06-20 12:30:16 +09001780 struct check *check = t->context;
1781 struct server *s = check->server;
1782 struct proxy *px = s->proxy;
1783 int status;
1784 pid_t pid;
1785
Simon Horman98637e52014-06-20 12:30:16 +09001786 status = SN_ERR_RESOURCE;
1787
1788 block_sigchld();
1789
1790 pid = fork();
1791 if (pid < 0) {
1792 Alert("Failed to fork process for external health check: %s. Aborting.\n",
1793 strerror(errno));
1794 set_server_check_status(check, HCHK_STATUS_SOCKERR, strerror(errno));
1795 goto out;
1796 }
1797 if (pid == 0) {
1798 /* Child */
1799 extern char **environ;
1800 environ = check->envp;
Cyril Bontéac92a062014-12-27 22:28:38 +01001801 extchk_setenv(check, EXTCHK_HAPROXY_SERVER_CURCONN, ultoa_r(s->cur_sess, buf, sizeof(buf)));
Simon Horman98637e52014-06-20 12:30:16 +09001802 execvp(px->check_command, check->argv);
1803 Alert("Failed to exec process for external health check: %s. Aborting.\n",
1804 strerror(errno));
1805 exit(-1);
1806 }
1807
1808 /* Parent */
1809 if (check->result == CHK_RES_UNKNOWN) {
1810 if (pid_list_add(pid, t) != NULL) {
1811 t->expire = tick_add(now_ms, MS_TO_TICKS(check->inter));
1812
1813 if (px->timeout.check && px->timeout.connect) {
1814 int t_con = tick_add(now_ms, px->timeout.connect);
1815 t->expire = tick_first(t->expire, t_con);
1816 }
1817 status = SN_ERR_NONE;
1818 goto out;
1819 }
1820 else {
1821 set_server_check_status(check, HCHK_STATUS_SOCKERR, strerror(errno));
1822 }
1823 kill(pid, SIGTERM); /* process creation error */
1824 }
1825 else
1826 set_server_check_status(check, HCHK_STATUS_SOCKERR, strerror(errno));
1827
1828out:
1829 unblock_sigchld();
1830 return status;
1831}
1832
1833/*
Simon Horman98637e52014-06-20 12:30:16 +09001834 * manages a server health-check that uses a process. Returns
Willy Tarreaubaaee002006-06-26 02:48:02 +02001835 * the time the task accepts to wait, or TIME_ETERNITY for infinity.
1836 */
Simon Horman98637e52014-06-20 12:30:16 +09001837static struct task *process_chk_proc(struct task *t)
1838{
1839 struct check *check = t->context;
1840 struct server *s = check->server;
1841 struct connection *conn = check->conn;
1842 int rv;
1843 int ret;
1844 int expired = tick_is_expired(t->expire, now_ms);
1845
1846 if (!(check->state & CHK_ST_INPROGRESS)) {
1847 /* no check currently running */
1848 if (!expired) /* woke up too early */
1849 return t;
1850
1851 /* we don't send any health-checks when the proxy is
1852 * stopped, the server should not be checked or the check
1853 * is disabled.
1854 */
1855 if (((check->state & (CHK_ST_ENABLED | CHK_ST_PAUSED)) != CHK_ST_ENABLED) ||
1856 s->proxy->state == PR_STSTOPPED)
1857 goto reschedule;
1858
1859 /* we'll initiate a new check */
1860 set_server_check_status(check, HCHK_STATUS_START, NULL);
1861
1862 check->state |= CHK_ST_INPROGRESS;
1863
Simon Hormandbf70192015-01-30 11:22:53 +09001864 ret = connect_proc_chk(t);
Simon Horman98637e52014-06-20 12:30:16 +09001865 switch (ret) {
1866 case SN_ERR_UP:
1867 return t;
1868 case SN_ERR_NONE:
1869 /* we allow up to min(inter, timeout.connect) for a connection
1870 * to establish but only when timeout.check is set
1871 * as it may be to short for a full check otherwise
1872 */
1873 t->expire = tick_add(now_ms, MS_TO_TICKS(check->inter));
1874
1875 if (s->proxy->timeout.check && s->proxy->timeout.connect) {
1876 int t_con = tick_add(now_ms, s->proxy->timeout.connect);
1877 t->expire = tick_first(t->expire, t_con);
1878 }
1879
1880 goto reschedule;
1881
1882 case SN_ERR_SRVTO: /* ETIMEDOUT */
1883 case SN_ERR_SRVCL: /* ECONNREFUSED, ENETUNREACH, ... */
1884 conn->flags |= CO_FL_ERROR;
1885 chk_report_conn_err(conn, errno, 0);
1886 break;
1887 case SN_ERR_PRXCOND:
1888 case SN_ERR_RESOURCE:
1889 case SN_ERR_INTERNAL:
1890 conn->flags |= CO_FL_ERROR;
1891 chk_report_conn_err(conn, 0, 0);
1892 break;
1893 }
1894
1895 /* here, we have seen a synchronous error, no fd was allocated */
1896
1897 check->state &= ~CHK_ST_INPROGRESS;
1898 check_notify_failure(check);
1899
1900 /* we allow up to min(inter, timeout.connect) for a connection
1901 * to establish but only when timeout.check is set
1902 * as it may be to short for a full check otherwise
1903 */
1904 while (tick_is_expired(t->expire, now_ms)) {
1905 int t_con;
1906
1907 t_con = tick_add(t->expire, s->proxy->timeout.connect);
1908 t->expire = tick_add(t->expire, MS_TO_TICKS(check->inter));
1909
1910 if (s->proxy->timeout.check)
1911 t->expire = tick_first(t->expire, t_con);
1912 }
1913 }
1914 else {
1915 /* there was a test running.
1916 * First, let's check whether there was an uncaught error,
1917 * which can happen on connect timeout or error.
1918 */
1919 if (check->result == CHK_RES_UNKNOWN) {
1920 /* good connection is enough for pure TCP check */
1921 struct pid_list *elem = check->curpid;
1922 int status = HCHK_STATUS_UNKNOWN;
1923
1924 if (elem->exited) {
1925 status = elem->status; /* Save in case the process exits between use below */
1926 if (!WIFEXITED(status))
1927 check->code = -1;
1928 else
1929 check->code = WEXITSTATUS(status);
1930 if (!WIFEXITED(status) || WEXITSTATUS(status))
1931 status = HCHK_STATUS_PROCERR;
1932 else
1933 status = HCHK_STATUS_PROCOK;
1934 } else if (expired) {
1935 status = HCHK_STATUS_PROCTOUT;
Willy Tarreaudc3d1902014-07-08 00:56:27 +02001936 Warning("kill %d\n", (int)elem->pid);
Simon Horman98637e52014-06-20 12:30:16 +09001937 kill(elem->pid, SIGTERM);
1938 }
1939 set_server_check_status(check, status, NULL);
1940 }
1941
1942 if (check->result == CHK_RES_FAILED) {
1943 /* a failure or timeout detected */
1944 check_notify_failure(check);
1945 }
1946 else if (check->result == CHK_RES_CONDPASS) {
1947 /* check is OK but asks for stopping mode */
1948 check_notify_stopping(check);
1949 }
1950 else if (check->result == CHK_RES_PASSED) {
1951 /* a success was detected */
1952 check_notify_success(check);
1953 }
1954 check->state &= ~CHK_ST_INPROGRESS;
1955
1956 pid_list_del(check->curpid);
1957
1958 rv = 0;
1959 if (global.spread_checks > 0) {
1960 rv = srv_getinter(check) * global.spread_checks / 100;
1961 rv -= (int) (2 * rv * (rand() / (RAND_MAX + 1.0)));
1962 }
1963 t->expire = tick_add(now_ms, MS_TO_TICKS(srv_getinter(check) + rv));
1964 }
1965
1966 reschedule:
1967 while (tick_is_expired(t->expire, now_ms))
1968 t->expire = tick_add(t->expire, MS_TO_TICKS(check->inter));
1969 return t;
1970}
1971
1972/*
1973 * manages a server health-check that uses a connection. Returns
1974 * the time the task accepts to wait, or TIME_ETERNITY for infinity.
1975 */
1976static struct task *process_chk_conn(struct task *t)
Willy Tarreaubaaee002006-06-26 02:48:02 +02001977{
Simon Horman4a741432013-02-23 15:35:38 +09001978 struct check *check = t->context;
1979 struct server *s = check->server;
1980 struct connection *conn = check->conn;
Krzysztof Oledzkib304dc72007-10-14 23:40:01 +02001981 int rv;
Willy Tarreaufb56aab2012-09-28 14:40:02 +02001982 int ret;
Willy Tarreauacbdc7a2012-11-23 14:02:10 +01001983 int expired = tick_is_expired(t->expire, now_ms);
Willy Tarreaubaaee002006-06-26 02:48:02 +02001984
Willy Tarreau2c115e52013-12-11 19:41:16 +01001985 if (!(check->state & CHK_ST_INPROGRESS)) {
Willy Tarreau5a78f362012-11-23 12:47:05 +01001986 /* no check currently running */
Willy Tarreauacbdc7a2012-11-23 14:02:10 +01001987 if (!expired) /* woke up too early */
Willy Tarreau26c25062009-03-08 09:38:41 +01001988 return t;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001989
Simon Horman671b6f02013-11-25 10:46:39 +09001990 /* we don't send any health-checks when the proxy is
1991 * stopped, the server should not be checked or the check
1992 * is disabled.
Willy Tarreaubaaee002006-06-26 02:48:02 +02001993 */
Willy Tarreau0d924cc2013-12-11 21:26:24 +01001994 if (((check->state & (CHK_ST_ENABLED | CHK_ST_PAUSED)) != CHK_ST_ENABLED) ||
Willy Tarreau33a08db2013-12-11 21:03:31 +01001995 s->proxy->state == PR_STSTOPPED)
Willy Tarreau5a78f362012-11-23 12:47:05 +01001996 goto reschedule;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001997
1998 /* we'll initiate a new check */
Simon Horman4a741432013-02-23 15:35:38 +09001999 set_server_check_status(check, HCHK_STATUS_START, NULL);
Willy Tarreau1ae1b7b2012-09-28 15:28:30 +02002000
Willy Tarreau2c115e52013-12-11 19:41:16 +01002001 check->state |= CHK_ST_INPROGRESS;
Simon Horman4a741432013-02-23 15:35:38 +09002002 check->bi->p = check->bi->data;
2003 check->bi->i = 0;
2004 check->bo->p = check->bo->data;
2005 check->bo->o = 0;
Willy Tarreau1ae1b7b2012-09-28 15:28:30 +02002006
Simon Hormandbf70192015-01-30 11:22:53 +09002007 ret = connect_conn_chk(t);
Willy Tarreaufb56aab2012-09-28 14:40:02 +02002008 switch (ret) {
Simon Hormanb00d17a2014-06-13 16:18:16 +09002009 case SN_ERR_UP:
2010 return t;
Willy Tarreaufb56aab2012-09-28 14:40:02 +02002011 case SN_ERR_NONE:
Willy Tarreaufb56aab2012-09-28 14:40:02 +02002012 /* we allow up to min(inter, timeout.connect) for a connection
2013 * to establish but only when timeout.check is set
2014 * as it may be to short for a full check otherwise
2015 */
Simon Horman4a741432013-02-23 15:35:38 +09002016 t->expire = tick_add(now_ms, MS_TO_TICKS(check->inter));
Krzysztof Piotr Oledzki09605412009-09-23 22:09:24 +02002017
Willy Tarreaufb56aab2012-09-28 14:40:02 +02002018 if (s->proxy->timeout.check && s->proxy->timeout.connect) {
2019 int t_con = tick_add(now_ms, s->proxy->timeout.connect);
2020 t->expire = tick_first(t->expire, t_con);
Willy Tarreaubaaee002006-06-26 02:48:02 +02002021 }
Willy Tarreau06559ac2013-12-05 01:53:08 +01002022
2023 if (check->type)
2024 conn_data_want_recv(conn); /* prepare for reading a possible reply */
2025
Willy Tarreau5a78f362012-11-23 12:47:05 +01002026 goto reschedule;
2027
2028 case SN_ERR_SRVTO: /* ETIMEDOUT */
2029 case SN_ERR_SRVCL: /* ECONNREFUSED, ENETUNREACH, ... */
Willy Tarreau4bd07de2014-01-24 16:10:57 +01002030 conn->flags |= CO_FL_ERROR;
2031 chk_report_conn_err(conn, errno, 0);
Willy Tarreau5a78f362012-11-23 12:47:05 +01002032 break;
2033 case SN_ERR_PRXCOND:
2034 case SN_ERR_RESOURCE:
2035 case SN_ERR_INTERNAL:
Willy Tarreau4bd07de2014-01-24 16:10:57 +01002036 conn->flags |= CO_FL_ERROR;
2037 chk_report_conn_err(conn, 0, 0);
Willy Tarreau5a78f362012-11-23 12:47:05 +01002038 break;
Willy Tarreaubaaee002006-06-26 02:48:02 +02002039 }
2040
Willy Tarreau5a78f362012-11-23 12:47:05 +01002041 /* here, we have seen a synchronous error, no fd was allocated */
Willy Tarreau6b0a8502012-11-23 08:51:32 +01002042
Willy Tarreau2c115e52013-12-11 19:41:16 +01002043 check->state &= ~CHK_ST_INPROGRESS;
Willy Tarreau4eec5472014-05-20 22:32:27 +02002044 check_notify_failure(check);
Willy Tarreaubaaee002006-06-26 02:48:02 +02002045
Krzysztof Piotr Oledzki5259dfe2008-01-21 01:54:06 +01002046 /* we allow up to min(inter, timeout.connect) for a connection
2047 * to establish but only when timeout.check is set
2048 * as it may be to short for a full check otherwise
2049 */
Willy Tarreau0c303ee2008-07-07 00:09:58 +02002050 while (tick_is_expired(t->expire, now_ms)) {
2051 int t_con;
Krzysztof Piotr Oledzki5259dfe2008-01-21 01:54:06 +01002052
Willy Tarreau0c303ee2008-07-07 00:09:58 +02002053 t_con = tick_add(t->expire, s->proxy->timeout.connect);
Simon Horman4a741432013-02-23 15:35:38 +09002054 t->expire = tick_add(t->expire, MS_TO_TICKS(check->inter));
Krzysztof Piotr Oledzki5259dfe2008-01-21 01:54:06 +01002055
Willy Tarreau0c303ee2008-07-07 00:09:58 +02002056 if (s->proxy->timeout.check)
2057 t->expire = tick_first(t->expire, t_con);
Krzysztof Piotr Oledzki5259dfe2008-01-21 01:54:06 +01002058 }
Willy Tarreaubaaee002006-06-26 02:48:02 +02002059 }
2060 else {
Willy Tarreauf1503172012-09-28 19:39:36 +02002061 /* there was a test running.
2062 * First, let's check whether there was an uncaught error,
2063 * which can happen on connect timeout or error.
2064 */
Simon Hormanccaabcd2014-06-20 12:29:47 +09002065 if (check->result == CHK_RES_UNKNOWN) {
Willy Tarreau25e2ab52013-12-04 11:17:05 +01002066 /* good connection is enough for pure TCP check */
2067 if ((conn->flags & CO_FL_CONNECTED) && !check->type) {
Simon Horman4a741432013-02-23 15:35:38 +09002068 if (check->use_ssl)
2069 set_server_check_status(check, HCHK_STATUS_L6OK, NULL);
Willy Tarreauf1503172012-09-28 19:39:36 +02002070 else
Simon Horman4a741432013-02-23 15:35:38 +09002071 set_server_check_status(check, HCHK_STATUS_L4OK, NULL);
Willy Tarreauacbdc7a2012-11-23 14:02:10 +01002072 }
Willy Tarreau25e2ab52013-12-04 11:17:05 +01002073 else if ((conn->flags & CO_FL_ERROR) || expired) {
2074 chk_report_conn_err(conn, 0, expired);
Willy Tarreauf1503172012-09-28 19:39:36 +02002075 }
Willy Tarreau74fa7fb2012-11-23 14:43:49 +01002076 else
2077 goto out_wait; /* timeout not reached, wait again */
Willy Tarreauf1503172012-09-28 19:39:36 +02002078 }
2079
Willy Tarreau74fa7fb2012-11-23 14:43:49 +01002080 /* check complete or aborted */
Willy Tarreau5ba04f62013-02-12 15:23:12 +01002081 if (conn->xprt) {
2082 /* The check was aborted and the connection was not yet closed.
2083 * This can happen upon timeout, or when an external event such
2084 * as a failed response coupled with "observe layer7" caused the
2085 * server state to be suddenly changed.
2086 */
Willy Tarreaud85c4852015-03-13 00:40:28 +01002087 conn_sock_drain(conn);
Willy Tarreauf79c8172013-10-21 16:30:56 +02002088 conn_force_close(conn);
Willy Tarreau5ba04f62013-02-12 15:23:12 +01002089 }
2090
Willy Tarreauaf549582014-05-16 17:37:50 +02002091 if (check->result == CHK_RES_FAILED) {
2092 /* a failure or timeout detected */
Willy Tarreau4eec5472014-05-20 22:32:27 +02002093 check_notify_failure(check);
Willy Tarreauaf549582014-05-16 17:37:50 +02002094 }
Willy Tarreaudb58b792014-05-21 13:57:23 +02002095 else if (check->result == CHK_RES_CONDPASS) {
2096 /* check is OK but asks for stopping mode */
2097 check_notify_stopping(check);
Willy Tarreauaf549582014-05-16 17:37:50 +02002098 }
Willy Tarreau3e048382014-05-21 10:30:54 +02002099 else if (check->result == CHK_RES_PASSED) {
2100 /* a success was detected */
2101 check_notify_success(check);
Willy Tarreaubaaee002006-06-26 02:48:02 +02002102 }
Willy Tarreau2c115e52013-12-11 19:41:16 +01002103 check->state &= ~CHK_ST_INPROGRESS;
Krzysztof Oledzkib304dc72007-10-14 23:40:01 +02002104
Willy Tarreau74fa7fb2012-11-23 14:43:49 +01002105 rv = 0;
2106 if (global.spread_checks > 0) {
Simon Horman4a741432013-02-23 15:35:38 +09002107 rv = srv_getinter(check) * global.spread_checks / 100;
Willy Tarreau74fa7fb2012-11-23 14:43:49 +01002108 rv -= (int) (2 * rv * (rand() / (RAND_MAX + 1.0)));
Willy Tarreaubaaee002006-06-26 02:48:02 +02002109 }
Simon Horman4a741432013-02-23 15:35:38 +09002110 t->expire = tick_add(now_ms, MS_TO_TICKS(srv_getinter(check) + rv));
Willy Tarreaubaaee002006-06-26 02:48:02 +02002111 }
Willy Tarreau5a78f362012-11-23 12:47:05 +01002112
2113 reschedule:
2114 while (tick_is_expired(t->expire, now_ms))
Simon Horman4a741432013-02-23 15:35:38 +09002115 t->expire = tick_add(t->expire, MS_TO_TICKS(check->inter));
Willy Tarreau74fa7fb2012-11-23 14:43:49 +01002116 out_wait:
Willy Tarreau26c25062009-03-08 09:38:41 +01002117 return t;
Willy Tarreaubaaee002006-06-26 02:48:02 +02002118}
2119
Simon Horman98637e52014-06-20 12:30:16 +09002120/*
2121 * manages a server health-check. Returns
2122 * the time the task accepts to wait, or TIME_ETERNITY for infinity.
2123 */
2124static struct task *process_chk(struct task *t)
2125{
2126 struct check *check = t->context;
2127
2128 if (check->type == PR_O2_EXT_CHK)
2129 return process_chk_proc(t);
2130 return process_chk_conn(t);
2131}
2132
Simon Horman5c942422013-11-25 10:46:32 +09002133static int start_check_task(struct check *check, int mininter,
2134 int nbcheck, int srvpos)
2135{
2136 struct task *t;
2137 /* task for the check */
2138 if ((t = task_new()) == NULL) {
2139 Alert("Starting [%s:%s] check: out of memory.\n",
2140 check->server->proxy->id, check->server->id);
2141 return 0;
2142 }
2143
2144 check->task = t;
2145 t->process = process_chk;
2146 t->context = check;
2147
Willy Tarreau1746eec2014-04-25 10:46:47 +02002148 if (mininter < srv_getinter(check))
2149 mininter = srv_getinter(check);
2150
2151 if (global.max_spread_checks && mininter > global.max_spread_checks)
2152 mininter = global.max_spread_checks;
2153
Simon Horman5c942422013-11-25 10:46:32 +09002154 /* check this every ms */
Willy Tarreau1746eec2014-04-25 10:46:47 +02002155 t->expire = tick_add(now_ms, MS_TO_TICKS(mininter * srvpos / nbcheck));
Simon Horman5c942422013-11-25 10:46:32 +09002156 check->start = now;
2157 task_queue(t);
2158
2159 return 1;
2160}
2161
Krzysztof Oledzkib304dc72007-10-14 23:40:01 +02002162/*
2163 * Start health-check.
2164 * Returns 0 if OK, -1 if error, and prints the error in this case.
2165 */
2166int start_checks() {
2167
2168 struct proxy *px;
2169 struct server *s;
2170 struct task *t;
Simon Horman4a741432013-02-23 15:35:38 +09002171 int nbcheck=0, mininter=0, srvpos=0;
Krzysztof Oledzkib304dc72007-10-14 23:40:01 +02002172
Willy Tarreau2c43a1e2007-10-14 23:05:39 +02002173 /* 1- count the checkers to run simultaneously.
2174 * We also determine the minimum interval among all of those which
2175 * have an interval larger than SRV_CHK_INTER_THRES. This interval
2176 * will be used to spread their start-up date. Those which have
Jamie Gloudon801a0a32012-08-25 00:18:33 -04002177 * a shorter interval will start independently and will not dictate
Willy Tarreau2c43a1e2007-10-14 23:05:39 +02002178 * too short an interval for all others.
2179 */
Krzysztof Oledzkib304dc72007-10-14 23:40:01 +02002180 for (px = proxy; px; px = px->next) {
2181 for (s = px->srv; s; s = s->next) {
Willy Tarreaue7b73482013-11-21 11:50:50 +01002182 if (s->slowstart) {
2183 if ((t = task_new()) == NULL) {
2184 Alert("Starting [%s:%s] check: out of memory.\n", px->id, s->id);
2185 return -1;
2186 }
2187 /* We need a warmup task that will be called when the server
2188 * state switches from down to up.
2189 */
2190 s->warmup = t;
2191 t->process = server_warmup;
2192 t->context = s;
2193 t->expire = TICK_ETERNITY;
2194 }
2195
Willy Tarreaud8514a22013-12-11 21:10:14 +01002196 if (s->check.state & CHK_ST_CONFIGURED) {
2197 nbcheck++;
2198 if ((srv_getinter(&s->check) >= SRV_CHK_INTER_THRES) &&
2199 (!mininter || mininter > srv_getinter(&s->check)))
2200 mininter = srv_getinter(&s->check);
2201 }
Willy Tarreau15f39102013-12-11 20:41:18 +01002202
Willy Tarreaud8514a22013-12-11 21:10:14 +01002203 if (s->agent.state & CHK_ST_CONFIGURED) {
2204 nbcheck++;
2205 if ((srv_getinter(&s->agent) >= SRV_CHK_INTER_THRES) &&
2206 (!mininter || mininter > srv_getinter(&s->agent)))
2207 mininter = srv_getinter(&s->agent);
2208 }
Krzysztof Oledzkib304dc72007-10-14 23:40:01 +02002209 }
2210 }
2211
Simon Horman4a741432013-02-23 15:35:38 +09002212 if (!nbcheck)
Krzysztof Oledzkib304dc72007-10-14 23:40:01 +02002213 return 0;
2214
2215 srand((unsigned)time(NULL));
2216
2217 /*
2218 * 2- start them as far as possible from each others. For this, we will
2219 * start them after their interval set to the min interval divided by
2220 * the number of servers, weighted by the server's position in the list.
2221 */
2222 for (px = proxy; px; px = px->next) {
Simon Horman98637e52014-06-20 12:30:16 +09002223 if ((px->options2 & PR_O2_CHK_ANY) == PR_O2_EXT_CHK) {
2224 if (init_pid_list()) {
2225 Alert("Starting [%s] check: out of memory.\n", px->id);
2226 return -1;
2227 }
2228 }
2229
Krzysztof Oledzkib304dc72007-10-14 23:40:01 +02002230 for (s = px->srv; s; s = s->next) {
Simon Hormand60d6912013-11-25 10:46:36 +09002231 /* A task for the main check */
Willy Tarreauff5ae352013-12-11 20:36:34 +01002232 if (s->check.state & CHK_ST_CONFIGURED) {
Cyril Bonté99c5bf52014-08-07 01:55:38 +02002233 if (s->check.type == PR_O2_EXT_CHK) {
2234 if (!prepare_external_check(&s->check))
2235 return -1;
2236 }
Simon Hormand60d6912013-11-25 10:46:36 +09002237 if (!start_check_task(&s->check, mininter, nbcheck, srvpos))
2238 return -1;
2239 srvpos++;
2240 }
Krzysztof Oledzkib304dc72007-10-14 23:40:01 +02002241
Simon Hormand60d6912013-11-25 10:46:36 +09002242 /* A task for a auxiliary agent check */
Willy Tarreauff5ae352013-12-11 20:36:34 +01002243 if (s->agent.state & CHK_ST_CONFIGURED) {
Simon Hormand60d6912013-11-25 10:46:36 +09002244 if (!start_check_task(&s->agent, mininter, nbcheck, srvpos)) {
2245 return -1;
2246 }
2247 srvpos++;
2248 }
Krzysztof Oledzkib304dc72007-10-14 23:40:01 +02002249 }
2250 }
2251 return 0;
2252}
Willy Tarreaubaaee002006-06-26 02:48:02 +02002253
2254/*
Willy Tarreau5b3a2022012-09-28 15:01:02 +02002255 * Perform content verification check on data in s->check.buffer buffer.
Willy Tarreaubd741542010-03-16 18:46:54 +01002256 * The buffer MUST be terminated by a null byte before calling this function.
2257 * Sets server status appropriately. The caller is responsible for ensuring
2258 * that the buffer contains at least 13 characters. If <done> is zero, we may
2259 * return 0 to indicate that data is required to decide of a match.
2260 */
2261static int httpchk_expect(struct server *s, int done)
2262{
2263 static char status_msg[] = "HTTP status check returned code <000>";
2264 char status_code[] = "000";
2265 char *contentptr;
2266 int crlf;
2267 int ret;
2268
2269 switch (s->proxy->options2 & PR_O2_EXP_TYPE) {
2270 case PR_O2_EXP_STS:
2271 case PR_O2_EXP_RSTS:
Willy Tarreau1ae1b7b2012-09-28 15:28:30 +02002272 memcpy(status_code, s->check.bi->data + 9, 3);
2273 memcpy(status_msg + strlen(status_msg) - 4, s->check.bi->data + 9, 3);
Willy Tarreaubd741542010-03-16 18:46:54 +01002274
2275 if ((s->proxy->options2 & PR_O2_EXP_TYPE) == PR_O2_EXP_STS)
2276 ret = strncmp(s->proxy->expect_str, status_code, 3) == 0;
2277 else
Thierry FOURNIER09af0d62014-06-18 11:35:54 +02002278 ret = regex_exec(s->proxy->expect_regex, status_code);
Willy Tarreaubd741542010-03-16 18:46:54 +01002279
2280 /* we necessarily have the response, so there are no partial failures */
2281 if (s->proxy->options2 & PR_O2_EXP_INV)
2282 ret = !ret;
2283
Simon Horman4a741432013-02-23 15:35:38 +09002284 set_server_check_status(&s->check, ret ? HCHK_STATUS_L7OKD : HCHK_STATUS_L7STS, status_msg);
Willy Tarreaubd741542010-03-16 18:46:54 +01002285 break;
2286
2287 case PR_O2_EXP_STR:
2288 case PR_O2_EXP_RSTR:
2289 /* very simple response parser: ignore CR and only count consecutive LFs,
2290 * stop with contentptr pointing to first char after the double CRLF or
2291 * to '\0' if crlf < 2.
2292 */
2293 crlf = 0;
Willy Tarreau1ae1b7b2012-09-28 15:28:30 +02002294 for (contentptr = s->check.bi->data; *contentptr; contentptr++) {
Willy Tarreaubd741542010-03-16 18:46:54 +01002295 if (crlf >= 2)
2296 break;
2297 if (*contentptr == '\r')
2298 continue;
2299 else if (*contentptr == '\n')
2300 crlf++;
2301 else
2302 crlf = 0;
2303 }
2304
2305 /* Check that response contains a body... */
2306 if (crlf < 2) {
2307 if (!done)
2308 return 0;
2309
Simon Horman4a741432013-02-23 15:35:38 +09002310 set_server_check_status(&s->check, HCHK_STATUS_L7RSP,
Willy Tarreaubd741542010-03-16 18:46:54 +01002311 "HTTP content check could not find a response body");
2312 return 1;
2313 }
2314
2315 /* Check that response body is not empty... */
2316 if (*contentptr == '\0') {
Willy Tarreaua164fb52011-04-13 09:32:41 +02002317 if (!done)
2318 return 0;
2319
Simon Horman4a741432013-02-23 15:35:38 +09002320 set_server_check_status(&s->check, HCHK_STATUS_L7RSP,
Willy Tarreaubd741542010-03-16 18:46:54 +01002321 "HTTP content check found empty response body");
2322 return 1;
2323 }
2324
2325 /* Check the response content against the supplied string
2326 * or regex... */
2327 if ((s->proxy->options2 & PR_O2_EXP_TYPE) == PR_O2_EXP_STR)
2328 ret = strstr(contentptr, s->proxy->expect_str) != NULL;
2329 else
Thierry FOURNIER09af0d62014-06-18 11:35:54 +02002330 ret = regex_exec(s->proxy->expect_regex, contentptr);
Willy Tarreaubd741542010-03-16 18:46:54 +01002331
2332 /* if we don't match, we may need to wait more */
2333 if (!ret && !done)
2334 return 0;
2335
2336 if (ret) {
2337 /* content matched */
2338 if (s->proxy->options2 & PR_O2_EXP_INV)
Simon Horman4a741432013-02-23 15:35:38 +09002339 set_server_check_status(&s->check, HCHK_STATUS_L7RSP,
Willy Tarreaubd741542010-03-16 18:46:54 +01002340 "HTTP check matched unwanted content");
2341 else
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 content check matched");
2344 }
2345 else {
2346 if (s->proxy->options2 & PR_O2_EXP_INV)
Simon Horman4a741432013-02-23 15:35:38 +09002347 set_server_check_status(&s->check, HCHK_STATUS_L7OKD,
Willy Tarreaubd741542010-03-16 18:46:54 +01002348 "HTTP check did not match unwanted content");
2349 else
Simon Horman4a741432013-02-23 15:35:38 +09002350 set_server_check_status(&s->check, HCHK_STATUS_L7RSP,
Willy Tarreaubd741542010-03-16 18:46:54 +01002351 "HTTP content check did not match");
2352 }
2353 break;
2354 }
2355 return 1;
2356}
2357
Baptiste Assmann5ecb77f2013-10-06 23:24:13 +02002358/*
2359 * return the id of a step in a send/expect session
2360 */
Simon Hormane16c1b32015-01-30 11:22:57 +09002361static int tcpcheck_get_step_id(struct check *check)
Baptiste Assmann5ecb77f2013-10-06 23:24:13 +02002362{
2363 struct tcpcheck_rule *cur = NULL, *next = NULL;
2364 int i = 0;
2365
Willy Tarreau213c6782014-10-02 14:51:02 +02002366 /* not even started anything yet => step 0 = initial connect */
Simon Hormane16c1b32015-01-30 11:22:57 +09002367 if (check->current_step)
Willy Tarreau213c6782014-10-02 14:51:02 +02002368 return 0;
2369
Simon Hormane16c1b32015-01-30 11:22:57 +09002370 cur = check->last_started_step;
Baptiste Assmann5ecb77f2013-10-06 23:24:13 +02002371
2372 /* no step => first step */
2373 if (cur == NULL)
2374 return 1;
2375
2376 /* increment i until current step */
Simon Hormane16c1b32015-01-30 11:22:57 +09002377 list_for_each_entry(next, check->tcpcheck_rules, list) {
Baptiste Assmann5ecb77f2013-10-06 23:24:13 +02002378 if (next->list.p == &cur->list)
2379 break;
2380 ++i;
2381 }
2382
2383 return i;
2384}
2385
2386static void tcpcheck_main(struct connection *conn)
2387{
2388 char *contentptr;
Willy Tarreauf3d34822014-12-08 12:11:28 +01002389 struct tcpcheck_rule *cur, *next;
Baptiste Assmann5ecb77f2013-10-06 23:24:13 +02002390 int done = 0, ret = 0;
Baptiste Assmann5ecb77f2013-10-06 23:24:13 +02002391 struct check *check = conn->owner;
2392 struct server *s = check->server;
2393 struct task *t = check->task;
Simon Hormane16c1b32015-01-30 11:22:57 +09002394 struct list *head = check->tcpcheck_rules;
Baptiste Assmann5ecb77f2013-10-06 23:24:13 +02002395
Willy Tarreauef953952014-10-02 14:30:14 +02002396 /* here, we know that the check is complete or that it failed */
2397 if (check->result != CHK_RES_UNKNOWN)
2398 goto out_end_tcpcheck;
2399
2400 /* We have 4 possibilities here :
2401 * 1. we've not yet attempted step 1, and step 1 is a connect, so no
2402 * connection attempt was made yet ;
2403 * 2. we've not yet attempted step 1, and step 1 is a not connect or
2404 * does not exist (no rule), so a connection attempt was made
2405 * before coming here.
2406 * 3. we're coming back after having started with step 1, so we may
2407 * be waiting for a connection attempt to complete.
2408 * 4. the connection + handshake are complete
2409 *
2410 * #2 and #3 are quite similar, we want both the connection and the
2411 * handshake to complete before going any further. Thus we must always
2412 * wait for a connection to complete unless we're before and existing
2413 * step 1.
Baptiste Assmann69e273f2013-12-11 00:52:19 +01002414 */
Willy Tarreauef953952014-10-02 14:30:14 +02002415 if ((!(conn->flags & CO_FL_CONNECTED) || (conn->flags & CO_FL_HANDSHAKE)) &&
2416 (check->current_step || LIST_ISEMPTY(head))) {
Baptiste Assmann5ecb77f2013-10-06 23:24:13 +02002417 /* we allow up to min(inter, timeout.connect) for a connection
2418 * to establish but only when timeout.check is set
2419 * as it may be to short for a full check otherwise
2420 */
2421 while (tick_is_expired(t->expire, now_ms)) {
2422 int t_con;
2423
2424 t_con = tick_add(t->expire, s->proxy->timeout.connect);
2425 t->expire = tick_add(t->expire, MS_TO_TICKS(check->inter));
2426
2427 if (s->proxy->timeout.check)
2428 t->expire = tick_first(t->expire, t_con);
2429 }
2430 return;
2431 }
2432
Willy Tarreauef953952014-10-02 14:30:14 +02002433 /* special case: option tcp-check with no rule, a connect is enough */
2434 if (LIST_ISEMPTY(head)) {
2435 set_server_check_status(check, HCHK_STATUS_L4OK, NULL);
Baptiste Assmann5ecb77f2013-10-06 23:24:13 +02002436 goto out_end_tcpcheck;
Willy Tarreauef953952014-10-02 14:30:14 +02002437 }
Baptiste Assmann5ecb77f2013-10-06 23:24:13 +02002438
Willy Tarreau213c6782014-10-02 14:51:02 +02002439 /* no step means first step initialisation */
Baptiste Assmann5ecb77f2013-10-06 23:24:13 +02002440 if (check->current_step == NULL) {
Willy Tarreau213c6782014-10-02 14:51:02 +02002441 check->last_started_step = NULL;
Baptiste Assmann5ecb77f2013-10-06 23:24:13 +02002442 check->bo->p = check->bo->data;
2443 check->bo->o = 0;
2444 check->bi->p = check->bi->data;
2445 check->bi->i = 0;
2446 cur = check->current_step = LIST_ELEM(head->n, struct tcpcheck_rule *, list);
2447 t->expire = tick_add(now_ms, MS_TO_TICKS(check->inter));
2448 if (s->proxy->timeout.check)
2449 t->expire = tick_add_ifset(now_ms, s->proxy->timeout.check);
2450 }
2451 /* keep on processing step */
2452 else {
2453 cur = check->current_step;
2454 }
2455
Willy Tarreaufbe0edf2013-12-06 16:54:31 +01002456 /* It's only the rules which will enable send/recv */
2457 __conn_data_stop_both(conn);
2458
Willy Tarreauabca5b62013-12-06 14:19:25 +01002459 while (1) {
Willy Tarreaufbe0edf2013-12-06 16:54:31 +01002460 /* we have to try to flush the output buffer before reading, at the end,
2461 * or if we're about to send a string that does not fit in the remaining space.
2462 */
2463 if (check->bo->o &&
2464 (&cur->list == head ||
2465 check->current_step->action != TCPCHK_ACT_SEND ||
2466 check->current_step->string_len >= buffer_total_space(check->bo))) {
2467
Willy Tarreau1049b1f2014-02-02 01:51:17 +01002468 if (conn->xprt->snd_buf(conn, check->bo, 0) <= 0) {
Willy Tarreaufbe0edf2013-12-06 16:54:31 +01002469 if (conn->flags & CO_FL_ERROR) {
2470 chk_report_conn_err(conn, errno, 0);
2471 __conn_data_stop_both(conn);
2472 goto out_end_tcpcheck;
2473 }
2474 goto out_need_io;
Willy Tarreauabca5b62013-12-06 14:19:25 +01002475 }
Willy Tarreauabca5b62013-12-06 14:19:25 +01002476 }
2477
Willy Tarreaufbe0edf2013-12-06 16:54:31 +01002478 /* did we reach the end ? If so, let's check that everything was sent */
2479 if (&cur->list == head) {
2480 if (check->bo->o)
2481 goto out_need_io;
Willy Tarreauabca5b62013-12-06 14:19:25 +01002482 break;
Willy Tarreaufbe0edf2013-12-06 16:54:31 +01002483 }
Willy Tarreauabca5b62013-12-06 14:19:25 +01002484
Willy Tarreauf3d34822014-12-08 12:11:28 +01002485 /* have 'next' point to the next rule or NULL if we're on the last one */
2486 next = (struct tcpcheck_rule *)cur->list.n;
2487 if (&next->list == head)
2488 next = NULL;
2489
Baptiste Assmann69e273f2013-12-11 00:52:19 +01002490 if (check->current_step->action == TCPCHK_ACT_CONNECT) {
2491 struct protocol *proto;
2492 struct xprt_ops *xprt;
2493
2494 /* mark the step as started */
2495 check->last_started_step = check->current_step;
2496 /* first, shut existing connection */
2497 conn_force_close(conn);
2498
2499 /* prepare new connection */
2500 /* initialization */
2501 conn_init(conn);
2502 conn_attach(conn, check, &check_conn_cb);
2503 conn->target = &s->obj_type;
2504
2505 /* no client address */
2506 clear_addr(&conn->addr.from);
2507
Simon Horman41f58762015-01-30 11:22:56 +09002508 if (is_addr(&check->addr)) {
Baptiste Assmann69e273f2013-12-11 00:52:19 +01002509 /* we'll connect to the check addr specified on the server */
Simon Horman41f58762015-01-30 11:22:56 +09002510 conn->addr.to = check->addr;
Willy Tarreau640556c2014-05-09 23:38:15 +02002511 }
2512 else {
Baptiste Assmann69e273f2013-12-11 00:52:19 +01002513 /* we'll connect to the addr on the server */
2514 conn->addr.to = s->addr;
Willy Tarreau640556c2014-05-09 23:38:15 +02002515 }
Thierry FOURNIERbb2ae642015-01-14 11:31:49 +01002516 proto = protocol_by_family(conn->addr.to.ss_family);
Baptiste Assmann69e273f2013-12-11 00:52:19 +01002517
2518 /* port */
2519 if (check->current_step->port)
2520 set_host_port(&conn->addr.to, check->current_step->port);
2521 else if (check->port)
2522 set_host_port(&conn->addr.to, check->port);
2523
2524#ifdef USE_OPENSSL
2525 if (check->current_step->conn_opts & TCPCHK_OPT_SSL) {
2526 xprt = &ssl_sock;
Baptiste Assmann69e273f2013-12-11 00:52:19 +01002527 }
2528 else {
2529 xprt = &raw_sock;
2530 }
2531#else /* USE_OPENSSL */
2532 xprt = &raw_sock;
2533#endif /* USE_OPENSSL */
2534 conn_prepare(conn, proto, xprt);
2535
2536 ret = SN_ERR_INTERNAL;
2537 if (proto->connect)
Willy Tarreauf3d34822014-12-08 12:11:28 +01002538 ret = proto->connect(conn,
2539 1 /* I/O polling is always needed */,
2540 (next && next->action == TCPCHK_ACT_EXPECT) ? 0 : 2);
Baptiste Assmann69e273f2013-12-11 00:52:19 +01002541 conn->flags |= CO_FL_WAKE_DATA;
2542 if (check->current_step->conn_opts & TCPCHK_OPT_SEND_PROXY) {
2543 conn->send_proxy_ofs = 1;
2544 conn->flags |= CO_FL_SEND_PROXY;
2545 }
2546
2547 /* It can return one of :
2548 * - SN_ERR_NONE if everything's OK
2549 * - SN_ERR_SRVTO if there are no more servers
2550 * - SN_ERR_SRVCL if the connection was refused by the server
2551 * - SN_ERR_PRXCOND if the connection has been limited by the proxy (maxconn)
2552 * - SN_ERR_RESOURCE if a system resource is lacking (eg: fd limits, ports, ...)
2553 * - SN_ERR_INTERNAL for any other purely internal errors
2554 * Additionnally, in the case of SN_ERR_RESOURCE, an emergency log will be emitted.
2555 * Note that we try to prevent the network stack from sending the ACK during the
2556 * connect() when a pure TCP check is used (without PROXY protocol).
2557 */
2558 switch (ret) {
2559 case SN_ERR_NONE:
2560 /* we allow up to min(inter, timeout.connect) for a connection
2561 * to establish but only when timeout.check is set
2562 * as it may be to short for a full check otherwise
2563 */
2564 t->expire = tick_add(now_ms, MS_TO_TICKS(check->inter));
2565
2566 if (s->proxy->timeout.check && s->proxy->timeout.connect) {
2567 int t_con = tick_add(now_ms, s->proxy->timeout.connect);
2568 t->expire = tick_first(t->expire, t_con);
2569 }
2570 break;
2571 case SN_ERR_SRVTO: /* ETIMEDOUT */
2572 case SN_ERR_SRVCL: /* ECONNREFUSED, ENETUNREACH, ... */
2573 chunk_printf(&trash, "TCPCHK error establishing connection at step %d: %s",
Simon Hormane16c1b32015-01-30 11:22:57 +09002574 tcpcheck_get_step_id(check), strerror(errno));
Baptiste Assmann69e273f2013-12-11 00:52:19 +01002575 set_server_check_status(check, HCHK_STATUS_L4CON, trash.str);
2576 goto out_end_tcpcheck;
2577 case SN_ERR_PRXCOND:
2578 case SN_ERR_RESOURCE:
2579 case SN_ERR_INTERNAL:
2580 chunk_printf(&trash, "TCPCHK error establishing connection at step %d",
Simon Hormane16c1b32015-01-30 11:22:57 +09002581 tcpcheck_get_step_id(check));
Baptiste Assmann69e273f2013-12-11 00:52:19 +01002582 set_server_check_status(check, HCHK_STATUS_SOCKERR, trash.str);
2583 goto out_end_tcpcheck;
2584 }
2585
2586 /* allow next rule */
2587 cur = (struct tcpcheck_rule *)cur->list.n;
2588 check->current_step = cur;
2589
2590 /* don't do anything until the connection is established */
2591 if (!(conn->flags & CO_FL_CONNECTED)) {
2592 /* update expire time, should be done by process_chk */
2593 /* we allow up to min(inter, timeout.connect) for a connection
2594 * to establish but only when timeout.check is set
2595 * as it may be to short for a full check otherwise
2596 */
2597 while (tick_is_expired(t->expire, now_ms)) {
2598 int t_con;
2599
2600 t_con = tick_add(t->expire, s->proxy->timeout.connect);
2601 t->expire = tick_add(t->expire, MS_TO_TICKS(check->inter));
2602
2603 if (s->proxy->timeout.check)
2604 t->expire = tick_first(t->expire, t_con);
2605 }
2606 return;
2607 }
2608
2609 } /* end 'connect' */
2610 else if (check->current_step->action == TCPCHK_ACT_SEND) {
2611 /* mark the step as started */
2612 check->last_started_step = check->current_step;
2613
Baptiste Assmann5ecb77f2013-10-06 23:24:13 +02002614 /* reset the read buffer */
2615 if (*check->bi->data != '\0') {
2616 *check->bi->data = '\0';
2617 check->bi->i = 0;
2618 }
2619
2620 if (conn->flags & (CO_FL_SOCK_WR_SH | CO_FL_DATA_WR_SH)) {
2621 conn->flags |= CO_FL_ERROR;
2622 chk_report_conn_err(conn, 0, 0);
2623 goto out_end_tcpcheck;
2624 }
2625
Willy Tarreauabca5b62013-12-06 14:19:25 +01002626 if (check->current_step->string_len >= check->bo->size) {
2627 chunk_printf(&trash, "tcp-check send : string too large (%d) for buffer size (%d) at step %d",
2628 check->current_step->string_len, check->bo->size,
Simon Hormane16c1b32015-01-30 11:22:57 +09002629 tcpcheck_get_step_id(check));
Willy Tarreauabca5b62013-12-06 14:19:25 +01002630 set_server_check_status(check, HCHK_STATUS_L7RSP, trash.str);
2631 goto out_end_tcpcheck;
2632 }
Baptiste Assmann5ecb77f2013-10-06 23:24:13 +02002633
Willy Tarreaufbe0edf2013-12-06 16:54:31 +01002634 /* do not try to send if there is no space */
2635 if (check->current_step->string_len >= buffer_total_space(check->bo))
2636 continue;
2637
Baptiste Assmann5ecb77f2013-10-06 23:24:13 +02002638 bo_putblk(check->bo, check->current_step->string, check->current_step->string_len);
2639 *check->bo->p = '\0'; /* to make gdb output easier to read */
2640
Willy Tarreauabca5b62013-12-06 14:19:25 +01002641 /* go to next rule and try to send */
Baptiste Assmann5ecb77f2013-10-06 23:24:13 +02002642 cur = (struct tcpcheck_rule *)cur->list.n;
2643 check->current_step = cur;
Baptiste Assmann5ecb77f2013-10-06 23:24:13 +02002644 } /* end 'send' */
Willy Tarreau98aec9f2013-12-06 16:16:41 +01002645 else if (check->current_step->action == TCPCHK_ACT_EXPECT) {
Willy Tarreau6aaa1b82013-12-11 17:09:34 +01002646 if (unlikely(check->result == CHK_RES_FAILED))
Baptiste Assmann5ecb77f2013-10-06 23:24:13 +02002647 goto out_end_tcpcheck;
2648
Willy Tarreau310987a2014-01-22 19:46:33 +01002649 if (conn->xprt->rcv_buf(conn, check->bi, check->bi->size) <= 0) {
Willy Tarreaufbe0edf2013-12-06 16:54:31 +01002650 if (conn->flags & (CO_FL_ERROR | CO_FL_SOCK_RD_SH | CO_FL_DATA_RD_SH)) {
2651 done = 1;
2652 if ((conn->flags & CO_FL_ERROR) && !check->bi->i) {
2653 /* Report network errors only if we got no other data. Otherwise
2654 * we'll let the upper layers decide whether the response is OK
2655 * or not. It is very common that an RST sent by the server is
2656 * reported as an error just after the last data chunk.
2657 */
2658 chk_report_conn_err(conn, errno, 0);
2659 goto out_end_tcpcheck;
2660 }
Baptiste Assmann5ecb77f2013-10-06 23:24:13 +02002661 }
Willy Tarreaufbe0edf2013-12-06 16:54:31 +01002662 else
2663 goto out_need_io;
Baptiste Assmann5ecb77f2013-10-06 23:24:13 +02002664 }
2665
Baptiste Assmann69e273f2013-12-11 00:52:19 +01002666 /* mark the step as started */
2667 check->last_started_step = check->current_step;
2668
2669
Baptiste Assmann5ecb77f2013-10-06 23:24:13 +02002670 /* Intermediate or complete response received.
2671 * Terminate string in check->bi->data buffer.
2672 */
2673 if (check->bi->i < check->bi->size) {
2674 check->bi->data[check->bi->i] = '\0';
2675 }
2676 else {
2677 check->bi->data[check->bi->i - 1] = '\0';
2678 done = 1; /* buffer full, don't wait for more data */
2679 }
2680
2681 contentptr = check->bi->data;
Baptiste Assmann5ecb77f2013-10-06 23:24:13 +02002682
2683 /* Check that response body is not empty... */
Willy Tarreauec6b0122014-05-13 17:57:29 +02002684 if (!check->bi->i) {
Baptiste Assmann5ecb77f2013-10-06 23:24:13 +02002685 if (!done)
Willy Tarreaufbe0edf2013-12-06 16:54:31 +01002686 continue;
Baptiste Assmann5ecb77f2013-10-06 23:24:13 +02002687
2688 /* empty response */
2689 chunk_printf(&trash, "TCPCHK got an empty response at step %d",
Simon Hormane16c1b32015-01-30 11:22:57 +09002690 tcpcheck_get_step_id(check));
Baptiste Assmann5ecb77f2013-10-06 23:24:13 +02002691 set_server_check_status(check, HCHK_STATUS_L7RSP, trash.str);
2692
2693 goto out_end_tcpcheck;
2694 }
2695
2696 if (!done && (cur->string != NULL) && (check->bi->i < cur->string_len) )
Willy Tarreaua970c282013-12-06 12:47:19 +01002697 continue; /* try to read more */
Baptiste Assmann5ecb77f2013-10-06 23:24:13 +02002698
Willy Tarreaua970c282013-12-06 12:47:19 +01002699 tcpcheck_expect:
Baptiste Assmann5ecb77f2013-10-06 23:24:13 +02002700 if (cur->string != NULL)
Willy Tarreauec6b0122014-05-13 17:57:29 +02002701 ret = my_memmem(contentptr, check->bi->i, cur->string, cur->string_len) != NULL;
Baptiste Assmann5ecb77f2013-10-06 23:24:13 +02002702 else if (cur->expect_regex != NULL)
Thierry FOURNIER09af0d62014-06-18 11:35:54 +02002703 ret = regex_exec(cur->expect_regex, contentptr);
Baptiste Assmann5ecb77f2013-10-06 23:24:13 +02002704
2705 if (!ret && !done)
Willy Tarreaua970c282013-12-06 12:47:19 +01002706 continue; /* try to read more */
Baptiste Assmann5ecb77f2013-10-06 23:24:13 +02002707
2708 /* matched */
2709 if (ret) {
2710 /* matched but we did not want to => ERROR */
2711 if (cur->inverse) {
2712 /* we were looking for a string */
2713 if (cur->string != NULL) {
2714 chunk_printf(&trash, "TCPCHK matched unwanted content '%s' at step %d",
Simon Hormane16c1b32015-01-30 11:22:57 +09002715 cur->string, tcpcheck_get_step_id(check));
Baptiste Assmann5ecb77f2013-10-06 23:24:13 +02002716 }
2717 else {
2718 /* we were looking for a regex */
2719 chunk_printf(&trash, "TCPCHK matched unwanted content (regex) at step %d",
Simon Hormane16c1b32015-01-30 11:22:57 +09002720 tcpcheck_get_step_id(check));
Baptiste Assmann5ecb77f2013-10-06 23:24:13 +02002721 }
2722 set_server_check_status(check, HCHK_STATUS_L7RSP, trash.str);
2723 goto out_end_tcpcheck;
2724 }
2725 /* matched and was supposed to => OK, next step */
2726 else {
2727 cur = (struct tcpcheck_rule*)cur->list.n;
2728 check->current_step = cur;
Willy Tarreau98aec9f2013-12-06 16:16:41 +01002729 if (check->current_step->action == TCPCHK_ACT_EXPECT)
Baptiste Assmann5ecb77f2013-10-06 23:24:13 +02002730 goto tcpcheck_expect;
2731 __conn_data_stop_recv(conn);
2732 }
2733 }
2734 else {
2735 /* not matched */
2736 /* not matched and was not supposed to => OK, next step */
2737 if (cur->inverse) {
2738 cur = (struct tcpcheck_rule*)cur->list.n;
2739 check->current_step = cur;
Willy Tarreau98aec9f2013-12-06 16:16:41 +01002740 if (check->current_step->action == TCPCHK_ACT_EXPECT)
Baptiste Assmann5ecb77f2013-10-06 23:24:13 +02002741 goto tcpcheck_expect;
2742 __conn_data_stop_recv(conn);
2743 }
2744 /* not matched but was supposed to => ERROR */
2745 else {
2746 /* we were looking for a string */
2747 if (cur->string != NULL) {
2748 chunk_printf(&trash, "TCPCHK did not match content '%s' at step %d",
Simon Hormane16c1b32015-01-30 11:22:57 +09002749 cur->string, tcpcheck_get_step_id(check));
Baptiste Assmann5ecb77f2013-10-06 23:24:13 +02002750 }
2751 else {
2752 /* we were looking for a regex */
2753 chunk_printf(&trash, "TCPCHK did not match content (regex) at step %d",
Simon Hormane16c1b32015-01-30 11:22:57 +09002754 tcpcheck_get_step_id(check));
Baptiste Assmann5ecb77f2013-10-06 23:24:13 +02002755 }
2756 set_server_check_status(check, HCHK_STATUS_L7RSP, trash.str);
2757 goto out_end_tcpcheck;
2758 }
2759 }
2760 } /* end expect */
2761 } /* end loop over double chained step list */
2762
2763 set_server_check_status(check, HCHK_STATUS_L7OKD, "(tcp-check)");
2764 goto out_end_tcpcheck;
2765
Willy Tarreaufbe0edf2013-12-06 16:54:31 +01002766 out_need_io:
2767 if (check->bo->o)
2768 __conn_data_want_send(conn);
2769
2770 if (check->current_step->action == TCPCHK_ACT_EXPECT)
2771 __conn_data_want_recv(conn);
Baptiste Assmann5ecb77f2013-10-06 23:24:13 +02002772 return;
2773
2774 out_end_tcpcheck:
2775 /* collect possible new errors */
2776 if (conn->flags & CO_FL_ERROR)
2777 chk_report_conn_err(conn, 0, 0);
2778
Baptiste Assmann69e273f2013-12-11 00:52:19 +01002779 /* cleanup before leaving */
Baptiste Assmann5ecb77f2013-10-06 23:24:13 +02002780 check->current_step = NULL;
2781
Willy Tarreau6aaa1b82013-12-11 17:09:34 +01002782 if (check->result == CHK_RES_FAILED)
Baptiste Assmann5ecb77f2013-10-06 23:24:13 +02002783 conn->flags |= CO_FL_ERROR;
2784
2785 __conn_data_stop_both(conn);
Baptiste Assmann5ecb77f2013-10-06 23:24:13 +02002786
2787 return;
2788}
2789
Simon Hormanb1900d52015-01-30 11:22:54 +09002790const char *init_check(struct check *check, int type)
2791{
2792 check->type = type;
2793
2794 /* Allocate buffer for requests... */
2795 if ((check->bi = calloc(sizeof(struct buffer) + global.tune.chksize, sizeof(char))) == NULL) {
2796 return "out of memory while allocating check buffer";
2797 }
2798 check->bi->size = global.tune.chksize;
2799
2800 /* Allocate buffer for responses... */
2801 if ((check->bo = calloc(sizeof(struct buffer) + global.tune.chksize, sizeof(char))) == NULL) {
2802 return "out of memory while allocating check buffer";
2803 }
2804 check->bo->size = global.tune.chksize;
2805
2806 /* Allocate buffer for partial results... */
2807 if ((check->conn = calloc(1, sizeof(struct connection))) == NULL) {
2808 return "out of memory while allocating check connection";
2809 }
2810
2811 check->conn->t.sock.fd = -1; /* no agent in progress yet */
2812
2813 return NULL;
2814}
2815
Simon Hormanbfb5d332015-01-30 11:22:55 +09002816void free_check(struct check *check)
2817{
2818 free(check->bi);
2819 free(check->bo);
2820 free(check->conn);
2821}
2822
Simon Horman0ba0e4a2015-01-30 11:23:00 +09002823void email_alert_free(struct email_alert *alert)
2824{
2825 struct tcpcheck_rule *rule, *back;
2826
2827 if (!alert)
2828 return;
2829
2830 list_for_each_entry_safe(rule, back, &alert->tcpcheck_rules, list)
2831 free(rule);
2832 free(alert);
2833}
2834
2835static struct task *process_email_alert(struct task *t)
2836{
2837 struct check *check = t->context;
2838 struct email_alertq *q;
2839
2840 q = container_of(check, typeof(*q), check);
2841
2842 if (!(check->state & CHK_ST_ENABLED)) {
2843 if (LIST_ISEMPTY(&q->email_alerts)) {
2844 /* All alerts processed, delete check */
2845 task_delete(t);
2846 task_free(t);
2847 check->task = NULL;
2848 return NULL;
2849 } else {
2850 struct email_alert *alert;
2851
2852 alert = LIST_NEXT(&q->email_alerts, typeof(alert), list);
2853 check->tcpcheck_rules = &alert->tcpcheck_rules;
2854 LIST_DEL(&alert->list);
2855
2856 check->state |= CHK_ST_ENABLED;
2857 }
2858
2859 }
2860
2861 process_chk(t);
2862
2863 if (!(check->state & CHK_ST_INPROGRESS) && check->tcpcheck_rules) {
2864 struct email_alert *alert;
2865
2866 alert = container_of(check->tcpcheck_rules, typeof(*alert), tcpcheck_rules);
2867 email_alert_free(alert);
2868
2869 check->tcpcheck_rules = NULL;
2870 check->state &= ~CHK_ST_ENABLED;
2871 }
2872 return t;
2873}
2874
2875static int init_email_alert_checks(struct server *s)
2876{
2877 int i;
2878 struct mailer *mailer;
2879 const char *err_str;
2880 struct proxy *p = s->proxy;
2881
2882 if (p->email_alert.queues)
2883 /* Already initialised, nothing to do */
2884 return 1;
2885
2886 p->email_alert.queues = calloc(p->email_alert.mailers.m->count, sizeof *p->email_alert.queues);
2887 if (!p->email_alert.queues) {
2888 err_str = "out of memory while allocating checks array";
2889 goto error_alert;
2890 }
2891
2892 for (i = 0, mailer = p->email_alert.mailers.m->mailer_list;
2893 i < p->email_alert.mailers.m->count; i++, mailer = mailer->next) {
2894 struct email_alertq *q = &p->email_alert.queues[i];
2895 struct check *check = &q->check;
2896
2897
2898 LIST_INIT(&q->email_alerts);
2899
2900 check->inter = DEF_CHKINTR; /* XXX: Would like to Skip to the next alert, if any, ASAP.
2901 * But need enough time so that timeouts don't occur
2902 * during tcp check procssing. For now just us an arbitrary default. */
2903 check->rise = DEF_AGENT_RISETIME;
2904 check->fall = DEF_AGENT_FALLTIME;
2905 err_str = init_check(check, PR_O2_TCPCHK_CHK);
2906 if (err_str) {
2907 goto error_free;
2908 }
2909
2910 check->xprt = mailer->xprt;
2911 if (!get_host_port(&mailer->addr))
2912 /* Default to submission port */
2913 check->port = 587;
Simon Horman0ba0e4a2015-01-30 11:23:00 +09002914 check->addr = mailer->addr;
2915 check->server = s;
2916 }
2917
2918 return 1;
2919
2920error_free:
2921 while (i-- > 1)
2922 task_free(p->email_alert.queues[i].check.task);
2923 free(p->email_alert.queues);
2924 p->email_alert.queues = NULL;
2925error_alert:
2926 Alert("Email alert [%s] could not be initialised: %s\n", p->id, err_str);
2927 return 0;
2928}
2929
2930
2931static int add_tcpcheck_expect_str(struct list *list, const char *str)
2932{
2933 struct tcpcheck_rule *tcpcheck;
2934
2935 tcpcheck = calloc(1, sizeof *tcpcheck);
2936 if (!tcpcheck)
2937 return 0;
2938
2939 tcpcheck->action = TCPCHK_ACT_EXPECT;
2940 tcpcheck->string = strdup(str);
2941 if (!tcpcheck->string) {
2942 free(tcpcheck);
2943 return 0;
2944 }
2945
2946 LIST_ADDQ(list, &tcpcheck->list);
2947 return 1;
2948}
2949
2950static int add_tcpcheck_send_strs(struct list *list, const char * const *strs)
2951{
2952 struct tcpcheck_rule *tcpcheck;
2953 int i;
2954
2955 tcpcheck = calloc(1, sizeof *tcpcheck);
2956 if (!tcpcheck)
2957 return 0;
2958
2959 tcpcheck->action = TCPCHK_ACT_SEND;
2960
2961 tcpcheck->string_len = 0;
2962 for (i = 0; strs[i]; i++)
2963 tcpcheck->string_len += strlen(strs[i]);
2964
2965 tcpcheck->string = malloc(tcpcheck->string_len + 1);
2966 if (!tcpcheck->string) {
2967 free(tcpcheck);
2968 return 0;
2969 }
2970 tcpcheck->string[0] = '\0';
2971
2972 for (i = 0; strs[i]; i++)
2973 strcat(tcpcheck->string, strs[i]);
2974
2975 LIST_ADDQ(list, &tcpcheck->list);
2976 return 1;
2977}
2978
2979static int enqueue_one_email_alert(struct email_alertq *q, const char *msg)
2980{
2981 struct email_alert *alert = NULL;
2982 struct tcpcheck_rule *tcpcheck;
2983 struct check *check = &q->check;
2984 struct proxy *p = check->server->proxy;
2985
2986 alert = calloc(1, sizeof *alert);
2987 if (!alert) {
2988 goto error;
2989 }
2990 LIST_INIT(&alert->tcpcheck_rules);
2991
2992 tcpcheck = calloc(1, sizeof *tcpcheck);
2993 if (!tcpcheck)
2994 goto error;
2995 tcpcheck->action = TCPCHK_ACT_CONNECT;
2996 LIST_ADDQ(&alert->tcpcheck_rules, &tcpcheck->list);
2997
2998 if (!add_tcpcheck_expect_str(&alert->tcpcheck_rules, "220 "))
2999 goto error;
3000
3001 {
3002 const char * const strs[4] = { "EHLO ", p->email_alert.myhostname, "\r\n" };
3003 if (!add_tcpcheck_send_strs(&alert->tcpcheck_rules, strs))
3004 goto error;
3005 }
3006
3007 if (!add_tcpcheck_expect_str(&alert->tcpcheck_rules, "250 "))
3008 goto error;
3009
3010 {
3011 const char * const strs[4] = { "MAIL FROM:<", p->email_alert.from, ">\r\n" };
3012 if (!add_tcpcheck_send_strs(&alert->tcpcheck_rules, strs))
3013 goto error;
3014 }
3015
3016 if (!add_tcpcheck_expect_str(&alert->tcpcheck_rules, "250 "))
3017 goto error;
3018
3019 {
3020 const char * const strs[4] = { "RCPT TO:<", p->email_alert.to, ">\r\n" };
3021 if (!add_tcpcheck_send_strs(&alert->tcpcheck_rules, strs))
3022 goto error;
3023 }
3024
3025 if (!add_tcpcheck_expect_str(&alert->tcpcheck_rules, "250 "))
3026 goto error;
3027
3028 {
3029 const char * const strs[2] = { "DATA\r\n" };
3030 if (!add_tcpcheck_send_strs(&alert->tcpcheck_rules, strs))
3031 goto error;
3032 }
3033
3034 if (!add_tcpcheck_expect_str(&alert->tcpcheck_rules, "354 "))
3035 goto error;
3036
3037 {
3038 struct tm tm;
3039 char datestr[48];
3040 const char * const strs[18] = {
3041 "From: ", p->email_alert.from, "\n",
3042 "To: ", p->email_alert.to, "\n",
3043 "Date: ", datestr, "\n",
3044 "Subject: [HAproxy Alert] ", msg, "\n",
3045 "\n",
3046 msg, "\n",
3047 ".\r\n",
3048 "\r\n",
3049 NULL
3050 };
3051
3052 get_localtime(date.tv_sec, &tm);
3053
3054 if (strftime(datestr, sizeof(datestr), "%a, %d %b %Y %T %z (%Z)", &tm) == 0) {
3055 goto error;
3056 }
3057
3058 if (!add_tcpcheck_send_strs(&alert->tcpcheck_rules, strs))
3059 goto error;
3060 }
3061
3062 if (!add_tcpcheck_expect_str(&alert->tcpcheck_rules, "250 "))
3063 goto error;
3064
3065 {
3066 const char * const strs[2] = { "QUIT\r\n" };
3067 if (!add_tcpcheck_send_strs(&alert->tcpcheck_rules, strs))
3068 goto error;
3069 }
3070
3071 if (!add_tcpcheck_expect_str(&alert->tcpcheck_rules, "221 "))
3072 goto error;
3073
3074 if (!check->task) {
3075 struct task *t;
3076
3077 if ((t = task_new()) == NULL)
3078 goto error;
3079
3080 check->task = t;
3081 t->process = process_email_alert;
3082 t->context = check;
3083
3084 /* check this in one ms */
3085 t->expire = tick_add(now_ms, MS_TO_TICKS(1));
3086 check->start = now;
3087 task_queue(t);
3088 }
3089
3090 LIST_ADDQ(&q->email_alerts, &alert->list);
3091
3092 return 1;
3093
3094error:
3095 email_alert_free(alert);
3096 return 0;
3097}
3098
3099static void enqueue_email_alert(struct proxy *p, const char *msg)
3100{
3101 int i;
3102 struct mailer *mailer;
3103
3104 for (i = 0, mailer = p->email_alert.mailers.m->mailer_list;
3105 i < p->email_alert.mailers.m->count; i++, mailer = mailer->next) {
3106 if (!enqueue_one_email_alert(&p->email_alert.queues[i], msg)) {
3107 Alert("Email alert [%s] could not be enqueued: out of memory\n", p->id);
3108 return;
3109 }
3110 }
3111
3112 return;
3113}
3114
3115/*
3116 * Send email alert if configured.
3117 */
Simon Horman64e34162015-02-06 11:11:57 +09003118void send_email_alert(struct server *s, int level, const char *format, ...)
Simon Horman0ba0e4a2015-01-30 11:23:00 +09003119{
3120 va_list argp;
3121 char buf[1024];
3122 int len;
3123 struct proxy *p = s->proxy;
3124
Simon Horman64e34162015-02-06 11:11:57 +09003125 if (!p->email_alert.mailers.m || level > p->email_alert.level ||
3126 format == NULL || !init_email_alert_checks(s))
Simon Horman0ba0e4a2015-01-30 11:23:00 +09003127 return;
3128
3129 va_start(argp, format);
3130 len = vsnprintf(buf, sizeof(buf), format, argp);
3131 va_end(argp);
3132
3133 if (len < 0) {
3134 Alert("Email alert [%s] could format message\n", p->id);
3135 return;
3136 }
3137
3138 enqueue_email_alert(p, buf);
3139}
3140
Baptiste Assmann5ecb77f2013-10-06 23:24:13 +02003141
Willy Tarreaubd741542010-03-16 18:46:54 +01003142/*
Willy Tarreaubaaee002006-06-26 02:48:02 +02003143 * Local variables:
3144 * c-indent-level: 8
3145 * c-basic-offset: 8
3146 * End:
3147 */