blob: 62a07219ac3cae9d46205335d587a25fa032d239 [file] [log] [blame]
Willy Tarreaubaaee002006-06-26 02:48:02 +02001/*
2 * Health-checks functions.
3 *
Willy Tarreau26c25062009-03-08 09:38:41 +01004 * Copyright 2000-2009 Willy Tarreau <w@1wt.eu>
Krzysztof Piotr Oledzki09605412009-09-23 22:09:24 +02005 * Copyright 2007-2009 Krzysztof Piotr Oledzki <ole@ans.pl>
Willy Tarreaubaaee002006-06-26 02:48:02 +02006 *
7 * This program is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU General Public License
9 * as published by the Free Software Foundation; either version
10 * 2 of the License, or (at your option) any later version.
11 *
12 */
13
Willy Tarreaub8816082008-01-18 12:18:15 +010014#include <assert.h>
Krzysztof Piotr Oledzki09605412009-09-23 22:09:24 +020015#include <ctype.h>
Willy Tarreaubaaee002006-06-26 02:48:02 +020016#include <errno.h>
17#include <fcntl.h>
Willy Tarreau9b39dc52014-07-08 00:54:10 +020018#include <signal.h>
Simon Horman0ba0e4a2015-01-30 11:23:00 +090019#include <stdarg.h>
Willy Tarreaubaaee002006-06-26 02:48:02 +020020#include <stdio.h>
Krzysztof Oledzkib304dc72007-10-14 23:40:01 +020021#include <stdlib.h>
Willy Tarreau2dd0d472006-06-29 17:53:05 +020022#include <string.h>
Krzysztof Oledzkib304dc72007-10-14 23:40:01 +020023#include <time.h>
Willy Tarreaubaaee002006-06-26 02:48:02 +020024#include <unistd.h>
25#include <sys/socket.h>
Dmitry Sivachenkocaf58982009-08-24 15:11:06 +040026#include <sys/types.h>
Simon Horman98637e52014-06-20 12:30:16 +090027#include <sys/wait.h>
Willy Tarreaubaaee002006-06-26 02:48:02 +020028#include <netinet/in.h>
Willy Tarreau1274bc42009-07-15 07:16:31 +020029#include <netinet/tcp.h>
Willy Tarreaubaaee002006-06-26 02:48:02 +020030#include <arpa/inet.h>
31
Willy Tarreauc7e42382012-08-24 19:22:53 +020032#include <common/chunk.h>
Willy Tarreau2dd0d472006-06-29 17:53:05 +020033#include <common/compat.h>
34#include <common/config.h>
35#include <common/mini-clist.h>
Willy Tarreau83749182007-04-15 20:56:27 +020036#include <common/standard.h>
Willy Tarreau2dd0d472006-06-29 17:53:05 +020037#include <common/time.h>
Willy Tarreaubaaee002006-06-26 02:48:02 +020038
39#include <types/global.h>
Simon Horman0ba0e4a2015-01-30 11:23:00 +090040#include <types/mailers.h>
Willy Tarreaubaaee002006-06-26 02:48:02 +020041
Baptiste Assmann69e273f2013-12-11 00:52:19 +010042#ifdef USE_OPENSSL
43#include <types/ssl_sock.h>
44#include <proto/ssl_sock.h>
45#endif /* USE_OPENSSL */
46
Willy Tarreaubaaee002006-06-26 02:48:02 +020047#include <proto/backend.h>
Krzysztof Piotr Oledzki09605412009-09-23 22:09:24 +020048#include <proto/checks.h>
Simon Hormana2b9dad2013-02-12 10:45:54 +090049#include <proto/dumpstats.h>
Willy Tarreaubaaee002006-06-26 02:48:02 +020050#include <proto/fd.h>
51#include <proto/log.h>
52#include <proto/queue.h>
Willy Tarreauc6f4ce82009-06-10 11:09:37 +020053#include <proto/port_range.h>
Willy Tarreau3d300592007-03-18 18:34:41 +010054#include <proto/proto_http.h>
Willy Tarreaue8c66af2008-01-13 18:40:14 +010055#include <proto/proto_tcp.h>
Baptiste Assmann69e273f2013-12-11 00:52:19 +010056#include <proto/protocol.h>
Willy Tarreau2b5652f2006-12-31 17:46:05 +010057#include <proto/proxy.h>
Willy Tarreaufb56aab2012-09-28 14:40:02 +020058#include <proto/raw_sock.h>
Willy Tarreaubaaee002006-06-26 02:48:02 +020059#include <proto/server.h>
Simon Hormane0d1bfb2011-06-21 14:34:58 +090060#include <proto/session.h>
Willy Tarreau9e000c62011-03-10 14:03:36 +010061#include <proto/stream_interface.h>
Willy Tarreaubaaee002006-06-26 02:48:02 +020062#include <proto/task.h>
63
Willy Tarreaubd741542010-03-16 18:46:54 +010064static int httpchk_expect(struct server *s, int done);
Simon Hormane16c1b32015-01-30 11:22:57 +090065static int tcpcheck_get_step_id(struct check *);
Baptiste Assmann5ecb77f2013-10-06 23:24:13 +020066static void tcpcheck_main(struct connection *);
Willy Tarreaubd741542010-03-16 18:46:54 +010067
Simon Horman63a4a822012-03-19 07:24:41 +090068static const struct check_status check_statuses[HCHK_STATUS_SIZE] = {
Willy Tarreau6aaa1b82013-12-11 17:09:34 +010069 [HCHK_STATUS_UNKNOWN] = { CHK_RES_UNKNOWN, "UNK", "Unknown" },
70 [HCHK_STATUS_INI] = { CHK_RES_UNKNOWN, "INI", "Initializing" },
Krzysztof Piotr Oledzki213014e2009-09-27 15:50:02 +020071 [HCHK_STATUS_START] = { /* SPECIAL STATUS*/ },
Krzysztof Piotr Oledzki09605412009-09-23 22:09:24 +020072
Willy Tarreau23964182014-05-20 20:56:30 +020073 /* Below we have finished checks */
74 [HCHK_STATUS_CHECKED] = { CHK_RES_NEUTRAL, "CHECKED", "No status change" },
Willy Tarreau6aaa1b82013-12-11 17:09:34 +010075 [HCHK_STATUS_HANA] = { CHK_RES_FAILED, "HANA", "Health analyze" },
Krzysztof Piotr Oledzki97f07b82009-12-15 22:31:24 +010076
Willy Tarreau6aaa1b82013-12-11 17:09:34 +010077 [HCHK_STATUS_SOCKERR] = { CHK_RES_FAILED, "SOCKERR", "Socket error" },
Krzysztof Piotr Oledzki09605412009-09-23 22:09:24 +020078
Willy Tarreau6aaa1b82013-12-11 17:09:34 +010079 [HCHK_STATUS_L4OK] = { CHK_RES_PASSED, "L4OK", "Layer4 check passed" },
80 [HCHK_STATUS_L4TOUT] = { CHK_RES_FAILED, "L4TOUT", "Layer4 timeout" },
81 [HCHK_STATUS_L4CON] = { CHK_RES_FAILED, "L4CON", "Layer4 connection problem" },
Krzysztof Piotr Oledzki09605412009-09-23 22:09:24 +020082
Willy Tarreau6aaa1b82013-12-11 17:09:34 +010083 [HCHK_STATUS_L6OK] = { CHK_RES_PASSED, "L6OK", "Layer6 check passed" },
84 [HCHK_STATUS_L6TOUT] = { CHK_RES_FAILED, "L6TOUT", "Layer6 timeout" },
85 [HCHK_STATUS_L6RSP] = { CHK_RES_FAILED, "L6RSP", "Layer6 invalid response" },
Krzysztof Piotr Oledzki09605412009-09-23 22:09:24 +020086
Willy Tarreau6aaa1b82013-12-11 17:09:34 +010087 [HCHK_STATUS_L7TOUT] = { CHK_RES_FAILED, "L7TOUT", "Layer7 timeout" },
88 [HCHK_STATUS_L7RSP] = { CHK_RES_FAILED, "L7RSP", "Layer7 invalid response" },
Krzysztof Piotr Oledzki09605412009-09-23 22:09:24 +020089
Krzysztof Piotr Oledzki213014e2009-09-27 15:50:02 +020090 [HCHK_STATUS_L57DATA] = { /* DUMMY STATUS */ },
Krzysztof Piotr Oledzki09605412009-09-23 22:09:24 +020091
Willy Tarreau6aaa1b82013-12-11 17:09:34 +010092 [HCHK_STATUS_L7OKD] = { CHK_RES_PASSED, "L7OK", "Layer7 check passed" },
93 [HCHK_STATUS_L7OKCD] = { CHK_RES_CONDPASS, "L7OKC", "Layer7 check conditionally passed" },
94 [HCHK_STATUS_L7STS] = { CHK_RES_FAILED, "L7STS", "Layer7 wrong status" },
Simon Horman98637e52014-06-20 12:30:16 +090095
96 [HCHK_STATUS_PROCERR] = { CHK_RES_FAILED, "PROCERR", "External check error" },
97 [HCHK_STATUS_PROCTOUT] = { CHK_RES_FAILED, "PROCTOUT", "External check timeout" },
Cyril Bonté77010d82014-08-07 01:55:37 +020098 [HCHK_STATUS_PROCOK] = { CHK_RES_PASSED, "PROCOK", "External check passed" },
Krzysztof Piotr Oledzki09605412009-09-23 22:09:24 +020099};
100
Cyril Bontéac92a062014-12-27 22:28:38 +0100101const struct extcheck_env extcheck_envs[EXTCHK_SIZE] = {
102 [EXTCHK_PATH] = { "PATH", EXTCHK_SIZE_EVAL_INIT },
103 [EXTCHK_HAPROXY_PROXY_NAME] = { "HAPROXY_PROXY_NAME", EXTCHK_SIZE_EVAL_INIT },
104 [EXTCHK_HAPROXY_PROXY_ID] = { "HAPROXY_PROXY_ID", EXTCHK_SIZE_EVAL_INIT },
105 [EXTCHK_HAPROXY_PROXY_ADDR] = { "HAPROXY_PROXY_ADDR", EXTCHK_SIZE_EVAL_INIT },
106 [EXTCHK_HAPROXY_PROXY_PORT] = { "HAPROXY_PROXY_PORT", EXTCHK_SIZE_EVAL_INIT },
107 [EXTCHK_HAPROXY_SERVER_NAME] = { "HAPROXY_SERVER_NAME", EXTCHK_SIZE_EVAL_INIT },
108 [EXTCHK_HAPROXY_SERVER_ID] = { "HAPROXY_SERVER_ID", EXTCHK_SIZE_EVAL_INIT },
109 [EXTCHK_HAPROXY_SERVER_ADDR] = { "HAPROXY_SERVER_ADDR", EXTCHK_SIZE_EVAL_INIT },
110 [EXTCHK_HAPROXY_SERVER_PORT] = { "HAPROXY_SERVER_PORT", EXTCHK_SIZE_EVAL_INIT },
111 [EXTCHK_HAPROXY_SERVER_MAXCONN] = { "HAPROXY_SERVER_MAXCONN", EXTCHK_SIZE_EVAL_INIT },
112 [EXTCHK_HAPROXY_SERVER_CURCONN] = { "HAPROXY_SERVER_CURCONN", EXTCHK_SIZE_ULONG },
113};
114
Simon Horman63a4a822012-03-19 07:24:41 +0900115static const struct analyze_status analyze_statuses[HANA_STATUS_SIZE] = { /* 0: ignore, 1: error, 2: OK */
Krzysztof Piotr Oledzki97f07b82009-12-15 22:31:24 +0100116 [HANA_STATUS_UNKNOWN] = { "Unknown", { 0, 0 }},
117
118 [HANA_STATUS_L4_OK] = { "L4 successful connection", { 2, 0 }},
119 [HANA_STATUS_L4_ERR] = { "L4 unsuccessful connection", { 1, 1 }},
120
121 [HANA_STATUS_HTTP_OK] = { "Correct http response", { 0, 2 }},
122 [HANA_STATUS_HTTP_STS] = { "Wrong http response", { 0, 1 }},
123 [HANA_STATUS_HTTP_HDRRSP] = { "Invalid http response (headers)", { 0, 1 }},
124 [HANA_STATUS_HTTP_RSP] = { "Invalid http response", { 0, 1 }},
125
126 [HANA_STATUS_HTTP_READ_ERROR] = { "Read error (http)", { 0, 1 }},
127 [HANA_STATUS_HTTP_READ_TIMEOUT] = { "Read timeout (http)", { 0, 1 }},
128 [HANA_STATUS_HTTP_BROKEN_PIPE] = { "Close from server (http)", { 0, 1 }},
129};
130
Krzysztof Piotr Oledzki09605412009-09-23 22:09:24 +0200131/*
132 * Convert check_status code to description
133 */
134const char *get_check_status_description(short check_status) {
135
136 const char *desc;
137
138 if (check_status < HCHK_STATUS_SIZE)
Krzysztof Piotr Oledzki213014e2009-09-27 15:50:02 +0200139 desc = check_statuses[check_status].desc;
Krzysztof Piotr Oledzki09605412009-09-23 22:09:24 +0200140 else
141 desc = NULL;
142
143 if (desc && *desc)
144 return desc;
145 else
Krzysztof Piotr Oledzki213014e2009-09-27 15:50:02 +0200146 return check_statuses[HCHK_STATUS_UNKNOWN].desc;
Krzysztof Piotr Oledzki09605412009-09-23 22:09:24 +0200147}
148
149/*
150 * Convert check_status code to short info
151 */
152const char *get_check_status_info(short check_status) {
153
154 const char *info;
155
156 if (check_status < HCHK_STATUS_SIZE)
Krzysztof Piotr Oledzki213014e2009-09-27 15:50:02 +0200157 info = check_statuses[check_status].info;
Krzysztof Piotr Oledzki09605412009-09-23 22:09:24 +0200158 else
159 info = NULL;
160
161 if (info && *info)
162 return info;
163 else
Krzysztof Piotr Oledzki213014e2009-09-27 15:50:02 +0200164 return check_statuses[HCHK_STATUS_UNKNOWN].info;
Krzysztof Piotr Oledzki09605412009-09-23 22:09:24 +0200165}
166
Krzysztof Piotr Oledzki97f07b82009-12-15 22:31:24 +0100167const char *get_analyze_status(short analyze_status) {
168
169 const char *desc;
170
171 if (analyze_status < HANA_STATUS_SIZE)
172 desc = analyze_statuses[analyze_status].desc;
173 else
174 desc = NULL;
175
176 if (desc && *desc)
177 return desc;
178 else
179 return analyze_statuses[HANA_STATUS_UNKNOWN].desc;
180}
181
Willy Tarreaua150cf12014-05-20 21:57:23 +0200182/* Builds a string containing some information about the health check's result.
183 * The output string is allocated from the trash chunks. If the check is NULL,
184 * NULL is returned. This is designed to be used when emitting logs about health
185 * checks.
Willy Tarreauddd329c2014-05-16 16:46:12 +0200186 */
Willy Tarreaua150cf12014-05-20 21:57:23 +0200187static const char *check_reason_string(struct check *check)
Willy Tarreauddd329c2014-05-16 16:46:12 +0200188{
Willy Tarreaua150cf12014-05-20 21:57:23 +0200189 struct chunk *msg;
Krzysztof Piotr Oledzki99ab5f82009-09-27 17:28:21 +0200190
Willy Tarreaua150cf12014-05-20 21:57:23 +0200191 if (!check)
192 return NULL;
Krzysztof Piotr Oledzki99ab5f82009-09-27 17:28:21 +0200193
Willy Tarreaua150cf12014-05-20 21:57:23 +0200194 msg = get_trash_chunk();
195 chunk_printf(msg, "reason: %s", get_check_status_description(check->status));
Krzysztof Piotr Oledzki99ab5f82009-09-27 17:28:21 +0200196
Willy Tarreaua150cf12014-05-20 21:57:23 +0200197 if (check->status >= HCHK_STATUS_L57DATA)
198 chunk_appendf(msg, ", code: %d", check->code);
Krzysztof Piotr Oledzkif7089f52009-10-10 21:06:49 +0200199
Willy Tarreaua150cf12014-05-20 21:57:23 +0200200 if (*check->desc) {
201 struct chunk src;
Krzysztof Piotr Oledzkif7089f52009-10-10 21:06:49 +0200202
Willy Tarreaua150cf12014-05-20 21:57:23 +0200203 chunk_appendf(msg, ", info: \"");
Krzysztof Piotr Oledzkif7089f52009-10-10 21:06:49 +0200204
Willy Tarreaua150cf12014-05-20 21:57:23 +0200205 chunk_initlen(&src, check->desc, 0, strlen(check->desc));
206 chunk_asciiencode(msg, &src, '"');
Krzysztof Piotr Oledzkif7089f52009-10-10 21:06:49 +0200207
Willy Tarreaua150cf12014-05-20 21:57:23 +0200208 chunk_appendf(msg, "\"");
Krzysztof Piotr Oledzki99ab5f82009-09-27 17:28:21 +0200209 }
210
Willy Tarreaua150cf12014-05-20 21:57:23 +0200211 if (check->duration >= 0)
212 chunk_appendf(msg, ", check duration: %ldms", check->duration);
213
214 return msg->str;
Krzysztof Piotr Oledzki99ab5f82009-09-27 17:28:21 +0200215}
216
Krzysztof Piotr Oledzki09605412009-09-23 22:09:24 +0200217/*
Simon Horman4a741432013-02-23 15:35:38 +0900218 * Set check->status, update check->duration and fill check->result with
Willy Tarreau7b1d47c2014-05-20 14:55:13 +0200219 * an adequate CHK_RES_* value. The new check->health is computed based
220 * on the result.
Krzysztof Piotr Oledzki213014e2009-09-27 15:50:02 +0200221 *
222 * Show information in logs about failed health check if server is UP
223 * or succeeded health checks if server is DOWN.
Krzysztof Piotr Oledzki09605412009-09-23 22:09:24 +0200224 */
Simon Horman4a741432013-02-23 15:35:38 +0900225static void set_server_check_status(struct check *check, short status, const char *desc)
Willy Tarreau19d14ef2012-10-29 16:51:55 +0100226{
Simon Horman4a741432013-02-23 15:35:38 +0900227 struct server *s = check->server;
Willy Tarreaubef1b322014-05-13 21:01:39 +0200228 short prev_status = check->status;
Willy Tarreau7b1d47c2014-05-20 14:55:13 +0200229 int report = 0;
Simon Horman4a741432013-02-23 15:35:38 +0900230
Krzysztof Piotr Oledzki213014e2009-09-27 15:50:02 +0200231 if (status == HCHK_STATUS_START) {
Willy Tarreau6aaa1b82013-12-11 17:09:34 +0100232 check->result = CHK_RES_UNKNOWN; /* no result yet */
Simon Horman4a741432013-02-23 15:35:38 +0900233 check->desc[0] = '\0';
234 check->start = now;
Krzysztof Piotr Oledzki213014e2009-09-27 15:50:02 +0200235 return;
236 }
237
Simon Horman4a741432013-02-23 15:35:38 +0900238 if (!check->status)
Krzysztof Piotr Oledzki213014e2009-09-27 15:50:02 +0200239 return;
240
Krzysztof Piotr Oledzkif7089f52009-10-10 21:06:49 +0200241 if (desc && *desc) {
Simon Horman4a741432013-02-23 15:35:38 +0900242 strncpy(check->desc, desc, HCHK_DESC_LEN-1);
243 check->desc[HCHK_DESC_LEN-1] = '\0';
Krzysztof Piotr Oledzkif7089f52009-10-10 21:06:49 +0200244 } else
Simon Horman4a741432013-02-23 15:35:38 +0900245 check->desc[0] = '\0';
Krzysztof Piotr Oledzkif7089f52009-10-10 21:06:49 +0200246
Simon Horman4a741432013-02-23 15:35:38 +0900247 check->status = status;
Krzysztof Piotr Oledzki213014e2009-09-27 15:50:02 +0200248 if (check_statuses[status].result)
Simon Horman4a741432013-02-23 15:35:38 +0900249 check->result = check_statuses[status].result;
Krzysztof Piotr Oledzki09605412009-09-23 22:09:24 +0200250
Krzysztof Piotr Oledzki97f07b82009-12-15 22:31:24 +0100251 if (status == HCHK_STATUS_HANA)
Simon Horman4a741432013-02-23 15:35:38 +0900252 check->duration = -1;
253 else if (!tv_iszero(&check->start)) {
Krzysztof Piotr Oledzki213014e2009-09-27 15:50:02 +0200254 /* set_server_check_status() may be called more than once */
Simon Horman4a741432013-02-23 15:35:38 +0900255 check->duration = tv_ms_elapsed(&check->start, &now);
256 tv_zero(&check->start);
Krzysztof Piotr Oledzki213014e2009-09-27 15:50:02 +0200257 }
258
Willy Tarreau23964182014-05-20 20:56:30 +0200259 /* no change is expected if no state change occurred */
260 if (check->result == CHK_RES_NEUTRAL)
261 return;
262
Willy Tarreau7b1d47c2014-05-20 14:55:13 +0200263 report = 0;
Krzysztof Piotr Oledzki213014e2009-09-27 15:50:02 +0200264
Willy Tarreau7b1d47c2014-05-20 14:55:13 +0200265 switch (check->result) {
266 case CHK_RES_FAILED:
Willy Tarreau12634e12014-05-23 11:32:36 +0200267 /* Failure to connect to the agent as a secondary check should not
268 * cause the server to be marked down.
269 */
270 if ((!(check->state & CHK_ST_AGENT) ||
Simon Hormaneaabd522015-02-26 11:26:17 +0900271 (check->status >= HCHK_STATUS_L57DATA)) &&
Willy Tarreau12634e12014-05-23 11:32:36 +0200272 (check->health >= check->rise)) {
Willy Tarreau7b1d47c2014-05-20 14:55:13 +0200273 s->counters.failed_checks++;
274 report = 1;
275 check->health--;
276 if (check->health < check->rise)
277 check->health = 0;
278 }
279 break;
Krzysztof Piotr Oledzki213014e2009-09-27 15:50:02 +0200280
Willy Tarreau7b1d47c2014-05-20 14:55:13 +0200281 case CHK_RES_PASSED:
282 case CHK_RES_CONDPASS: /* "condpass" cannot make the first step but it OK after a "passed" */
283 if ((check->health < check->rise + check->fall - 1) &&
284 (check->result == CHK_RES_PASSED || check->health > 0)) {
285 report = 1;
286 check->health++;
Krzysztof Piotr Oledzki213014e2009-09-27 15:50:02 +0200287
Willy Tarreau7b1d47c2014-05-20 14:55:13 +0200288 if (check->health >= check->rise)
289 check->health = check->rise + check->fall - 1; /* OK now */
290 }
Krzysztof Piotr Oledzki213014e2009-09-27 15:50:02 +0200291
Willy Tarreau7b1d47c2014-05-20 14:55:13 +0200292 /* clear consecutive_errors if observing is enabled */
293 if (s->onerror)
294 s->consecutive_errors = 0;
295 break;
Krzysztof Piotr Oledzki97f07b82009-12-15 22:31:24 +0100296
Willy Tarreau7b1d47c2014-05-20 14:55:13 +0200297 default:
298 break;
299 }
Krzysztof Piotr Oledzki213014e2009-09-27 15:50:02 +0200300
Willy Tarreau7b1d47c2014-05-20 14:55:13 +0200301 if (s->proxy->options2 & PR_O2_LOGHCHKS &&
302 (status != prev_status || report)) {
303 chunk_printf(&trash,
Willy Tarreau12634e12014-05-23 11:32:36 +0200304 "%s check for %sserver %s/%s %s%s",
305 (check->state & CHK_ST_AGENT) ? "Agent" : "Health",
Willy Tarreauc93cd162014-05-13 15:54:22 +0200306 s->flags & SRV_F_BACKUP ? "backup " : "",
Willy Tarreau19d14ef2012-10-29 16:51:55 +0100307 s->proxy->id, s->id,
Willy Tarreau6aaa1b82013-12-11 17:09:34 +0100308 (check->result == CHK_RES_CONDPASS) ? "conditionally ":"",
Willy Tarreau7b1d47c2014-05-20 14:55:13 +0200309 (check->result >= CHK_RES_PASSED) ? "succeeded" : "failed");
Krzysztof Piotr Oledzki213014e2009-09-27 15:50:02 +0200310
Willy Tarreaua150cf12014-05-20 21:57:23 +0200311 srv_append_status(&trash, s, check_reason_string(check), -1, 0);
Krzysztof Piotr Oledzki213014e2009-09-27 15:50:02 +0200312
Willy Tarreau19d14ef2012-10-29 16:51:55 +0100313 chunk_appendf(&trash, ", status: %d/%d %s",
Willy Tarreau7b1d47c2014-05-20 14:55:13 +0200314 (check->health >= check->rise) ? check->health - check->rise + 1 : check->health,
315 (check->health >= check->rise) ? check->fall : check->rise,
316 (check->health >= check->rise) ? (s->uweight ? "UP" : "DRAIN") : "DOWN");
Krzysztof Piotr Oledzki213014e2009-09-27 15:50:02 +0200317
Willy Tarreau19d14ef2012-10-29 16:51:55 +0100318 Warning("%s.\n", trash.str);
319 send_log(s->proxy, LOG_NOTICE, "%s.\n", trash.str);
Simon Horman64e34162015-02-06 11:11:57 +0900320 send_email_alert(s, LOG_NOTICE, "%s", trash.str);
Krzysztof Piotr Oledzki213014e2009-09-27 15:50:02 +0200321 }
Krzysztof Piotr Oledzki09605412009-09-23 22:09:24 +0200322}
323
Willy Tarreau4eec5472014-05-20 22:32:27 +0200324/* Marks the check <check>'s server down if the current check is already failed
325 * and the server is not down yet nor in maintenance.
Willy Tarreaubaaee002006-06-26 02:48:02 +0200326 */
Willy Tarreau4eec5472014-05-20 22:32:27 +0200327static void check_notify_failure(struct check *check)
Willy Tarreaubaaee002006-06-26 02:48:02 +0200328{
Simon Horman4a741432013-02-23 15:35:38 +0900329 struct server *s = check->server;
Simon Hormane0d1bfb2011-06-21 14:34:58 +0900330
Willy Tarreau7b1d47c2014-05-20 14:55:13 +0200331 /* The agent secondary check should only cause a server to be marked
332 * as down if check->status is HCHK_STATUS_L7STS, which indicates
333 * that the agent returned "fail", "stopped" or "down".
334 * The implication here is that failure to connect to the agent
335 * as a secondary check should not cause the server to be marked
336 * down. */
337 if ((check->state & CHK_ST_AGENT) && check->status != HCHK_STATUS_L7STS)
338 return;
339
Willy Tarreau4eec5472014-05-20 22:32:27 +0200340 if (check->health > 0)
341 return;
Krzysztof Piotr Oledzkic8b16fc2008-02-18 01:26:35 +0100342
Willy Tarreau4eec5472014-05-20 22:32:27 +0200343 /* We only report a reason for the check if we did not do so previously */
344 srv_set_stopped(s, (!s->track && !(s->proxy->options2 & PR_O2_LOGHCHKS)) ? check_reason_string(check) : NULL);
Willy Tarreaubaaee002006-06-26 02:48:02 +0200345}
346
Willy Tarreauaf549582014-05-16 17:37:50 +0200347/* Marks the check <check> as valid and tries to set its server up, provided
Willy Tarreau3e048382014-05-21 10:30:54 +0200348 * it isn't in maintenance, it is not tracking a down server and other checks
349 * comply. The rule is simple : by default, a server is up, unless any of the
350 * following conditions is true :
351 * - health check failed (check->health < rise)
352 * - agent check failed (agent->health < rise)
353 * - the server tracks a down server (track && track->state == STOPPED)
354 * Note that if the server has a slowstart, it will switch to STARTING instead
355 * of RUNNING. Also, only the health checks support the nolb mode, so the
356 * agent's success may not take the server out of this mode.
Willy Tarreauaf549582014-05-16 17:37:50 +0200357 */
Willy Tarreau3e048382014-05-21 10:30:54 +0200358static void check_notify_success(struct check *check)
Willy Tarreauaf549582014-05-16 17:37:50 +0200359{
Simon Horman4a741432013-02-23 15:35:38 +0900360 struct server *s = check->server;
Krzysztof Piotr Oledzkic8b16fc2008-02-18 01:26:35 +0100361
Willy Tarreauaf549582014-05-16 17:37:50 +0200362 if (s->admin & SRV_ADMF_MAINT)
363 return;
Cyril Bontécd19e512010-01-31 22:34:03 +0100364
Willy Tarreau3e048382014-05-21 10:30:54 +0200365 if (s->track && s->track->state == SRV_ST_STOPPED)
Willy Tarreauaf549582014-05-16 17:37:50 +0200366 return;
Krzysztof Piotr Oledzkic8b16fc2008-02-18 01:26:35 +0100367
Willy Tarreau3e048382014-05-21 10:30:54 +0200368 if ((s->check.state & CHK_ST_ENABLED) && (s->check.health < s->check.rise))
369 return;
Krzysztof Piotr Oledzkic8b16fc2008-02-18 01:26:35 +0100370
Willy Tarreau3e048382014-05-21 10:30:54 +0200371 if ((s->agent.state & CHK_ST_ENABLED) && (s->agent.health < s->agent.rise))
372 return;
Willy Tarreauaf549582014-05-16 17:37:50 +0200373
Willy Tarreau3e048382014-05-21 10:30:54 +0200374 if ((check->state & CHK_ST_AGENT) && s->state == SRV_ST_STOPPING)
375 return;
Krzysztof Piotr Oledzkic8b16fc2008-02-18 01:26:35 +0100376
Willy Tarreau3e048382014-05-21 10:30:54 +0200377 srv_set_running(s, (!s->track && !(s->proxy->options2 & PR_O2_LOGHCHKS)) ? check_reason_string(check) : NULL);
Krzysztof Piotr Oledzkic8b16fc2008-02-18 01:26:35 +0100378}
379
Willy Tarreaudb58b792014-05-21 13:57:23 +0200380/* Marks the check <check> as valid and tries to set its server into stopping mode
381 * if it was running or starting, and provided it isn't in maintenance and other
382 * checks comply. The conditions for the server to be marked in stopping mode are
383 * the same as for it to be turned up. Also, only the health checks support the
384 * nolb mode.
Willy Tarreauaf549582014-05-16 17:37:50 +0200385 */
Willy Tarreaudb58b792014-05-21 13:57:23 +0200386static void check_notify_stopping(struct check *check)
Willy Tarreauaf549582014-05-16 17:37:50 +0200387{
Simon Horman4a741432013-02-23 15:35:38 +0900388 struct server *s = check->server;
Krzysztof Piotr Oledzkic8b16fc2008-02-18 01:26:35 +0100389
Willy Tarreauaf549582014-05-16 17:37:50 +0200390 if (s->admin & SRV_ADMF_MAINT)
391 return;
392
Willy Tarreaudb58b792014-05-21 13:57:23 +0200393 if (check->state & CHK_ST_AGENT)
394 return;
Krzysztof Piotr Oledzkic8b16fc2008-02-18 01:26:35 +0100395
Willy Tarreaudb58b792014-05-21 13:57:23 +0200396 if (s->track && s->track->state == SRV_ST_STOPPED)
397 return;
Krzysztof Piotr Oledzkic8b16fc2008-02-18 01:26:35 +0100398
Willy Tarreaudb58b792014-05-21 13:57:23 +0200399 if ((s->check.state & CHK_ST_ENABLED) && (s->check.health < s->check.rise))
400 return;
Krzysztof Piotr Oledzkic8b16fc2008-02-18 01:26:35 +0100401
Willy Tarreaudb58b792014-05-21 13:57:23 +0200402 if ((s->agent.state & CHK_ST_ENABLED) && (s->agent.health < s->agent.rise))
403 return;
Krzysztof Piotr Oledzkic8b16fc2008-02-18 01:26:35 +0100404
Willy Tarreaudb58b792014-05-21 13:57:23 +0200405 srv_set_stopping(s, (!s->track && !(s->proxy->options2 & PR_O2_LOGHCHKS)) ? check_reason_string(check) : NULL);
Krzysztof Piotr Oledzkic8b16fc2008-02-18 01:26:35 +0100406}
Willy Tarreaubaaee002006-06-26 02:48:02 +0200407
Willy Tarreau9fe7aae2013-12-31 23:47:37 +0100408/* note: use health_adjust() only, which first checks that the observe mode is
409 * enabled.
410 */
411void __health_adjust(struct server *s, short status)
Willy Tarreau19d14ef2012-10-29 16:51:55 +0100412{
Krzysztof Piotr Oledzki97f07b82009-12-15 22:31:24 +0100413 int failed;
414 int expire;
415
Krzysztof Piotr Oledzki97f07b82009-12-15 22:31:24 +0100416 if (s->observe >= HANA_OBS_SIZE)
417 return;
418
Willy Tarreaubb956662013-01-24 00:37:39 +0100419 if (status >= HANA_STATUS_SIZE || !analyze_statuses[status].desc)
Krzysztof Piotr Oledzki97f07b82009-12-15 22:31:24 +0100420 return;
421
422 switch (analyze_statuses[status].lr[s->observe - 1]) {
423 case 1:
424 failed = 1;
425 break;
426
427 case 2:
428 failed = 0;
429 break;
430
431 default:
432 return;
433 }
434
435 if (!failed) {
436 /* good: clear consecutive_errors */
437 s->consecutive_errors = 0;
438 return;
439 }
440
441 s->consecutive_errors++;
442
443 if (s->consecutive_errors < s->consecutive_errors_limit)
444 return;
445
Willy Tarreau19d14ef2012-10-29 16:51:55 +0100446 chunk_printf(&trash, "Detected %d consecutive errors, last one was: %s",
447 s->consecutive_errors, get_analyze_status(status));
Krzysztof Piotr Oledzki97f07b82009-12-15 22:31:24 +0100448
449 switch (s->onerror) {
450 case HANA_ONERR_FASTINTER:
451 /* force fastinter - nothing to do here as all modes force it */
452 break;
453
454 case HANA_ONERR_SUDDTH:
455 /* simulate a pre-fatal failed health check */
Simon Horman58c32972013-11-25 10:46:38 +0900456 if (s->check.health > s->check.rise)
457 s->check.health = s->check.rise + 1;
Krzysztof Piotr Oledzki97f07b82009-12-15 22:31:24 +0100458
459 /* no break - fall through */
460
461 case HANA_ONERR_FAILCHK:
462 /* simulate a failed health check */
Simon Horman4a741432013-02-23 15:35:38 +0900463 set_server_check_status(&s->check, HCHK_STATUS_HANA, trash.str);
Willy Tarreau4eec5472014-05-20 22:32:27 +0200464 check_notify_failure(&s->check);
Krzysztof Piotr Oledzki97f07b82009-12-15 22:31:24 +0100465 break;
466
467 case HANA_ONERR_MARKDWN:
468 /* mark server down */
Simon Horman58c32972013-11-25 10:46:38 +0900469 s->check.health = s->check.rise;
Simon Horman4a741432013-02-23 15:35:38 +0900470 set_server_check_status(&s->check, HCHK_STATUS_HANA, trash.str);
Willy Tarreau4eec5472014-05-20 22:32:27 +0200471 check_notify_failure(&s->check);
Krzysztof Piotr Oledzki97f07b82009-12-15 22:31:24 +0100472 break;
473
474 default:
475 /* write a warning? */
476 break;
477 }
478
479 s->consecutive_errors = 0;
480 s->counters.failed_hana++;
481
Simon Horman66183002013-02-23 10:16:43 +0900482 if (s->check.fastinter) {
483 expire = tick_add(now_ms, MS_TO_TICKS(s->check.fastinter));
Sergiy Prykhodko1d57e502013-09-21 12:05:00 +0300484 if (s->check.task->expire > expire) {
Willy Tarreau5b3a2022012-09-28 15:01:02 +0200485 s->check.task->expire = expire;
Sergiy Prykhodko1d57e502013-09-21 12:05:00 +0300486 /* requeue check task with new expire */
487 task_queue(s->check.task);
488 }
Krzysztof Piotr Oledzki97f07b82009-12-15 22:31:24 +0100489 }
490}
491
Willy Tarreaua1dab552014-04-14 15:04:54 +0200492static int httpchk_build_status_header(struct server *s, char *buffer, int size)
Willy Tarreauef781042010-01-27 11:53:01 +0100493{
494 int sv_state;
495 int ratio;
496 int hlen = 0;
497 const char *srv_hlt_st[7] = { "DOWN", "DOWN %d/%d",
498 "UP %d/%d", "UP",
499 "NOLB %d/%d", "NOLB",
500 "no check" };
501
502 memcpy(buffer + hlen, "X-Haproxy-Server-State: ", 24);
503 hlen += 24;
504
Willy Tarreauff5ae352013-12-11 20:36:34 +0100505 if (!(s->check.state & CHK_ST_ENABLED))
506 sv_state = 6;
Willy Tarreau892337c2014-05-13 23:41:20 +0200507 else if (s->state != SRV_ST_STOPPED) {
Simon Horman58c32972013-11-25 10:46:38 +0900508 if (s->check.health == s->check.rise + s->check.fall - 1)
Willy Tarreauef781042010-01-27 11:53:01 +0100509 sv_state = 3; /* UP */
510 else
511 sv_state = 2; /* going down */
512
Willy Tarreau892337c2014-05-13 23:41:20 +0200513 if (s->state == SRV_ST_STOPPING)
Willy Tarreauef781042010-01-27 11:53:01 +0100514 sv_state += 2;
515 } else {
Simon Horman125d0992013-02-24 17:23:38 +0900516 if (s->check.health)
Willy Tarreauef781042010-01-27 11:53:01 +0100517 sv_state = 1; /* going up */
518 else
519 sv_state = 0; /* DOWN */
520 }
521
Willy Tarreaua1dab552014-04-14 15:04:54 +0200522 hlen += snprintf(buffer + hlen, size - hlen,
Willy Tarreauef781042010-01-27 11:53:01 +0100523 srv_hlt_st[sv_state],
Willy Tarreau892337c2014-05-13 23:41:20 +0200524 (s->state != SRV_ST_STOPPED) ? (s->check.health - s->check.rise + 1) : (s->check.health),
525 (s->state != SRV_ST_STOPPED) ? (s->check.fall) : (s->check.rise));
Willy Tarreauef781042010-01-27 11:53:01 +0100526
Willy Tarreaua1dab552014-04-14 15:04:54 +0200527 hlen += snprintf(buffer + hlen, size - hlen, "; name=%s/%s; node=%s; weight=%d/%d; scur=%d/%d; qcur=%d",
Willy Tarreauef781042010-01-27 11:53:01 +0100528 s->proxy->id, s->id,
529 global.node,
530 (s->eweight * s->proxy->lbprm.wmult + s->proxy->lbprm.wdiv - 1) / s->proxy->lbprm.wdiv,
531 (s->proxy->lbprm.tot_weight * s->proxy->lbprm.wmult + s->proxy->lbprm.wdiv - 1) / s->proxy->lbprm.wdiv,
532 s->cur_sess, s->proxy->beconn - s->proxy->nbpend,
533 s->nbpend);
534
Willy Tarreau892337c2014-05-13 23:41:20 +0200535 if ((s->state == SRV_ST_STARTING) &&
Willy Tarreauef781042010-01-27 11:53:01 +0100536 now.tv_sec < s->last_change + s->slowstart &&
537 now.tv_sec >= s->last_change) {
538 ratio = MAX(1, 100 * (now.tv_sec - s->last_change) / s->slowstart);
Willy Tarreaua1dab552014-04-14 15:04:54 +0200539 hlen += snprintf(buffer + hlen, size - hlen, "; throttle=%d%%", ratio);
Willy Tarreauef781042010-01-27 11:53:01 +0100540 }
541
542 buffer[hlen++] = '\r';
543 buffer[hlen++] = '\n';
544
545 return hlen;
546}
547
Willy Tarreau20a18342013-12-05 00:31:46 +0100548/* Check the connection. If an error has already been reported or the socket is
549 * closed, keep errno intact as it is supposed to contain the valid error code.
550 * If no error is reported, check the socket's error queue using getsockopt().
551 * Warning, this must be done only once when returning from poll, and never
552 * after an I/O error was attempted, otherwise the error queue might contain
553 * inconsistent errors. If an error is detected, the CO_FL_ERROR is set on the
554 * socket. Returns non-zero if an error was reported, zero if everything is
555 * clean (including a properly closed socket).
556 */
557static int retrieve_errno_from_socket(struct connection *conn)
558{
559 int skerr;
560 socklen_t lskerr = sizeof(skerr);
561
562 if (conn->flags & CO_FL_ERROR && ((errno && errno != EAGAIN) || !conn->ctrl))
563 return 1;
564
Willy Tarreau3c728722014-01-23 13:50:42 +0100565 if (!conn_ctrl_ready(conn))
Willy Tarreau20a18342013-12-05 00:31:46 +0100566 return 0;
567
568 if (getsockopt(conn->t.sock.fd, SOL_SOCKET, SO_ERROR, &skerr, &lskerr) == 0)
569 errno = skerr;
570
571 if (errno == EAGAIN)
572 errno = 0;
573
574 if (!errno) {
575 /* we could not retrieve an error, that does not mean there is
576 * none. Just don't change anything and only report the prior
577 * error if any.
578 */
579 if (conn->flags & CO_FL_ERROR)
580 return 1;
581 else
582 return 0;
583 }
584
585 conn->flags |= CO_FL_ERROR | CO_FL_SOCK_WR_SH | CO_FL_SOCK_RD_SH;
586 return 1;
587}
588
Willy Tarreau25e2ab52013-12-04 11:17:05 +0100589/* Try to collect as much information as possible on the connection status,
590 * and adjust the server status accordingly. It may make use of <errno_bck>
591 * if non-null when the caller is absolutely certain of its validity (eg:
592 * checked just after a syscall). If the caller doesn't have a valid errno,
593 * it can pass zero, and retrieve_errno_from_socket() will be called to try
594 * to extract errno from the socket. If no error is reported, it will consider
595 * the <expired> flag. This is intended to be used when a connection error was
596 * reported in conn->flags or when a timeout was reported in <expired>. The
597 * function takes care of not updating a server status which was already set.
598 * All situations where at least one of <expired> or CO_FL_ERROR are set
599 * produce a status.
600 */
601static void chk_report_conn_err(struct connection *conn, int errno_bck, int expired)
602{
603 struct check *check = conn->owner;
604 const char *err_msg;
Baptiste Assmann5ecb77f2013-10-06 23:24:13 +0200605 struct chunk *chk;
Willy Tarreau213c6782014-10-02 14:51:02 +0200606 int step;
Willy Tarreau25e2ab52013-12-04 11:17:05 +0100607
Willy Tarreau6aaa1b82013-12-11 17:09:34 +0100608 if (check->result != CHK_RES_UNKNOWN)
Willy Tarreau25e2ab52013-12-04 11:17:05 +0100609 return;
610
611 errno = errno_bck;
612 if (!errno || errno == EAGAIN)
613 retrieve_errno_from_socket(conn);
614
615 if (!(conn->flags & CO_FL_ERROR) && !expired)
616 return;
617
618 /* we'll try to build a meaningful error message depending on the
619 * context of the error possibly present in conn->err_code, and the
620 * socket error possibly collected above. This is useful to know the
621 * exact step of the L6 layer (eg: SSL handshake).
622 */
Baptiste Assmann5ecb77f2013-10-06 23:24:13 +0200623 chk = get_trash_chunk();
624
625 if (check->type == PR_O2_TCPCHK_CHK) {
Simon Hormane16c1b32015-01-30 11:22:57 +0900626 step = tcpcheck_get_step_id(check);
Willy Tarreau213c6782014-10-02 14:51:02 +0200627 if (!step)
628 chunk_printf(chk, " at initial connection step of tcp-check");
629 else {
630 chunk_printf(chk, " at step %d of tcp-check", step);
631 /* we were looking for a string */
632 if (check->last_started_step && check->last_started_step->action == TCPCHK_ACT_CONNECT) {
633 if (check->last_started_step->port)
634 chunk_appendf(chk, " (connect port %d)" ,check->last_started_step->port);
635 else
636 chunk_appendf(chk, " (connect)");
637 }
638 else if (check->last_started_step && check->last_started_step->action == TCPCHK_ACT_EXPECT) {
639 if (check->last_started_step->string)
640 chunk_appendf(chk, " (string '%s')", check->last_started_step->string);
641 else if (check->last_started_step->expect_regex)
642 chunk_appendf(chk, " (expect regex)");
643 }
644 else if (check->last_started_step && check->last_started_step->action == TCPCHK_ACT_SEND) {
645 chunk_appendf(chk, " (send)");
646 }
Baptiste Assmann5ecb77f2013-10-06 23:24:13 +0200647 }
648 }
649
Willy Tarreau25e2ab52013-12-04 11:17:05 +0100650 if (conn->err_code) {
651 if (errno && errno != EAGAIN)
Baptiste Assmann5ecb77f2013-10-06 23:24:13 +0200652 chunk_printf(&trash, "%s (%s)%s", conn_err_code_str(conn), strerror(errno), chk->str);
Willy Tarreau25e2ab52013-12-04 11:17:05 +0100653 else
Baptiste Assmann5ecb77f2013-10-06 23:24:13 +0200654 chunk_printf(&trash, "%s%s", conn_err_code_str(conn), chk->str);
Willy Tarreau25e2ab52013-12-04 11:17:05 +0100655 err_msg = trash.str;
656 }
657 else {
658 if (errno && errno != EAGAIN) {
Baptiste Assmann5ecb77f2013-10-06 23:24:13 +0200659 chunk_printf(&trash, "%s%s", strerror(errno), chk->str);
Willy Tarreau25e2ab52013-12-04 11:17:05 +0100660 err_msg = trash.str;
661 }
662 else {
Baptiste Assmann5ecb77f2013-10-06 23:24:13 +0200663 err_msg = chk->str;
Willy Tarreau25e2ab52013-12-04 11:17:05 +0100664 }
665 }
666
667 if ((conn->flags & (CO_FL_CONNECTED|CO_FL_WAIT_L4_CONN)) == CO_FL_WAIT_L4_CONN) {
668 /* L4 not established (yet) */
669 if (conn->flags & CO_FL_ERROR)
670 set_server_check_status(check, HCHK_STATUS_L4CON, err_msg);
671 else if (expired)
672 set_server_check_status(check, HCHK_STATUS_L4TOUT, err_msg);
673 }
674 else if ((conn->flags & (CO_FL_CONNECTED|CO_FL_WAIT_L6_CONN)) == CO_FL_WAIT_L6_CONN) {
675 /* L6 not established (yet) */
676 if (conn->flags & CO_FL_ERROR)
677 set_server_check_status(check, HCHK_STATUS_L6RSP, err_msg);
678 else if (expired)
679 set_server_check_status(check, HCHK_STATUS_L6TOUT, err_msg);
680 }
681 else if (conn->flags & CO_FL_ERROR) {
682 /* I/O error after connection was established and before we could diagnose */
683 set_server_check_status(check, HCHK_STATUS_SOCKERR, err_msg);
684 }
685 else if (expired) {
686 /* connection established but expired check */
687 if (check->type == PR_O2_SSL3_CHK)
688 set_server_check_status(check, HCHK_STATUS_L6TOUT, err_msg);
689 else /* HTTP, SMTP, ... */
690 set_server_check_status(check, HCHK_STATUS_L7TOUT, err_msg);
691 }
692
693 return;
694}
695
Willy Tarreaubaaee002006-06-26 02:48:02 +0200696/*
697 * This function is used only for server health-checks. It handles
Krzysztof Piotr Oledzki213014e2009-09-27 15:50:02 +0200698 * the connection acknowledgement. If the proxy requires L7 health-checks,
699 * it sends the request. In other cases, it calls set_server_check_status()
Simon Horman4a741432013-02-23 15:35:38 +0900700 * to set check->status, check->duration and check->result.
Willy Tarreaubaaee002006-06-26 02:48:02 +0200701 */
Willy Tarreaufb56aab2012-09-28 14:40:02 +0200702static void event_srv_chk_w(struct connection *conn)
Willy Tarreaubaaee002006-06-26 02:48:02 +0200703{
Simon Horman4a741432013-02-23 15:35:38 +0900704 struct check *check = conn->owner;
705 struct server *s = check->server;
Simon Horman4a741432013-02-23 15:35:38 +0900706 struct task *t = check->task;
Willy Tarreaufb56aab2012-09-28 14:40:02 +0200707
Willy Tarreau6aaa1b82013-12-11 17:09:34 +0100708 if (unlikely(check->result == CHK_RES_FAILED))
Willy Tarreau25e2ab52013-12-04 11:17:05 +0100709 goto out_wakeup;
710
Willy Tarreau310987a2014-01-22 19:46:33 +0100711 if (conn->flags & CO_FL_HANDSHAKE)
Willy Tarreau25e2ab52013-12-04 11:17:05 +0100712 return;
713
Willy Tarreau20a18342013-12-05 00:31:46 +0100714 if (retrieve_errno_from_socket(conn)) {
Willy Tarreau25e2ab52013-12-04 11:17:05 +0100715 chk_report_conn_err(conn, errno, 0);
Willy Tarreau20a18342013-12-05 00:31:46 +0100716 __conn_data_stop_both(conn);
717 goto out_wakeup;
718 }
Krzysztof Piotr Oledzki6492db52010-01-02 22:03:01 +0100719
Willy Tarreau25e2ab52013-12-04 11:17:05 +0100720 if (conn->flags & (CO_FL_SOCK_WR_SH | CO_FL_DATA_WR_SH)) {
Willy Tarreau20a18342013-12-05 00:31:46 +0100721 /* if the output is closed, we can't do anything */
722 conn->flags |= CO_FL_ERROR;
Willy Tarreau25e2ab52013-12-04 11:17:05 +0100723 chk_report_conn_err(conn, 0, 0);
Willy Tarreau20a18342013-12-05 00:31:46 +0100724 goto out_wakeup;
Krzysztof Piotr Oledzki09605412009-09-23 22:09:24 +0200725 }
Willy Tarreau6996e152007-04-30 14:37:43 +0200726
Willy Tarreau06559ac2013-12-05 01:53:08 +0100727 /* here, we know that the connection is established. That's enough for
728 * a pure TCP check.
729 */
730 if (!check->type)
731 goto out_wakeup;
732
Baptiste Assmann5ecb77f2013-10-06 23:24:13 +0200733 if (check->type == PR_O2_TCPCHK_CHK) {
734 tcpcheck_main(conn);
735 return;
736 }
737
Willy Tarreau25e2ab52013-12-04 11:17:05 +0100738 if (check->bo->o) {
Willy Tarreau1049b1f2014-02-02 01:51:17 +0100739 conn->xprt->snd_buf(conn, check->bo, 0);
Willy Tarreau25e2ab52013-12-04 11:17:05 +0100740 if (conn->flags & CO_FL_ERROR) {
741 chk_report_conn_err(conn, errno, 0);
742 __conn_data_stop_both(conn);
743 goto out_wakeup;
Willy Tarreaubaaee002006-06-26 02:48:02 +0200744 }
Willy Tarreau25e2ab52013-12-04 11:17:05 +0100745 if (check->bo->o)
746 return;
747 }
Willy Tarreau6996e152007-04-30 14:37:43 +0200748
Willy Tarreau25e2ab52013-12-04 11:17:05 +0100749 /* full request sent, we allow up to <timeout.check> if nonzero for a response */
750 if (s->proxy->timeout.check) {
751 t->expire = tick_add_ifset(now_ms, s->proxy->timeout.check);
752 task_queue(t);
Willy Tarreaubaaee002006-06-26 02:48:02 +0200753 }
Willy Tarreau25e2ab52013-12-04 11:17:05 +0100754 goto out_nowake;
755
Willy Tarreau83749182007-04-15 20:56:27 +0200756 out_wakeup:
Willy Tarreaufdccded2008-08-29 18:19:04 +0200757 task_wakeup(t, TASK_WOKEN_IO);
Willy Tarreau83749182007-04-15 20:56:27 +0200758 out_nowake:
Willy Tarreaufb56aab2012-09-28 14:40:02 +0200759 __conn_data_stop_send(conn); /* nothing more to write */
Willy Tarreaubaaee002006-06-26 02:48:02 +0200760}
761
Willy Tarreaubaaee002006-06-26 02:48:02 +0200762/*
Willy Tarreauf3c69202006-07-09 16:42:34 +0200763 * This function is used only for server health-checks. It handles the server's
Hervé COMMOWICK8776f1b2010-10-18 15:58:36 +0200764 * reply to an HTTP request, SSL HELLO or MySQL client Auth. It calls
Simon Horman4a741432013-02-23 15:35:38 +0900765 * set_server_check_status() to update check->status, check->duration
766 * and check->result.
Krzysztof Piotr Oledzki213014e2009-09-27 15:50:02 +0200767
768 * The set_server_check_status function is called with HCHK_STATUS_L7OKD if
769 * an HTTP server replies HTTP 2xx or 3xx (valid responses), if an SMTP server
770 * returns 2xx, HCHK_STATUS_L6OK if an SSL server returns at least 5 bytes in
771 * response to an SSL HELLO (the principle is that this is enough to
772 * distinguish between an SSL server and a pure TCP relay). All other cases will
773 * call it with a proper error status like HCHK_STATUS_L7STS, HCHK_STATUS_L6RSP,
774 * etc.
Willy Tarreaubaaee002006-06-26 02:48:02 +0200775 */
Willy Tarreaufb56aab2012-09-28 14:40:02 +0200776static void event_srv_chk_r(struct connection *conn)
Willy Tarreaubaaee002006-06-26 02:48:02 +0200777{
Simon Horman4a741432013-02-23 15:35:38 +0900778 struct check *check = conn->owner;
779 struct server *s = check->server;
780 struct task *t = check->task;
Krzysztof Piotr Oledzkif7089f52009-10-10 21:06:49 +0200781 char *desc;
Willy Tarreau03938182010-03-17 21:52:07 +0100782 int done;
Gabor Lekenyb4c81e42010-09-29 18:17:05 +0200783 unsigned short msglen;
Willy Tarreau83749182007-04-15 20:56:27 +0200784
Willy Tarreau6aaa1b82013-12-11 17:09:34 +0100785 if (unlikely(check->result == CHK_RES_FAILED))
Willy Tarreau83749182007-04-15 20:56:27 +0200786 goto out_wakeup;
Willy Tarreau83749182007-04-15 20:56:27 +0200787
Willy Tarreau310987a2014-01-22 19:46:33 +0100788 if (conn->flags & CO_FL_HANDSHAKE)
Willy Tarreaufb56aab2012-09-28 14:40:02 +0200789 return;
Baptiste Assmann5ecb77f2013-10-06 23:24:13 +0200790
791 if (check->type == PR_O2_TCPCHK_CHK) {
792 tcpcheck_main(conn);
793 return;
794 }
Willy Tarreaufb56aab2012-09-28 14:40:02 +0200795
Willy Tarreau83749182007-04-15 20:56:27 +0200796 /* Warning! Linux returns EAGAIN on SO_ERROR if data are still available
797 * but the connection was closed on the remote end. Fortunately, recv still
798 * works correctly and we don't need to do the getsockopt() on linux.
799 */
Nick Chalk57b1bf72010-03-16 15:50:46 +0000800
801 /* Set buffer to point to the end of the data already read, and check
802 * that there is free space remaining. If the buffer is full, proceed
803 * with running the checks without attempting another socket read.
804 */
Nick Chalk57b1bf72010-03-16 15:50:46 +0000805
Willy Tarreau03938182010-03-17 21:52:07 +0100806 done = 0;
Nick Chalk57b1bf72010-03-16 15:50:46 +0000807
Simon Horman4a741432013-02-23 15:35:38 +0900808 conn->xprt->rcv_buf(conn, check->bi, check->bi->size);
Willy Tarreauf1503172012-09-28 19:39:36 +0200809 if (conn->flags & (CO_FL_ERROR | CO_FL_SOCK_RD_SH | CO_FL_DATA_RD_SH)) {
Willy Tarreau03938182010-03-17 21:52:07 +0100810 done = 1;
Simon Horman4a741432013-02-23 15:35:38 +0900811 if ((conn->flags & CO_FL_ERROR) && !check->bi->i) {
Willy Tarreauf1503172012-09-28 19:39:36 +0200812 /* Report network errors only if we got no other data. Otherwise
813 * we'll let the upper layers decide whether the response is OK
814 * or not. It is very common that an RST sent by the server is
815 * reported as an error just after the last data chunk.
816 */
Willy Tarreau25e2ab52013-12-04 11:17:05 +0100817 chk_report_conn_err(conn, errno, 0);
Willy Tarreauc1a07962010-03-16 20:55:43 +0100818 goto out_wakeup;
819 }
Willy Tarreaubaaee002006-06-26 02:48:02 +0200820 }
821
Willy Tarreau25e2ab52013-12-04 11:17:05 +0100822
Willy Tarreau03938182010-03-17 21:52:07 +0100823 /* Intermediate or complete response received.
Simon Horman4a741432013-02-23 15:35:38 +0900824 * Terminate string in check->bi->data buffer.
Willy Tarreau03938182010-03-17 21:52:07 +0100825 */
Simon Horman4a741432013-02-23 15:35:38 +0900826 if (check->bi->i < check->bi->size)
827 check->bi->data[check->bi->i] = '\0';
Willy Tarreau03938182010-03-17 21:52:07 +0100828 else {
Simon Horman4a741432013-02-23 15:35:38 +0900829 check->bi->data[check->bi->i - 1] = '\0';
Willy Tarreau03938182010-03-17 21:52:07 +0100830 done = 1; /* buffer full, don't wait for more data */
831 }
Krzysztof Piotr Oledzkif7089f52009-10-10 21:06:49 +0200832
Nick Chalk57b1bf72010-03-16 15:50:46 +0000833 /* Run the checks... */
Simon Horman4a741432013-02-23 15:35:38 +0900834 switch (check->type) {
Willy Tarreau1620ec32011-08-06 17:05:02 +0200835 case PR_O2_HTTP_CHK:
Simon Horman4a741432013-02-23 15:35:38 +0900836 if (!done && check->bi->i < strlen("HTTP/1.0 000\r"))
Willy Tarreau03938182010-03-17 21:52:07 +0100837 goto wait_more_data;
838
Willy Tarreauc7dd71a2007-11-30 08:33:21 +0100839 /* Check if the server speaks HTTP 1.X */
Simon Horman4a741432013-02-23 15:35:38 +0900840 if ((check->bi->i < strlen("HTTP/1.0 000\r")) ||
841 (memcmp(check->bi->data, "HTTP/1.", 7) != 0 ||
842 (*(check->bi->data + 12) != ' ' && *(check->bi->data + 12) != '\r')) ||
843 !isdigit((unsigned char) *(check->bi->data + 9)) || !isdigit((unsigned char) *(check->bi->data + 10)) ||
844 !isdigit((unsigned char) *(check->bi->data + 11))) {
845 cut_crlf(check->bi->data);
846 set_server_check_status(check, HCHK_STATUS_L7RSP, check->bi->data);
Krzysztof Piotr Oledzkif7089f52009-10-10 21:06:49 +0200847
Willy Tarreauc7dd71a2007-11-30 08:33:21 +0100848 goto out_wakeup;
849 }
850
Simon Horman4a741432013-02-23 15:35:38 +0900851 check->code = str2uic(check->bi->data + 9);
852 desc = ltrim(check->bi->data + 12, ' ');
Nick Chalk57b1bf72010-03-16 15:50:46 +0000853
Willy Tarreaubd741542010-03-16 18:46:54 +0100854 if ((s->proxy->options & PR_O_DISABLE404) &&
Willy Tarreau892337c2014-05-13 23:41:20 +0200855 (s->state != SRV_ST_STOPPED) && (check->code == 404)) {
Nick Chalk57b1bf72010-03-16 15:50:46 +0000856 /* 404 may be accepted as "stopping" only if the server was up */
857 cut_crlf(desc);
Simon Horman4a741432013-02-23 15:35:38 +0900858 set_server_check_status(check, HCHK_STATUS_L7OKCD, desc);
Nick Chalk57b1bf72010-03-16 15:50:46 +0000859 }
Willy Tarreaubd741542010-03-16 18:46:54 +0100860 else if (s->proxy->options2 & PR_O2_EXP_TYPE) {
861 /* Run content verification check... We know we have at least 13 chars */
862 if (!httpchk_expect(s, done))
863 goto wait_more_data;
864 }
865 /* check the reply : HTTP/1.X 2xx and 3xx are OK */
Simon Horman4a741432013-02-23 15:35:38 +0900866 else if (*(check->bi->data + 9) == '2' || *(check->bi->data + 9) == '3') {
Willy Tarreaubd741542010-03-16 18:46:54 +0100867 cut_crlf(desc);
Simon Horman4a741432013-02-23 15:35:38 +0900868 set_server_check_status(check, HCHK_STATUS_L7OKD, desc);
Willy Tarreaubd741542010-03-16 18:46:54 +0100869 }
Nick Chalk57b1bf72010-03-16 15:50:46 +0000870 else {
871 cut_crlf(desc);
Simon Horman4a741432013-02-23 15:35:38 +0900872 set_server_check_status(check, HCHK_STATUS_L7STS, desc);
Nick Chalk57b1bf72010-03-16 15:50:46 +0000873 }
Willy Tarreau1620ec32011-08-06 17:05:02 +0200874 break;
875
876 case PR_O2_SSL3_CHK:
Simon Horman4a741432013-02-23 15:35:38 +0900877 if (!done && check->bi->i < 5)
Willy Tarreau03938182010-03-17 21:52:07 +0100878 goto wait_more_data;
879
Willy Tarreauc7dd71a2007-11-30 08:33:21 +0100880 /* Check for SSLv3 alert or handshake */
Simon Horman4a741432013-02-23 15:35:38 +0900881 if ((check->bi->i >= 5) && (*check->bi->data == 0x15 || *check->bi->data == 0x16))
882 set_server_check_status(check, HCHK_STATUS_L6OK, NULL);
Krzysztof Piotr Oledzki213014e2009-09-27 15:50:02 +0200883 else
Simon Horman4a741432013-02-23 15:35:38 +0900884 set_server_check_status(check, HCHK_STATUS_L6RSP, NULL);
Willy Tarreau1620ec32011-08-06 17:05:02 +0200885 break;
886
887 case PR_O2_SMTP_CHK:
Simon Horman4a741432013-02-23 15:35:38 +0900888 if (!done && check->bi->i < strlen("000\r"))
Willy Tarreau03938182010-03-17 21:52:07 +0100889 goto wait_more_data;
890
Krzysztof Piotr Oledzki09605412009-09-23 22:09:24 +0200891 /* Check if the server speaks SMTP */
Simon Horman4a741432013-02-23 15:35:38 +0900892 if ((check->bi->i < strlen("000\r")) ||
893 (*(check->bi->data + 3) != ' ' && *(check->bi->data + 3) != '\r') ||
894 !isdigit((unsigned char) *check->bi->data) || !isdigit((unsigned char) *(check->bi->data + 1)) ||
895 !isdigit((unsigned char) *(check->bi->data + 2))) {
896 cut_crlf(check->bi->data);
897 set_server_check_status(check, HCHK_STATUS_L7RSP, check->bi->data);
Krzysztof Piotr Oledzkif7089f52009-10-10 21:06:49 +0200898
Krzysztof Piotr Oledzki09605412009-09-23 22:09:24 +0200899 goto out_wakeup;
900 }
901
Simon Horman4a741432013-02-23 15:35:38 +0900902 check->code = str2uic(check->bi->data);
Krzysztof Piotr Oledzki09605412009-09-23 22:09:24 +0200903
Simon Horman4a741432013-02-23 15:35:38 +0900904 desc = ltrim(check->bi->data + 3, ' ');
Krzysztof Piotr Oledzkif7089f52009-10-10 21:06:49 +0200905 cut_crlf(desc);
906
Willy Tarreauc7dd71a2007-11-30 08:33:21 +0100907 /* Check for SMTP code 2xx (should be 250) */
Simon Horman4a741432013-02-23 15:35:38 +0900908 if (*check->bi->data == '2')
909 set_server_check_status(check, HCHK_STATUS_L7OKD, desc);
Krzysztof Piotr Oledzki213014e2009-09-27 15:50:02 +0200910 else
Simon Horman4a741432013-02-23 15:35:38 +0900911 set_server_check_status(check, HCHK_STATUS_L7STS, desc);
Willy Tarreau1620ec32011-08-06 17:05:02 +0200912 break;
913
Simon Hormana2b9dad2013-02-12 10:45:54 +0900914 case PR_O2_LB_AGENT_CHK: {
Willy Tarreau81f5d942013-12-09 20:51:51 +0100915 int status = HCHK_STATUS_CHECKED;
916 const char *hs = NULL; /* health status */
917 const char *as = NULL; /* admin status */
918 const char *ps = NULL; /* performance status */
919 const char *err = NULL; /* first error to report */
920 const char *wrn = NULL; /* first warning to report */
921 char *cmd, *p;
Simon Hormana2b9dad2013-02-12 10:45:54 +0900922
Willy Tarreau81f5d942013-12-09 20:51:51 +0100923 /* We're getting an agent check response. The agent could
924 * have been disabled in the mean time with a long check
925 * still pending. It is important that we ignore the whole
926 * response.
927 */
928 if (!(check->server->agent.state & CHK_ST_ENABLED))
929 break;
930
931 /* The agent supports strings made of a single line ended by the
932 * first CR ('\r') or LF ('\n'). This line is composed of words
933 * delimited by spaces (' '), tabs ('\t'), or commas (','). The
934 * line may optionally contained a description of a state change
935 * after a sharp ('#'), which is only considered if a health state
936 * is announced.
937 *
938 * Words may be composed of :
939 * - a numeric weight suffixed by the percent character ('%').
940 * - a health status among "up", "down", "stopped", and "fail".
941 * - an admin status among "ready", "drain", "maint".
942 *
943 * These words may appear in any order. If multiple words of the
944 * same category appear, the last one wins.
945 */
946
Willy Tarreau9809b782013-12-11 21:40:11 +0100947 p = check->bi->data;
948 while (*p && *p != '\n' && *p != '\r')
949 p++;
950
951 if (!*p) {
952 if (!done)
953 goto wait_more_data;
Simon Hormana2b9dad2013-02-12 10:45:54 +0900954
Willy Tarreau9809b782013-12-11 21:40:11 +0100955 /* at least inform the admin that the agent is mis-behaving */
956 set_server_check_status(check, check->status, "Ignoring incomplete line from agent");
957 break;
958 }
Willy Tarreau81f5d942013-12-09 20:51:51 +0100959
Willy Tarreau9809b782013-12-11 21:40:11 +0100960 *p = 0;
Willy Tarreau81f5d942013-12-09 20:51:51 +0100961 cmd = check->bi->data;
Simon Hormana2b9dad2013-02-12 10:45:54 +0900962
Willy Tarreau81f5d942013-12-09 20:51:51 +0100963 while (*cmd) {
964 /* look for next word */
965 if (*cmd == ' ' || *cmd == '\t' || *cmd == ',') {
966 cmd++;
967 continue;
968 }
Simon Horman671b6f02013-11-25 10:46:39 +0900969
Willy Tarreau81f5d942013-12-09 20:51:51 +0100970 if (*cmd == '#') {
971 /* this is the beginning of a health status description,
972 * skip the sharp and blanks.
973 */
974 cmd++;
975 while (*cmd == '\t' || *cmd == ' ')
976 cmd++;
Simon Horman671b6f02013-11-25 10:46:39 +0900977 break;
Simon Hormana2b9dad2013-02-12 10:45:54 +0900978 }
Willy Tarreau81f5d942013-12-09 20:51:51 +0100979
980 /* find the end of the word so that we have a null-terminated
981 * word between <cmd> and <p>.
982 */
983 p = cmd + 1;
984 while (*p && *p != '\t' && *p != ' ' && *p != '\n' && *p != ',')
985 p++;
986 if (*p)
987 *p++ = 0;
988
989 /* first, health statuses */
990 if (strcasecmp(cmd, "up") == 0) {
991 check->health = check->rise + check->fall - 1;
Simon Hormana2b9dad2013-02-12 10:45:54 +0900992 status = HCHK_STATUS_L7OKD;
Willy Tarreau81f5d942013-12-09 20:51:51 +0100993 hs = cmd;
994 }
995 else if (strcasecmp(cmd, "down") == 0) {
996 check->health = 0;
997 status = HCHK_STATUS_L7STS;
998 hs = cmd;
Simon Hormana2b9dad2013-02-12 10:45:54 +0900999 }
Willy Tarreau81f5d942013-12-09 20:51:51 +01001000 else if (strcasecmp(cmd, "stopped") == 0) {
1001 check->health = 0;
1002 status = HCHK_STATUS_L7STS;
1003 hs = cmd;
1004 }
1005 else if (strcasecmp(cmd, "fail") == 0) {
1006 check->health = 0;
1007 status = HCHK_STATUS_L7STS;
1008 hs = cmd;
1009 }
1010 /* admin statuses */
1011 else if (strcasecmp(cmd, "ready") == 0) {
1012 as = cmd;
1013 }
1014 else if (strcasecmp(cmd, "drain") == 0) {
1015 as = cmd;
1016 }
1017 else if (strcasecmp(cmd, "maint") == 0) {
1018 as = cmd;
1019 }
1020 /* else try to parse a weight here and keep the last one */
1021 else if (isdigit((unsigned char)*cmd) && strchr(cmd, '%') != NULL) {
1022 ps = cmd;
1023 }
1024 else {
1025 /* keep a copy of the first error */
1026 if (!err)
1027 err = cmd;
1028 }
1029 /* skip to next word */
1030 cmd = p;
1031 }
1032 /* here, cmd points either to \0 or to the beginning of a
1033 * description. Skip possible leading spaces.
1034 */
1035 while (*cmd == ' ' || *cmd == '\n')
1036 cmd++;
1037
1038 /* First, update the admin status so that we avoid sending other
1039 * possibly useless warnings and can also update the health if
1040 * present after going back up.
1041 */
1042 if (as) {
1043 if (strcasecmp(as, "drain") == 0)
1044 srv_adm_set_drain(check->server);
1045 else if (strcasecmp(as, "maint") == 0)
1046 srv_adm_set_maint(check->server);
1047 else
1048 srv_adm_set_ready(check->server);
Simon Hormana2b9dad2013-02-12 10:45:54 +09001049 }
1050
Willy Tarreau81f5d942013-12-09 20:51:51 +01001051 /* now change weights */
1052 if (ps) {
1053 const char *msg;
1054
1055 msg = server_parse_weight_change_request(s, ps);
1056 if (!wrn || !*wrn)
1057 wrn = msg;
1058 }
1059
1060 /* and finally health status */
1061 if (hs) {
1062 /* We'll report some of the warnings and errors we have
1063 * here. Down reports are critical, we leave them untouched.
1064 * Lack of report, or report of 'UP' leaves the room for
1065 * ERR first, then WARN.
Simon Hormana2b9dad2013-02-12 10:45:54 +09001066 */
Willy Tarreau81f5d942013-12-09 20:51:51 +01001067 const char *msg = cmd;
1068 struct chunk *t;
1069
1070 if (!*msg || status == HCHK_STATUS_L7OKD) {
1071 if (err && *err)
1072 msg = err;
1073 else if (wrn && *wrn)
1074 msg = wrn;
Simon Hormana2b9dad2013-02-12 10:45:54 +09001075 }
Willy Tarreau81f5d942013-12-09 20:51:51 +01001076
1077 t = get_trash_chunk();
1078 chunk_printf(t, "via agent : %s%s%s%s",
1079 hs, *msg ? " (" : "",
1080 msg, *msg ? ")" : "");
1081
1082 set_server_check_status(check, status, t->str);
Simon Hormana2b9dad2013-02-12 10:45:54 +09001083 }
Willy Tarreau81f5d942013-12-09 20:51:51 +01001084 else if (err && *err) {
1085 /* No status change but we'd like to report something odd.
1086 * Just report the current state and copy the message.
1087 */
1088 chunk_printf(&trash, "agent reports an error : %s", err);
1089 set_server_check_status(check, status/*check->status*/, trash.str);
Simon Hormana2b9dad2013-02-12 10:45:54 +09001090
Willy Tarreau81f5d942013-12-09 20:51:51 +01001091 }
1092 else if (wrn && *wrn) {
1093 /* No status change but we'd like to report something odd.
1094 * Just report the current state and copy the message.
1095 */
1096 chunk_printf(&trash, "agent warns : %s", wrn);
1097 set_server_check_status(check, status/*check->status*/, trash.str);
1098 }
1099 else
1100 set_server_check_status(check, status, NULL);
Simon Hormana2b9dad2013-02-12 10:45:54 +09001101 break;
1102 }
1103
Willy Tarreau1620ec32011-08-06 17:05:02 +02001104 case PR_O2_PGSQL_CHK:
Simon Horman4a741432013-02-23 15:35:38 +09001105 if (!done && check->bi->i < 9)
Rauf Kuliyev38b41562011-01-04 15:14:13 +01001106 goto wait_more_data;
1107
Simon Horman4a741432013-02-23 15:35:38 +09001108 if (check->bi->data[0] == 'R') {
1109 set_server_check_status(check, HCHK_STATUS_L7OKD, "PostgreSQL server is ok");
Rauf Kuliyev38b41562011-01-04 15:14:13 +01001110 }
1111 else {
Simon Horman4a741432013-02-23 15:35:38 +09001112 if ((check->bi->data[0] == 'E') && (check->bi->data[5]!=0) && (check->bi->data[6]!=0))
1113 desc = &check->bi->data[6];
Rauf Kuliyev38b41562011-01-04 15:14:13 +01001114 else
1115 desc = "PostgreSQL unknown error";
1116
Simon Horman4a741432013-02-23 15:35:38 +09001117 set_server_check_status(check, HCHK_STATUS_L7STS, desc);
Rauf Kuliyev38b41562011-01-04 15:14:13 +01001118 }
Willy Tarreau1620ec32011-08-06 17:05:02 +02001119 break;
1120
1121 case PR_O2_REDIS_CHK:
Simon Horman4a741432013-02-23 15:35:38 +09001122 if (!done && check->bi->i < 7)
Hervé COMMOWICKec032d62011-08-05 16:23:48 +02001123 goto wait_more_data;
1124
Simon Horman4a741432013-02-23 15:35:38 +09001125 if (strcmp(check->bi->data, "+PONG\r\n") == 0) {
1126 set_server_check_status(check, HCHK_STATUS_L7OKD, "Redis server is ok");
Hervé COMMOWICKec032d62011-08-05 16:23:48 +02001127 }
1128 else {
Simon Horman4a741432013-02-23 15:35:38 +09001129 set_server_check_status(check, HCHK_STATUS_L7STS, check->bi->data);
Hervé COMMOWICKec032d62011-08-05 16:23:48 +02001130 }
Willy Tarreau1620ec32011-08-06 17:05:02 +02001131 break;
1132
1133 case PR_O2_MYSQL_CHK:
Simon Horman4a741432013-02-23 15:35:38 +09001134 if (!done && check->bi->i < 5)
Willy Tarreau03938182010-03-17 21:52:07 +01001135 goto wait_more_data;
1136
Hervé COMMOWICK8776f1b2010-10-18 15:58:36 +02001137 if (s->proxy->check_len == 0) { // old mode
Simon Horman4a741432013-02-23 15:35:38 +09001138 if (*(check->bi->data + 4) != '\xff') {
Hervé COMMOWICK8776f1b2010-10-18 15:58:36 +02001139 /* We set the MySQL Version in description for information purpose
1140 * FIXME : it can be cool to use MySQL Version for other purpose,
1141 * like mark as down old MySQL server.
1142 */
Simon Horman4a741432013-02-23 15:35:38 +09001143 if (check->bi->i > 51) {
1144 desc = ltrim(check->bi->data + 5, ' ');
1145 set_server_check_status(check, HCHK_STATUS_L7OKD, desc);
Hervé COMMOWICK8776f1b2010-10-18 15:58:36 +02001146 }
1147 else {
1148 if (!done)
1149 goto wait_more_data;
1150 /* it seems we have a OK packet but without a valid length,
1151 * it must be a protocol error
1152 */
Simon Horman4a741432013-02-23 15:35:38 +09001153 set_server_check_status(check, HCHK_STATUS_L7RSP, check->bi->data);
Hervé COMMOWICK8776f1b2010-10-18 15:58:36 +02001154 }
Hervé COMMOWICK698ae002010-01-12 09:25:13 +01001155 }
1156 else {
Hervé COMMOWICK8776f1b2010-10-18 15:58:36 +02001157 /* An error message is attached in the Error packet */
Simon Horman4a741432013-02-23 15:35:38 +09001158 desc = ltrim(check->bi->data + 7, ' ');
1159 set_server_check_status(check, HCHK_STATUS_L7STS, desc);
Hervé COMMOWICK8776f1b2010-10-18 15:58:36 +02001160 }
1161 } else {
Simon Horman4a741432013-02-23 15:35:38 +09001162 unsigned int first_packet_len = ((unsigned int) *check->bi->data) +
1163 (((unsigned int) *(check->bi->data + 1)) << 8) +
1164 (((unsigned int) *(check->bi->data + 2)) << 16);
Hervé COMMOWICK8776f1b2010-10-18 15:58:36 +02001165
Simon Horman4a741432013-02-23 15:35:38 +09001166 if (check->bi->i == first_packet_len + 4) {
Hervé COMMOWICK8776f1b2010-10-18 15:58:36 +02001167 /* MySQL Error packet always begin with field_count = 0xff */
Simon Horman4a741432013-02-23 15:35:38 +09001168 if (*(check->bi->data + 4) != '\xff') {
Hervé COMMOWICK8776f1b2010-10-18 15:58:36 +02001169 /* We have only one MySQL packet and it is a Handshake Initialization packet
1170 * but we need to have a second packet to know if it is alright
1171 */
Simon Horman4a741432013-02-23 15:35:38 +09001172 if (!done && check->bi->i < first_packet_len + 5)
Hervé COMMOWICK8776f1b2010-10-18 15:58:36 +02001173 goto wait_more_data;
1174 }
1175 else {
1176 /* We have only one packet and it is an Error packet,
1177 * an error message is attached, so we can display it
1178 */
Simon Horman4a741432013-02-23 15:35:38 +09001179 desc = &check->bi->data[7];
Hervé COMMOWICK8776f1b2010-10-18 15:58:36 +02001180 //Warning("onlyoneERR: %s\n", desc);
Simon Horman4a741432013-02-23 15:35:38 +09001181 set_server_check_status(check, HCHK_STATUS_L7STS, desc);
Hervé COMMOWICK8776f1b2010-10-18 15:58:36 +02001182 }
Simon Horman4a741432013-02-23 15:35:38 +09001183 } else if (check->bi->i > first_packet_len + 4) {
1184 unsigned int second_packet_len = ((unsigned int) *(check->bi->data + first_packet_len + 4)) +
1185 (((unsigned int) *(check->bi->data + first_packet_len + 5)) << 8) +
1186 (((unsigned int) *(check->bi->data + first_packet_len + 6)) << 16);
Hervé COMMOWICK8776f1b2010-10-18 15:58:36 +02001187
Simon Horman4a741432013-02-23 15:35:38 +09001188 if (check->bi->i == first_packet_len + 4 + second_packet_len + 4 ) {
Hervé COMMOWICK8776f1b2010-10-18 15:58:36 +02001189 /* We have 2 packets and that's good */
1190 /* Check if the second packet is a MySQL Error packet or not */
Simon Horman4a741432013-02-23 15:35:38 +09001191 if (*(check->bi->data + first_packet_len + 8) != '\xff') {
Hervé COMMOWICK8776f1b2010-10-18 15:58:36 +02001192 /* No error packet */
1193 /* We set the MySQL Version in description for information purpose */
Simon Horman4a741432013-02-23 15:35:38 +09001194 desc = &check->bi->data[5];
Hervé COMMOWICK8776f1b2010-10-18 15:58:36 +02001195 //Warning("2packetOK: %s\n", desc);
Simon Horman4a741432013-02-23 15:35:38 +09001196 set_server_check_status(check, HCHK_STATUS_L7OKD, desc);
Hervé COMMOWICK8776f1b2010-10-18 15:58:36 +02001197 }
1198 else {
1199 /* An error message is attached in the Error packet
1200 * so we can display it ! :)
1201 */
Simon Horman4a741432013-02-23 15:35:38 +09001202 desc = &check->bi->data[first_packet_len+11];
Hervé COMMOWICK8776f1b2010-10-18 15:58:36 +02001203 //Warning("2packetERR: %s\n", desc);
Simon Horman4a741432013-02-23 15:35:38 +09001204 set_server_check_status(check, HCHK_STATUS_L7STS, desc);
Hervé COMMOWICK8776f1b2010-10-18 15:58:36 +02001205 }
1206 }
1207 }
1208 else {
Willy Tarreau03938182010-03-17 21:52:07 +01001209 if (!done)
1210 goto wait_more_data;
Hervé COMMOWICK8776f1b2010-10-18 15:58:36 +02001211 /* it seems we have a Handshake Initialization packet but without a valid length,
Hervé COMMOWICK698ae002010-01-12 09:25:13 +01001212 * it must be a protocol error
1213 */
Simon Horman4a741432013-02-23 15:35:38 +09001214 desc = &check->bi->data[5];
Hervé COMMOWICK8776f1b2010-10-18 15:58:36 +02001215 //Warning("protoerr: %s\n", desc);
Simon Horman4a741432013-02-23 15:35:38 +09001216 set_server_check_status(check, HCHK_STATUS_L7RSP, desc);
Hervé COMMOWICK698ae002010-01-12 09:25:13 +01001217 }
1218 }
Willy Tarreau1620ec32011-08-06 17:05:02 +02001219 break;
1220
1221 case PR_O2_LDAP_CHK:
Simon Horman4a741432013-02-23 15:35:38 +09001222 if (!done && check->bi->i < 14)
Gabor Lekenyb4c81e42010-09-29 18:17:05 +02001223 goto wait_more_data;
1224
1225 /* Check if the server speaks LDAP (ASN.1/BER)
1226 * http://en.wikipedia.org/wiki/Basic_Encoding_Rules
1227 * http://tools.ietf.org/html/rfc4511
1228 */
1229
1230 /* http://tools.ietf.org/html/rfc4511#section-4.1.1
1231 * LDAPMessage: 0x30: SEQUENCE
1232 */
Simon Horman4a741432013-02-23 15:35:38 +09001233 if ((check->bi->i < 14) || (*(check->bi->data) != '\x30')) {
1234 set_server_check_status(check, HCHK_STATUS_L7RSP, "Not LDAPv3 protocol");
Gabor Lekenyb4c81e42010-09-29 18:17:05 +02001235 }
1236 else {
1237 /* size of LDAPMessage */
Simon Horman4a741432013-02-23 15:35:38 +09001238 msglen = (*(check->bi->data + 1) & 0x80) ? (*(check->bi->data + 1) & 0x7f) : 0;
Gabor Lekenyb4c81e42010-09-29 18:17:05 +02001239
1240 /* http://tools.ietf.org/html/rfc4511#section-4.2.2
1241 * messageID: 0x02 0x01 0x01: INTEGER 1
1242 * protocolOp: 0x61: bindResponse
1243 */
1244 if ((msglen > 2) ||
Simon Horman4a741432013-02-23 15:35:38 +09001245 (memcmp(check->bi->data + 2 + msglen, "\x02\x01\x01\x61", 4) != 0)) {
1246 set_server_check_status(check, HCHK_STATUS_L7RSP, "Not LDAPv3 protocol");
Gabor Lekenyb4c81e42010-09-29 18:17:05 +02001247
1248 goto out_wakeup;
1249 }
1250
1251 /* size of bindResponse */
Simon Horman4a741432013-02-23 15:35:38 +09001252 msglen += (*(check->bi->data + msglen + 6) & 0x80) ? (*(check->bi->data + msglen + 6) & 0x7f) : 0;
Gabor Lekenyb4c81e42010-09-29 18:17:05 +02001253
1254 /* http://tools.ietf.org/html/rfc4511#section-4.1.9
1255 * ldapResult: 0x0a 0x01: ENUMERATION
1256 */
1257 if ((msglen > 4) ||
Simon Horman4a741432013-02-23 15:35:38 +09001258 (memcmp(check->bi->data + 7 + msglen, "\x0a\x01", 2) != 0)) {
1259 set_server_check_status(check, HCHK_STATUS_L7RSP, "Not LDAPv3 protocol");
Gabor Lekenyb4c81e42010-09-29 18:17:05 +02001260
1261 goto out_wakeup;
1262 }
1263
1264 /* http://tools.ietf.org/html/rfc4511#section-4.1.9
1265 * resultCode
1266 */
Simon Horman4a741432013-02-23 15:35:38 +09001267 check->code = *(check->bi->data + msglen + 9);
1268 if (check->code) {
1269 set_server_check_status(check, HCHK_STATUS_L7STS, "See RFC: http://tools.ietf.org/html/rfc4511#section-4.1.9");
Gabor Lekenyb4c81e42010-09-29 18:17:05 +02001270 } else {
Simon Horman4a741432013-02-23 15:35:38 +09001271 set_server_check_status(check, HCHK_STATUS_L7OKD, "Success");
Gabor Lekenyb4c81e42010-09-29 18:17:05 +02001272 }
1273 }
Willy Tarreau1620ec32011-08-06 17:05:02 +02001274 break;
1275
1276 default:
Willy Tarreau06559ac2013-12-05 01:53:08 +01001277 /* for other checks (eg: pure TCP), delegate to the main task */
Willy Tarreau1620ec32011-08-06 17:05:02 +02001278 break;
1279 } /* switch */
Willy Tarreau83749182007-04-15 20:56:27 +02001280
Willy Tarreauc7dd71a2007-11-30 08:33:21 +01001281 out_wakeup:
Willy Tarreau25e2ab52013-12-04 11:17:05 +01001282 /* collect possible new errors */
1283 if (conn->flags & CO_FL_ERROR)
1284 chk_report_conn_err(conn, 0, 0);
Willy Tarreaubaaee002006-06-26 02:48:02 +02001285
Nick Chalk57b1bf72010-03-16 15:50:46 +00001286 /* Reset the check buffer... */
Simon Horman4a741432013-02-23 15:35:38 +09001287 *check->bi->data = '\0';
1288 check->bi->i = 0;
Nick Chalk57b1bf72010-03-16 15:50:46 +00001289
Willy Tarreaufd29cc52012-11-23 09:18:20 +01001290 /* Close the connection... We absolutely want to perform a hard close
1291 * and reset the connection if some data are pending, otherwise we end
1292 * up with many TIME_WAITs and eat all the source port range quickly.
1293 * To avoid sending RSTs all the time, we first try to drain pending
1294 * data.
1295 */
Willy Tarreauf1503172012-09-28 19:39:36 +02001296 if (conn->xprt && conn->xprt->shutw)
1297 conn->xprt->shutw(conn, 0);
Willy Tarreau2b57cb82013-06-10 19:56:38 +02001298
Willy Tarreau25e2ab52013-12-04 11:17:05 +01001299 /* OK, let's not stay here forever */
Willy Tarreau6aaa1b82013-12-11 17:09:34 +01001300 if (check->result == CHK_RES_FAILED)
Willy Tarreau25e2ab52013-12-04 11:17:05 +01001301 conn->flags |= CO_FL_ERROR;
1302
Willy Tarreaua522f802012-11-23 08:56:35 +01001303 __conn_data_stop_both(conn);
Willy Tarreaufdccded2008-08-29 18:19:04 +02001304 task_wakeup(t, TASK_WOKEN_IO);
Willy Tarreau3267d362012-08-17 23:53:56 +02001305 return;
Willy Tarreau03938182010-03-17 21:52:07 +01001306
1307 wait_more_data:
Willy Tarreauf817e9f2014-01-10 16:58:45 +01001308 __conn_data_want_recv(conn);
Willy Tarreaubaaee002006-06-26 02:48:02 +02001309}
1310
Willy Tarreaufb56aab2012-09-28 14:40:02 +02001311/*
1312 * This function is used only for server health-checks. It handles connection
1313 * status updates including errors. If necessary, it wakes the check task up.
1314 * It always returns 0.
1315 */
1316static int wake_srv_chk(struct connection *conn)
Willy Tarreau20bea422012-07-06 12:00:49 +02001317{
Simon Horman4a741432013-02-23 15:35:38 +09001318 struct check *check = conn->owner;
Willy Tarreau20bea422012-07-06 12:00:49 +02001319
Willy Tarreau6c560da2012-11-24 11:14:45 +01001320 if (unlikely(conn->flags & CO_FL_ERROR)) {
Willy Tarreau02b0f582013-12-03 15:42:33 +01001321 /* We may get error reports bypassing the I/O handlers, typically
1322 * the case when sending a pure TCP check which fails, then the I/O
1323 * handlers above are not called. This is completely handled by the
Willy Tarreau25e2ab52013-12-04 11:17:05 +01001324 * main processing task so let's simply wake it up. If we get here,
1325 * we expect errno to still be valid.
1326 */
1327 chk_report_conn_err(conn, errno, 0);
1328
Willy Tarreau2d351b62013-12-05 02:36:25 +01001329 __conn_data_stop_both(conn);
1330 task_wakeup(check->task, TASK_WOKEN_IO);
1331 }
Willy Tarreau3be293f2014-02-05 18:31:24 +01001332 else if (!(conn->flags & (CO_FL_DATA_RD_ENA|CO_FL_DATA_WR_ENA|CO_FL_HANDSHAKE))) {
1333 /* we may get here if only a connection probe was required : we
1334 * don't have any data to send nor anything expected in response,
1335 * so the completion of the connection establishment is enough.
1336 */
1337 task_wakeup(check->task, TASK_WOKEN_IO);
1338 }
Willy Tarreau2d351b62013-12-05 02:36:25 +01001339
Willy Tarreau6aaa1b82013-12-11 17:09:34 +01001340 if (check->result != CHK_RES_UNKNOWN) {
Willy Tarreau25e2ab52013-12-04 11:17:05 +01001341 /* We're here because nobody wants to handle the error, so we
1342 * sure want to abort the hard way.
Willy Tarreau02b0f582013-12-03 15:42:33 +01001343 */
Willy Tarreau46be2e52014-01-20 12:10:52 +01001344 conn_drain(conn);
Willy Tarreauf79c8172013-10-21 16:30:56 +02001345 conn_force_close(conn);
Willy Tarreau2d351b62013-12-05 02:36:25 +01001346 }
Willy Tarreau3267d362012-08-17 23:53:56 +02001347 return 0;
Willy Tarreau20bea422012-07-06 12:00:49 +02001348}
1349
Willy Tarreaufb56aab2012-09-28 14:40:02 +02001350struct data_cb check_conn_cb = {
1351 .recv = event_srv_chk_r,
1352 .send = event_srv_chk_w,
1353 .wake = wake_srv_chk,
1354};
1355
Willy Tarreaubaaee002006-06-26 02:48:02 +02001356/*
Willy Tarreau2e993902011-10-31 11:53:20 +01001357 * updates the server's weight during a warmup stage. Once the final weight is
1358 * reached, the task automatically stops. Note that any server status change
1359 * must have updated s->last_change accordingly.
1360 */
1361static struct task *server_warmup(struct task *t)
1362{
1363 struct server *s = t->context;
1364
1365 /* by default, plan on stopping the task */
1366 t->expire = TICK_ETERNITY;
Willy Tarreau20125212014-05-13 19:44:56 +02001367 if ((s->admin & SRV_ADMF_MAINT) ||
Willy Tarreau892337c2014-05-13 23:41:20 +02001368 (s->state != SRV_ST_STARTING))
Willy Tarreau2e993902011-10-31 11:53:20 +01001369 return t;
1370
Willy Tarreau892337c2014-05-13 23:41:20 +02001371 /* recalculate the weights and update the state */
Willy Tarreau004e0452013-11-21 11:22:01 +01001372 server_recalc_eweight(s);
Willy Tarreau2e993902011-10-31 11:53:20 +01001373
1374 /* probably that we can refill this server with a bit more connections */
Willy Tarreau4aac7db2014-05-16 11:48:10 +02001375 pendconn_grab_from_px(s);
Willy Tarreau2e993902011-10-31 11:53:20 +01001376
1377 /* get back there in 1 second or 1/20th of the slowstart interval,
1378 * whichever is greater, resulting in small 5% steps.
1379 */
Willy Tarreau892337c2014-05-13 23:41:20 +02001380 if (s->state == SRV_ST_STARTING)
Willy Tarreau2e993902011-10-31 11:53:20 +01001381 t->expire = tick_add(now_ms, MS_TO_TICKS(MAX(1000, s->slowstart / 20)));
1382 return t;
1383}
1384
1385/*
Simon Horman98637e52014-06-20 12:30:16 +09001386 * establish a server health-check that makes use of a connection.
Simon Hormanb00d17a2014-06-13 16:18:16 +09001387 *
1388 * It can return one of :
1389 * - SN_ERR_NONE if everything's OK and tcpcheck_main() was not called
1390 * - SN_ERR_UP if if everything's OK and tcpcheck_main() was called
1391 * - SN_ERR_SRVTO if there are no more servers
1392 * - SN_ERR_SRVCL if the connection was refused by the server
1393 * - SN_ERR_PRXCOND if the connection has been limited by the proxy (maxconn)
1394 * - SN_ERR_RESOURCE if a system resource is lacking (eg: fd limits, ports, ...)
1395 * - SN_ERR_INTERNAL for any other purely internal errors
1396 * Additionnally, in the case of SN_ERR_RESOURCE, an emergency log will be emitted.
1397 * Note that we try to prevent the network stack from sending the ACK during the
1398 * connect() when a pure TCP check is used (without PROXY protocol).
1399 */
Simon Horman98637e52014-06-20 12:30:16 +09001400static int connect_conn_chk(struct task *t)
Simon Hormanb00d17a2014-06-13 16:18:16 +09001401{
1402 struct check *check = t->context;
1403 struct server *s = check->server;
1404 struct connection *conn = check->conn;
1405 struct protocol *proto;
1406 int ret;
Willy Tarreauf3d34822014-12-08 12:11:28 +01001407 int quickack;
Simon Hormanb00d17a2014-06-13 16:18:16 +09001408
1409 /* tcpcheck send/expect initialisation */
1410 if (check->type == PR_O2_TCPCHK_CHK)
1411 check->current_step = NULL;
1412
1413 /* prepare the check buffer.
1414 * This should not be used if check is the secondary agent check
1415 * of a server as s->proxy->check_req will relate to the
1416 * configuration of the primary check. Similarly, tcp-check uses
1417 * its own strings.
1418 */
1419 if (check->type && check->type != PR_O2_TCPCHK_CHK && !(check->state & CHK_ST_AGENT)) {
1420 bo_putblk(check->bo, s->proxy->check_req, s->proxy->check_len);
1421
1422 /* we want to check if this host replies to HTTP or SSLv3 requests
1423 * so we'll send the request, and won't wake the checker up now.
1424 */
1425 if ((check->type) == PR_O2_SSL3_CHK) {
1426 /* SSL requires that we put Unix time in the request */
1427 int gmt_time = htonl(date.tv_sec);
1428 memcpy(check->bo->data + 11, &gmt_time, 4);
1429 }
1430 else if ((check->type) == PR_O2_HTTP_CHK) {
1431 if (s->proxy->options2 & PR_O2_CHK_SNDST)
1432 bo_putblk(check->bo, trash.str, httpchk_build_status_header(s, trash.str, trash.size));
Cyril Bonté32602d22015-01-30 00:07:07 +01001433 /* prevent HTTP keep-alive when "http-check expect" is used */
1434 if (s->proxy->options2 & PR_O2_EXP_TYPE)
1435 bo_putstr(check->bo, "Connection: close\r\n");
Simon Hormanb00d17a2014-06-13 16:18:16 +09001436 bo_putstr(check->bo, "\r\n");
1437 *check->bo->p = '\0'; /* to make gdb output easier to read */
1438 }
1439 }
1440
1441 /* prepare a new connection */
1442 conn_init(conn);
Simon Horman41f58762015-01-30 11:22:56 +09001443 conn_prepare(conn, check->proto, check->xprt);
Simon Hormanb00d17a2014-06-13 16:18:16 +09001444 conn_attach(conn, check, &check_conn_cb);
1445 conn->target = &s->obj_type;
1446
1447 /* no client address */
1448 clear_addr(&conn->addr.from);
1449
Simon Horman41f58762015-01-30 11:22:56 +09001450 if (is_addr(&check->addr)) {
Simon Hormanb00d17a2014-06-13 16:18:16 +09001451
1452 /* we'll connect to the check addr specified on the server */
Simon Horman41f58762015-01-30 11:22:56 +09001453 conn->addr.to = check->addr;
1454 proto = check->proto;
Simon Hormanb00d17a2014-06-13 16:18:16 +09001455 }
1456 else {
1457 /* we'll connect to the addr on the server */
1458 conn->addr.to = s->addr;
1459 proto = s->proto;
1460 }
1461
1462 if (check->port) {
1463 set_host_port(&conn->addr.to, check->port);
1464 }
1465
Willy Tarreauf3d34822014-12-08 12:11:28 +01001466 /* only plain tcp-check supports quick ACK */
1467 quickack = check->type == 0 || check->type == PR_O2_TCPCHK_CHK;
1468
Simon Hormane16c1b32015-01-30 11:22:57 +09001469 if (check->type == PR_O2_TCPCHK_CHK && !LIST_ISEMPTY(check->tcpcheck_rules)) {
1470 struct tcpcheck_rule *r = (struct tcpcheck_rule *) check->tcpcheck_rules->n;
Simon Hormanb00d17a2014-06-13 16:18:16 +09001471 /* if first step is a 'connect', then tcpcheck_main must run it */
1472 if (r->action == TCPCHK_ACT_CONNECT) {
1473 tcpcheck_main(conn);
1474 return SN_ERR_UP;
1475 }
Willy Tarreauf3d34822014-12-08 12:11:28 +01001476 if (r->action == TCPCHK_ACT_EXPECT)
1477 quickack = 0;
Simon Hormanb00d17a2014-06-13 16:18:16 +09001478 }
1479
1480 ret = SN_ERR_INTERNAL;
1481 if (proto->connect)
Willy Tarreauf3d34822014-12-08 12:11:28 +01001482 ret = proto->connect(conn, check->type, quickack ? 2 : 0);
Simon Hormanb00d17a2014-06-13 16:18:16 +09001483 conn->flags |= CO_FL_WAKE_DATA;
1484 if (s->check.send_proxy) {
1485 conn->send_proxy_ofs = 1;
1486 conn->flags |= CO_FL_SEND_PROXY;
1487 }
1488
1489 return ret;
1490}
1491
Simon Horman98637e52014-06-20 12:30:16 +09001492static struct list pid_list = LIST_HEAD_INIT(pid_list);
1493static struct pool_head *pool2_pid_list;
1494
1495void block_sigchld(void)
1496{
1497 sigset_t set;
1498 sigemptyset(&set);
1499 sigaddset(&set, SIGCHLD);
1500 assert(sigprocmask(SIG_SETMASK, &set, NULL) == 0);
1501}
1502
1503void unblock_sigchld(void)
1504{
1505 sigset_t set;
1506 sigemptyset(&set);
1507 assert(sigprocmask(SIG_SETMASK, &set, NULL) == 0);
1508}
1509
1510/* Call with SIGCHLD blocked */
1511static struct pid_list *pid_list_add(pid_t pid, struct task *t)
1512{
1513 struct pid_list *elem;
1514 struct check *check = t->context;
1515
1516 elem = pool_alloc2(pool2_pid_list);
1517 if (!elem)
1518 return NULL;
1519 elem->pid = pid;
1520 elem->t = t;
1521 elem->exited = 0;
1522 check->curpid = elem;
1523 LIST_INIT(&elem->list);
1524 LIST_ADD(&pid_list, &elem->list);
1525 return elem;
1526}
1527
1528/* Blocks blocks and then unblocks SIGCHLD */
1529static void pid_list_del(struct pid_list *elem)
1530{
1531 struct check *check;
1532
1533 if (!elem)
1534 return;
1535
1536 block_sigchld();
1537 LIST_DEL(&elem->list);
1538 unblock_sigchld();
1539 if (!elem->exited)
1540 kill(elem->pid, SIGTERM);
1541
1542 check = elem->t->context;
1543 check->curpid = NULL;
1544 pool_free2(pool2_pid_list, elem);
1545}
1546
1547/* Called from inside SIGCHLD handler, SIGCHLD is blocked */
1548static void pid_list_expire(pid_t pid, int status)
1549{
1550 struct pid_list *elem;
1551
1552 list_for_each_entry(elem, &pid_list, list) {
1553 if (elem->pid == pid) {
1554 elem->t->expire = now_ms;
1555 elem->status = status;
1556 elem->exited = 1;
Cyril Bonté9dbcfab2014-08-07 01:55:39 +02001557 task_wakeup(elem->t, TASK_WOKEN_IO);
Simon Horman98637e52014-06-20 12:30:16 +09001558 return;
1559 }
1560 }
1561}
1562
1563static void sigchld_handler(int signal)
1564{
1565 pid_t pid;
1566 int status;
1567 while ((pid = waitpid(0, &status, WNOHANG)) > 0)
1568 pid_list_expire(pid, status);
1569}
1570
1571static int init_pid_list(void) {
1572 struct sigaction action = {
1573 .sa_handler = sigchld_handler,
1574 .sa_flags = SA_NOCLDSTOP
1575 };
1576
1577 if (pool2_pid_list != NULL)
1578 /* Nothing to do */
1579 return 0;
1580
1581 if (sigaction(SIGCHLD, &action, NULL)) {
1582 Alert("Failed to set signal handler for external health checks: %s. Aborting.\n",
1583 strerror(errno));
1584 return 1;
1585 }
1586
1587 pool2_pid_list = create_pool("pid_list", sizeof(struct pid_list), MEM_F_SHARED);
1588 if (pool2_pid_list == NULL) {
1589 Alert("Failed to allocate memory pool for external health checks: %s. Aborting.\n",
1590 strerror(errno));
1591 return 1;
1592 }
1593
1594 return 0;
1595}
1596
Cyril Bontéac92a062014-12-27 22:28:38 +01001597/* helper macro to set an environment variable and jump to a specific label on failure. */
1598#define EXTCHK_SETENV(check, envidx, value, fail) { if (extchk_setenv(check, envidx, value)) goto fail; }
Cyril Bonté9ede66b2014-12-02 21:21:36 +01001599
1600/*
Cyril Bontéac92a062014-12-27 22:28:38 +01001601 * helper function to allocate enough memory to store an environment variable.
1602 * It will also check that the environment variable is updatable, and silently
1603 * fail if not.
Cyril Bonté9ede66b2014-12-02 21:21:36 +01001604 */
Cyril Bontéac92a062014-12-27 22:28:38 +01001605static int extchk_setenv(struct check *check, int idx, const char *value)
Cyril Bonté9ede66b2014-12-02 21:21:36 +01001606{
1607 int len, ret;
Cyril Bontéac92a062014-12-27 22:28:38 +01001608 char *envname;
1609 int vmaxlen;
Cyril Bonté9ede66b2014-12-02 21:21:36 +01001610
Cyril Bontéac92a062014-12-27 22:28:38 +01001611 if (idx < 0 || idx >= EXTCHK_SIZE) {
1612 Alert("Illegal environment variable index %d. Aborting.\n", idx);
1613 return 1;
Cyril Bonté9ede66b2014-12-02 21:21:36 +01001614 }
Cyril Bontéac92a062014-12-27 22:28:38 +01001615
1616 envname = extcheck_envs[idx].name;
1617 vmaxlen = extcheck_envs[idx].vmaxlen;
1618
1619 /* Check if the environment variable is already set, and silently reject
1620 * the update if this one is not updatable. */
1621 if ((vmaxlen == EXTCHK_SIZE_EVAL_INIT) && (check->envp[idx]))
1622 return 0;
1623
Cyril Bonté9ede66b2014-12-02 21:21:36 +01001624 /* Instead of sending NOT_USED, sending an empty value is preferable */
1625 if (strcmp(value, "NOT_USED") == 0) {
1626 value = "";
1627 }
Cyril Bontéac92a062014-12-27 22:28:38 +01001628
1629 len = strlen(envname) + 1;
1630 if (vmaxlen == EXTCHK_SIZE_EVAL_INIT)
1631 len += strlen(value);
1632 else
1633 len += vmaxlen;
1634
1635 if (!check->envp[idx])
1636 check->envp[idx] = malloc(len + 1);
1637
1638 if (!check->envp[idx]) {
Cyril Bonté9ede66b2014-12-02 21:21:36 +01001639 Alert("Failed to allocate memory for the environment variable '%s'. Aborting.\n", envname);
1640 return 1;
1641 }
Cyril Bontéac92a062014-12-27 22:28:38 +01001642 ret = snprintf(check->envp[idx], len + 1, "%s=%s", envname, value);
Cyril Bonté9ede66b2014-12-02 21:21:36 +01001643 if (ret < 0) {
1644 Alert("Failed to store the environment variable '%s'. Reason : %s. Aborting.\n", envname, strerror(errno));
1645 return 1;
1646 }
Cyril Bontéac92a062014-12-27 22:28:38 +01001647 else if (ret > len) {
Cyril Bonté9ede66b2014-12-02 21:21:36 +01001648 Alert("Environment variable '%s' was truncated. Aborting.\n", envname);
1649 return 1;
1650 }
Cyril Bonté9ede66b2014-12-02 21:21:36 +01001651 return 0;
1652}
Simon Horman98637e52014-06-20 12:30:16 +09001653
1654static int prepare_external_check(struct check *check)
1655{
1656 struct server *s = check->server;
1657 struct proxy *px = s->proxy;
1658 struct listener *listener = NULL, *l;
1659 int i;
Simon Horman98637e52014-06-20 12:30:16 +09001660 const char *path = px->check_path ? px->check_path : DEF_CHECK_PATH;
Cyril Bonté9ede66b2014-12-02 21:21:36 +01001661 char buf[256];
Simon Horman98637e52014-06-20 12:30:16 +09001662
1663 list_for_each_entry(l, &px->conf.listeners, by_fe)
1664 /* Use the first INET, INET6 or UNIX listener */
1665 if (l->addr.ss_family == AF_INET ||
1666 l->addr.ss_family == AF_INET6 ||
1667 l->addr.ss_family == AF_UNIX) {
1668 listener = l;
1669 break;
1670 }
1671
Simon Horman98637e52014-06-20 12:30:16 +09001672 check->curpid = NULL;
Cyril Bontéac92a062014-12-27 22:28:38 +01001673 check->envp = calloc((EXTCHK_SIZE + 1), sizeof(char *));
1674 if (!check->envp) {
1675 Alert("Failed to allocate memory for environment variables. Aborting\n");
1676 goto err;
1677 }
Simon Horman98637e52014-06-20 12:30:16 +09001678
Cyril Bontéac92a062014-12-27 22:28:38 +01001679 check->argv = calloc(6, sizeof(char *));
1680 if (!check->argv) {
1681 Alert("Starting [%s:%s] check: out of memory.\n", px->id, s->id);
Simon Horman98637e52014-06-20 12:30:16 +09001682 goto err;
Cyril Bontéac92a062014-12-27 22:28:38 +01001683 }
Simon Horman98637e52014-06-20 12:30:16 +09001684
1685 check->argv[0] = px->check_command;
1686
Cyril Bonté777be862014-12-02 21:21:35 +01001687 if (!listener) {
1688 check->argv[1] = strdup("NOT_USED");
1689 check->argv[2] = strdup("NOT_USED");
1690 }
1691 else if (listener->addr.ss_family == AF_INET ||
Simon Horman98637e52014-06-20 12:30:16 +09001692 listener->addr.ss_family == AF_INET6) {
Cyril Bonté9ede66b2014-12-02 21:21:36 +01001693 addr_to_str(&listener->addr, buf, sizeof(buf));
1694 check->argv[1] = strdup(buf);
1695 port_to_str(&listener->addr, buf, sizeof(buf));
1696 check->argv[2] = strdup(buf);
Cyril Bonté777be862014-12-02 21:21:35 +01001697 }
1698 else if (listener->addr.ss_family == AF_UNIX) {
Simon Horman98637e52014-06-20 12:30:16 +09001699 const struct sockaddr_un *un;
1700
1701 un = (struct sockaddr_un *)&listener->addr;
1702 check->argv[1] = strdup(un->sun_path);
1703 check->argv[2] = strdup("NOT_USED");
Cyril Bonté777be862014-12-02 21:21:35 +01001704 }
1705 else {
Cyril Bontéac92a062014-12-27 22:28:38 +01001706 Alert("Starting [%s:%s] check: unsupported address family.\n", px->id, s->id);
Simon Horman98637e52014-06-20 12:30:16 +09001707 goto err;
1708 }
1709
Cyril Bonté9ede66b2014-12-02 21:21:36 +01001710 addr_to_str(&s->addr, buf, sizeof(buf));
1711 check->argv[3] = strdup(buf);
1712 port_to_str(&s->addr, buf, sizeof(buf));
1713 check->argv[4] = strdup(buf);
Simon Horman98637e52014-06-20 12:30:16 +09001714
Cyril Bontéac92a062014-12-27 22:28:38 +01001715 for (i = 0; i < 5; i++) {
1716 if (!check->argv[i]) {
1717 Alert("Starting [%s:%s] check: out of memory.\n", px->id, s->id);
Simon Horman98637e52014-06-20 12:30:16 +09001718 goto err;
Cyril Bontéac92a062014-12-27 22:28:38 +01001719 }
1720 }
Simon Horman98637e52014-06-20 12:30:16 +09001721
Cyril Bontéac92a062014-12-27 22:28:38 +01001722 EXTCHK_SETENV(check, EXTCHK_PATH, path, err);
Cyril Bonté9ede66b2014-12-02 21:21:36 +01001723 /* Add proxy environment variables */
Cyril Bontéac92a062014-12-27 22:28:38 +01001724 EXTCHK_SETENV(check, EXTCHK_HAPROXY_PROXY_NAME, px->id, err);
1725 EXTCHK_SETENV(check, EXTCHK_HAPROXY_PROXY_ID, ultoa_r(px->uuid, buf, sizeof(buf)), err);
1726 EXTCHK_SETENV(check, EXTCHK_HAPROXY_PROXY_ADDR, check->argv[1], err);
1727 EXTCHK_SETENV(check, EXTCHK_HAPROXY_PROXY_PORT, check->argv[2], err);
Cyril Bonté9ede66b2014-12-02 21:21:36 +01001728 /* Add server environment variables */
Cyril Bontéac92a062014-12-27 22:28:38 +01001729 EXTCHK_SETENV(check, EXTCHK_HAPROXY_SERVER_NAME, s->id, err);
1730 EXTCHK_SETENV(check, EXTCHK_HAPROXY_SERVER_ID, ultoa_r(s->puid, buf, sizeof(buf)), err);
1731 EXTCHK_SETENV(check, EXTCHK_HAPROXY_SERVER_ADDR, check->argv[3], err);
1732 EXTCHK_SETENV(check, EXTCHK_HAPROXY_SERVER_PORT, check->argv[4], err);
1733 EXTCHK_SETENV(check, EXTCHK_HAPROXY_SERVER_MAXCONN, ultoa_r(s->maxconn, buf, sizeof(buf)), err);
1734 EXTCHK_SETENV(check, EXTCHK_HAPROXY_SERVER_CURCONN, ultoa_r(s->cur_sess, buf, sizeof(buf)), err);
1735
1736 /* Ensure that we don't leave any hole in check->envp */
1737 for (i = 0; i < EXTCHK_SIZE; i++)
1738 if (!check->envp[i])
1739 EXTCHK_SETENV(check, i, "", err);
Cyril Bonté9ede66b2014-12-02 21:21:36 +01001740
Cyril Bonté99c5bf52014-08-07 01:55:38 +02001741 return 1;
Simon Horman98637e52014-06-20 12:30:16 +09001742err:
1743 if (check->envp) {
Cyril Bontéac92a062014-12-27 22:28:38 +01001744 for (i = 0; i < EXTCHK_SIZE; i++)
Cyril Bonté9ede66b2014-12-02 21:21:36 +01001745 free(check->envp[i]);
Simon Horman98637e52014-06-20 12:30:16 +09001746 free(check->envp);
1747 check->envp = NULL;
1748 }
1749
1750 if (check->argv) {
1751 for (i = 1; i < 5; i++)
1752 free(check->argv[i]);
1753 free(check->argv);
1754 check->argv = NULL;
1755 }
Cyril Bonté99c5bf52014-08-07 01:55:38 +02001756 return 0;
Simon Horman98637e52014-06-20 12:30:16 +09001757}
1758
Simon Hormanb00d17a2014-06-13 16:18:16 +09001759/*
Simon Horman98637e52014-06-20 12:30:16 +09001760 * establish a server health-check that makes use of a process.
1761 *
1762 * It can return one of :
1763 * - SN_ERR_NONE if everything's OK
1764 * - SN_ERR_SRVTO if there are no more servers
1765 * - SN_ERR_SRVCL if the connection was refused by the server
1766 * - SN_ERR_PRXCOND if the connection has been limited by the proxy (maxconn)
1767 * - SN_ERR_RESOURCE if a system resource is lacking (eg: fd limits, ports, ...)
1768 * - SN_ERR_INTERNAL for any other purely internal errors
1769 * Additionnally, in the case of SN_ERR_RESOURCE, an emergency log will be emitted.
1770 *
1771 * Blocks and then unblocks SIGCHLD
1772 */
1773static int connect_proc_chk(struct task *t)
1774{
Cyril Bontéac92a062014-12-27 22:28:38 +01001775 char buf[256];
Simon Horman98637e52014-06-20 12:30:16 +09001776 struct check *check = t->context;
1777 struct server *s = check->server;
1778 struct proxy *px = s->proxy;
1779 int status;
1780 pid_t pid;
1781
Simon Horman98637e52014-06-20 12:30:16 +09001782 status = SN_ERR_RESOURCE;
1783
1784 block_sigchld();
1785
1786 pid = fork();
1787 if (pid < 0) {
1788 Alert("Failed to fork process for external health check: %s. Aborting.\n",
1789 strerror(errno));
1790 set_server_check_status(check, HCHK_STATUS_SOCKERR, strerror(errno));
1791 goto out;
1792 }
1793 if (pid == 0) {
1794 /* Child */
1795 extern char **environ;
1796 environ = check->envp;
Cyril Bontéac92a062014-12-27 22:28:38 +01001797 extchk_setenv(check, EXTCHK_HAPROXY_SERVER_CURCONN, ultoa_r(s->cur_sess, buf, sizeof(buf)));
Simon Horman98637e52014-06-20 12:30:16 +09001798 execvp(px->check_command, check->argv);
1799 Alert("Failed to exec process for external health check: %s. Aborting.\n",
1800 strerror(errno));
1801 exit(-1);
1802 }
1803
1804 /* Parent */
1805 if (check->result == CHK_RES_UNKNOWN) {
1806 if (pid_list_add(pid, t) != NULL) {
1807 t->expire = tick_add(now_ms, MS_TO_TICKS(check->inter));
1808
1809 if (px->timeout.check && px->timeout.connect) {
1810 int t_con = tick_add(now_ms, px->timeout.connect);
1811 t->expire = tick_first(t->expire, t_con);
1812 }
1813 status = SN_ERR_NONE;
1814 goto out;
1815 }
1816 else {
1817 set_server_check_status(check, HCHK_STATUS_SOCKERR, strerror(errno));
1818 }
1819 kill(pid, SIGTERM); /* process creation error */
1820 }
1821 else
1822 set_server_check_status(check, HCHK_STATUS_SOCKERR, strerror(errno));
1823
1824out:
1825 unblock_sigchld();
1826 return status;
1827}
1828
1829/*
Simon Horman98637e52014-06-20 12:30:16 +09001830 * manages a server health-check that uses a process. Returns
Willy Tarreaubaaee002006-06-26 02:48:02 +02001831 * the time the task accepts to wait, or TIME_ETERNITY for infinity.
1832 */
Simon Horman98637e52014-06-20 12:30:16 +09001833static struct task *process_chk_proc(struct task *t)
1834{
1835 struct check *check = t->context;
1836 struct server *s = check->server;
1837 struct connection *conn = check->conn;
1838 int rv;
1839 int ret;
1840 int expired = tick_is_expired(t->expire, now_ms);
1841
1842 if (!(check->state & CHK_ST_INPROGRESS)) {
1843 /* no check currently running */
1844 if (!expired) /* woke up too early */
1845 return t;
1846
1847 /* we don't send any health-checks when the proxy is
1848 * stopped, the server should not be checked or the check
1849 * is disabled.
1850 */
1851 if (((check->state & (CHK_ST_ENABLED | CHK_ST_PAUSED)) != CHK_ST_ENABLED) ||
1852 s->proxy->state == PR_STSTOPPED)
1853 goto reschedule;
1854
1855 /* we'll initiate a new check */
1856 set_server_check_status(check, HCHK_STATUS_START, NULL);
1857
1858 check->state |= CHK_ST_INPROGRESS;
1859
Simon Hormandbf70192015-01-30 11:22:53 +09001860 ret = connect_proc_chk(t);
Simon Horman98637e52014-06-20 12:30:16 +09001861 switch (ret) {
1862 case SN_ERR_UP:
1863 return t;
1864 case SN_ERR_NONE:
1865 /* we allow up to min(inter, timeout.connect) for a connection
1866 * to establish but only when timeout.check is set
1867 * as it may be to short for a full check otherwise
1868 */
1869 t->expire = tick_add(now_ms, MS_TO_TICKS(check->inter));
1870
1871 if (s->proxy->timeout.check && s->proxy->timeout.connect) {
1872 int t_con = tick_add(now_ms, s->proxy->timeout.connect);
1873 t->expire = tick_first(t->expire, t_con);
1874 }
1875
1876 goto reschedule;
1877
1878 case SN_ERR_SRVTO: /* ETIMEDOUT */
1879 case SN_ERR_SRVCL: /* ECONNREFUSED, ENETUNREACH, ... */
1880 conn->flags |= CO_FL_ERROR;
1881 chk_report_conn_err(conn, errno, 0);
1882 break;
1883 case SN_ERR_PRXCOND:
1884 case SN_ERR_RESOURCE:
1885 case SN_ERR_INTERNAL:
1886 conn->flags |= CO_FL_ERROR;
1887 chk_report_conn_err(conn, 0, 0);
1888 break;
1889 }
1890
1891 /* here, we have seen a synchronous error, no fd was allocated */
1892
1893 check->state &= ~CHK_ST_INPROGRESS;
1894 check_notify_failure(check);
1895
1896 /* we allow up to min(inter, timeout.connect) for a connection
1897 * to establish but only when timeout.check is set
1898 * as it may be to short for a full check otherwise
1899 */
1900 while (tick_is_expired(t->expire, now_ms)) {
1901 int t_con;
1902
1903 t_con = tick_add(t->expire, s->proxy->timeout.connect);
1904 t->expire = tick_add(t->expire, MS_TO_TICKS(check->inter));
1905
1906 if (s->proxy->timeout.check)
1907 t->expire = tick_first(t->expire, t_con);
1908 }
1909 }
1910 else {
1911 /* there was a test running.
1912 * First, let's check whether there was an uncaught error,
1913 * which can happen on connect timeout or error.
1914 */
1915 if (check->result == CHK_RES_UNKNOWN) {
1916 /* good connection is enough for pure TCP check */
1917 struct pid_list *elem = check->curpid;
1918 int status = HCHK_STATUS_UNKNOWN;
1919
1920 if (elem->exited) {
1921 status = elem->status; /* Save in case the process exits between use below */
1922 if (!WIFEXITED(status))
1923 check->code = -1;
1924 else
1925 check->code = WEXITSTATUS(status);
1926 if (!WIFEXITED(status) || WEXITSTATUS(status))
1927 status = HCHK_STATUS_PROCERR;
1928 else
1929 status = HCHK_STATUS_PROCOK;
1930 } else if (expired) {
1931 status = HCHK_STATUS_PROCTOUT;
Willy Tarreaudc3d1902014-07-08 00:56:27 +02001932 Warning("kill %d\n", (int)elem->pid);
Simon Horman98637e52014-06-20 12:30:16 +09001933 kill(elem->pid, SIGTERM);
1934 }
1935 set_server_check_status(check, status, NULL);
1936 }
1937
1938 if (check->result == CHK_RES_FAILED) {
1939 /* a failure or timeout detected */
1940 check_notify_failure(check);
1941 }
1942 else if (check->result == CHK_RES_CONDPASS) {
1943 /* check is OK but asks for stopping mode */
1944 check_notify_stopping(check);
1945 }
1946 else if (check->result == CHK_RES_PASSED) {
1947 /* a success was detected */
1948 check_notify_success(check);
1949 }
1950 check->state &= ~CHK_ST_INPROGRESS;
1951
1952 pid_list_del(check->curpid);
1953
1954 rv = 0;
1955 if (global.spread_checks > 0) {
1956 rv = srv_getinter(check) * global.spread_checks / 100;
1957 rv -= (int) (2 * rv * (rand() / (RAND_MAX + 1.0)));
1958 }
1959 t->expire = tick_add(now_ms, MS_TO_TICKS(srv_getinter(check) + rv));
1960 }
1961
1962 reschedule:
1963 while (tick_is_expired(t->expire, now_ms))
1964 t->expire = tick_add(t->expire, MS_TO_TICKS(check->inter));
1965 return t;
1966}
1967
1968/*
1969 * manages a server health-check that uses a connection. Returns
1970 * the time the task accepts to wait, or TIME_ETERNITY for infinity.
1971 */
1972static struct task *process_chk_conn(struct task *t)
Willy Tarreaubaaee002006-06-26 02:48:02 +02001973{
Simon Horman4a741432013-02-23 15:35:38 +09001974 struct check *check = t->context;
1975 struct server *s = check->server;
1976 struct connection *conn = check->conn;
Krzysztof Oledzkib304dc72007-10-14 23:40:01 +02001977 int rv;
Willy Tarreaufb56aab2012-09-28 14:40:02 +02001978 int ret;
Willy Tarreauacbdc7a2012-11-23 14:02:10 +01001979 int expired = tick_is_expired(t->expire, now_ms);
Willy Tarreaubaaee002006-06-26 02:48:02 +02001980
Willy Tarreau2c115e52013-12-11 19:41:16 +01001981 if (!(check->state & CHK_ST_INPROGRESS)) {
Willy Tarreau5a78f362012-11-23 12:47:05 +01001982 /* no check currently running */
Willy Tarreauacbdc7a2012-11-23 14:02:10 +01001983 if (!expired) /* woke up too early */
Willy Tarreau26c25062009-03-08 09:38:41 +01001984 return t;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001985
Simon Horman671b6f02013-11-25 10:46:39 +09001986 /* we don't send any health-checks when the proxy is
1987 * stopped, the server should not be checked or the check
1988 * is disabled.
Willy Tarreaubaaee002006-06-26 02:48:02 +02001989 */
Willy Tarreau0d924cc2013-12-11 21:26:24 +01001990 if (((check->state & (CHK_ST_ENABLED | CHK_ST_PAUSED)) != CHK_ST_ENABLED) ||
Willy Tarreau33a08db2013-12-11 21:03:31 +01001991 s->proxy->state == PR_STSTOPPED)
Willy Tarreau5a78f362012-11-23 12:47:05 +01001992 goto reschedule;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001993
1994 /* we'll initiate a new check */
Simon Horman4a741432013-02-23 15:35:38 +09001995 set_server_check_status(check, HCHK_STATUS_START, NULL);
Willy Tarreau1ae1b7b2012-09-28 15:28:30 +02001996
Willy Tarreau2c115e52013-12-11 19:41:16 +01001997 check->state |= CHK_ST_INPROGRESS;
Simon Horman4a741432013-02-23 15:35:38 +09001998 check->bi->p = check->bi->data;
1999 check->bi->i = 0;
2000 check->bo->p = check->bo->data;
2001 check->bo->o = 0;
Willy Tarreau1ae1b7b2012-09-28 15:28:30 +02002002
Simon Hormandbf70192015-01-30 11:22:53 +09002003 ret = connect_conn_chk(t);
Willy Tarreaufb56aab2012-09-28 14:40:02 +02002004 switch (ret) {
Simon Hormanb00d17a2014-06-13 16:18:16 +09002005 case SN_ERR_UP:
2006 return t;
Willy Tarreaufb56aab2012-09-28 14:40:02 +02002007 case SN_ERR_NONE:
Willy Tarreaufb56aab2012-09-28 14:40:02 +02002008 /* we allow up to min(inter, timeout.connect) for a connection
2009 * to establish but only when timeout.check is set
2010 * as it may be to short for a full check otherwise
2011 */
Simon Horman4a741432013-02-23 15:35:38 +09002012 t->expire = tick_add(now_ms, MS_TO_TICKS(check->inter));
Krzysztof Piotr Oledzki09605412009-09-23 22:09:24 +02002013
Willy Tarreaufb56aab2012-09-28 14:40:02 +02002014 if (s->proxy->timeout.check && s->proxy->timeout.connect) {
2015 int t_con = tick_add(now_ms, s->proxy->timeout.connect);
2016 t->expire = tick_first(t->expire, t_con);
Willy Tarreaubaaee002006-06-26 02:48:02 +02002017 }
Willy Tarreau06559ac2013-12-05 01:53:08 +01002018
2019 if (check->type)
2020 conn_data_want_recv(conn); /* prepare for reading a possible reply */
2021
Willy Tarreau5a78f362012-11-23 12:47:05 +01002022 goto reschedule;
2023
2024 case SN_ERR_SRVTO: /* ETIMEDOUT */
2025 case SN_ERR_SRVCL: /* ECONNREFUSED, ENETUNREACH, ... */
Willy Tarreau4bd07de2014-01-24 16:10:57 +01002026 conn->flags |= CO_FL_ERROR;
2027 chk_report_conn_err(conn, errno, 0);
Willy Tarreau5a78f362012-11-23 12:47:05 +01002028 break;
2029 case SN_ERR_PRXCOND:
2030 case SN_ERR_RESOURCE:
2031 case SN_ERR_INTERNAL:
Willy Tarreau4bd07de2014-01-24 16:10:57 +01002032 conn->flags |= CO_FL_ERROR;
2033 chk_report_conn_err(conn, 0, 0);
Willy Tarreau5a78f362012-11-23 12:47:05 +01002034 break;
Willy Tarreaubaaee002006-06-26 02:48:02 +02002035 }
2036
Willy Tarreau5a78f362012-11-23 12:47:05 +01002037 /* here, we have seen a synchronous error, no fd was allocated */
Willy Tarreau6b0a8502012-11-23 08:51:32 +01002038
Willy Tarreau2c115e52013-12-11 19:41:16 +01002039 check->state &= ~CHK_ST_INPROGRESS;
Willy Tarreau4eec5472014-05-20 22:32:27 +02002040 check_notify_failure(check);
Willy Tarreaubaaee002006-06-26 02:48:02 +02002041
Krzysztof Piotr Oledzki5259dfe2008-01-21 01:54:06 +01002042 /* we allow up to min(inter, timeout.connect) for a connection
2043 * to establish but only when timeout.check is set
2044 * as it may be to short for a full check otherwise
2045 */
Willy Tarreau0c303ee2008-07-07 00:09:58 +02002046 while (tick_is_expired(t->expire, now_ms)) {
2047 int t_con;
Krzysztof Piotr Oledzki5259dfe2008-01-21 01:54:06 +01002048
Willy Tarreau0c303ee2008-07-07 00:09:58 +02002049 t_con = tick_add(t->expire, s->proxy->timeout.connect);
Simon Horman4a741432013-02-23 15:35:38 +09002050 t->expire = tick_add(t->expire, MS_TO_TICKS(check->inter));
Krzysztof Piotr Oledzki5259dfe2008-01-21 01:54:06 +01002051
Willy Tarreau0c303ee2008-07-07 00:09:58 +02002052 if (s->proxy->timeout.check)
2053 t->expire = tick_first(t->expire, t_con);
Krzysztof Piotr Oledzki5259dfe2008-01-21 01:54:06 +01002054 }
Willy Tarreaubaaee002006-06-26 02:48:02 +02002055 }
2056 else {
Willy Tarreauf1503172012-09-28 19:39:36 +02002057 /* there was a test running.
2058 * First, let's check whether there was an uncaught error,
2059 * which can happen on connect timeout or error.
2060 */
Simon Hormanccaabcd2014-06-20 12:29:47 +09002061 if (check->result == CHK_RES_UNKNOWN) {
Willy Tarreau25e2ab52013-12-04 11:17:05 +01002062 /* good connection is enough for pure TCP check */
2063 if ((conn->flags & CO_FL_CONNECTED) && !check->type) {
Simon Horman4a741432013-02-23 15:35:38 +09002064 if (check->use_ssl)
2065 set_server_check_status(check, HCHK_STATUS_L6OK, NULL);
Willy Tarreauf1503172012-09-28 19:39:36 +02002066 else
Simon Horman4a741432013-02-23 15:35:38 +09002067 set_server_check_status(check, HCHK_STATUS_L4OK, NULL);
Willy Tarreauacbdc7a2012-11-23 14:02:10 +01002068 }
Willy Tarreau25e2ab52013-12-04 11:17:05 +01002069 else if ((conn->flags & CO_FL_ERROR) || expired) {
2070 chk_report_conn_err(conn, 0, expired);
Willy Tarreauf1503172012-09-28 19:39:36 +02002071 }
Willy Tarreau74fa7fb2012-11-23 14:43:49 +01002072 else
2073 goto out_wait; /* timeout not reached, wait again */
Willy Tarreauf1503172012-09-28 19:39:36 +02002074 }
2075
Willy Tarreau74fa7fb2012-11-23 14:43:49 +01002076 /* check complete or aborted */
Willy Tarreau5ba04f62013-02-12 15:23:12 +01002077 if (conn->xprt) {
2078 /* The check was aborted and the connection was not yet closed.
2079 * This can happen upon timeout, or when an external event such
2080 * as a failed response coupled with "observe layer7" caused the
2081 * server state to be suddenly changed.
2082 */
Willy Tarreau46be2e52014-01-20 12:10:52 +01002083 conn_drain(conn);
Willy Tarreauf79c8172013-10-21 16:30:56 +02002084 conn_force_close(conn);
Willy Tarreau5ba04f62013-02-12 15:23:12 +01002085 }
2086
Willy Tarreauaf549582014-05-16 17:37:50 +02002087 if (check->result == CHK_RES_FAILED) {
2088 /* a failure or timeout detected */
Willy Tarreau4eec5472014-05-20 22:32:27 +02002089 check_notify_failure(check);
Willy Tarreauaf549582014-05-16 17:37:50 +02002090 }
Willy Tarreaudb58b792014-05-21 13:57:23 +02002091 else if (check->result == CHK_RES_CONDPASS) {
2092 /* check is OK but asks for stopping mode */
2093 check_notify_stopping(check);
Willy Tarreauaf549582014-05-16 17:37:50 +02002094 }
Willy Tarreau3e048382014-05-21 10:30:54 +02002095 else if (check->result == CHK_RES_PASSED) {
2096 /* a success was detected */
2097 check_notify_success(check);
Willy Tarreaubaaee002006-06-26 02:48:02 +02002098 }
Willy Tarreau2c115e52013-12-11 19:41:16 +01002099 check->state &= ~CHK_ST_INPROGRESS;
Krzysztof Oledzkib304dc72007-10-14 23:40:01 +02002100
Willy Tarreau74fa7fb2012-11-23 14:43:49 +01002101 rv = 0;
2102 if (global.spread_checks > 0) {
Simon Horman4a741432013-02-23 15:35:38 +09002103 rv = srv_getinter(check) * global.spread_checks / 100;
Willy Tarreau74fa7fb2012-11-23 14:43:49 +01002104 rv -= (int) (2 * rv * (rand() / (RAND_MAX + 1.0)));
Willy Tarreaubaaee002006-06-26 02:48:02 +02002105 }
Simon Horman4a741432013-02-23 15:35:38 +09002106 t->expire = tick_add(now_ms, MS_TO_TICKS(srv_getinter(check) + rv));
Willy Tarreaubaaee002006-06-26 02:48:02 +02002107 }
Willy Tarreau5a78f362012-11-23 12:47:05 +01002108
2109 reschedule:
2110 while (tick_is_expired(t->expire, now_ms))
Simon Horman4a741432013-02-23 15:35:38 +09002111 t->expire = tick_add(t->expire, MS_TO_TICKS(check->inter));
Willy Tarreau74fa7fb2012-11-23 14:43:49 +01002112 out_wait:
Willy Tarreau26c25062009-03-08 09:38:41 +01002113 return t;
Willy Tarreaubaaee002006-06-26 02:48:02 +02002114}
2115
Simon Horman98637e52014-06-20 12:30:16 +09002116/*
2117 * manages a server health-check. Returns
2118 * the time the task accepts to wait, or TIME_ETERNITY for infinity.
2119 */
2120static struct task *process_chk(struct task *t)
2121{
2122 struct check *check = t->context;
2123
2124 if (check->type == PR_O2_EXT_CHK)
2125 return process_chk_proc(t);
2126 return process_chk_conn(t);
2127}
2128
Simon Horman5c942422013-11-25 10:46:32 +09002129static int start_check_task(struct check *check, int mininter,
2130 int nbcheck, int srvpos)
2131{
2132 struct task *t;
2133 /* task for the check */
2134 if ((t = task_new()) == NULL) {
2135 Alert("Starting [%s:%s] check: out of memory.\n",
2136 check->server->proxy->id, check->server->id);
2137 return 0;
2138 }
2139
2140 check->task = t;
2141 t->process = process_chk;
2142 t->context = check;
2143
Willy Tarreau1746eec2014-04-25 10:46:47 +02002144 if (mininter < srv_getinter(check))
2145 mininter = srv_getinter(check);
2146
2147 if (global.max_spread_checks && mininter > global.max_spread_checks)
2148 mininter = global.max_spread_checks;
2149
Simon Horman5c942422013-11-25 10:46:32 +09002150 /* check this every ms */
Willy Tarreau1746eec2014-04-25 10:46:47 +02002151 t->expire = tick_add(now_ms, MS_TO_TICKS(mininter * srvpos / nbcheck));
Simon Horman5c942422013-11-25 10:46:32 +09002152 check->start = now;
2153 task_queue(t);
2154
2155 return 1;
2156}
2157
Krzysztof Oledzkib304dc72007-10-14 23:40:01 +02002158/*
2159 * Start health-check.
2160 * Returns 0 if OK, -1 if error, and prints the error in this case.
2161 */
2162int start_checks() {
2163
2164 struct proxy *px;
2165 struct server *s;
2166 struct task *t;
Simon Horman4a741432013-02-23 15:35:38 +09002167 int nbcheck=0, mininter=0, srvpos=0;
Krzysztof Oledzkib304dc72007-10-14 23:40:01 +02002168
Willy Tarreau2c43a1e2007-10-14 23:05:39 +02002169 /* 1- count the checkers to run simultaneously.
2170 * We also determine the minimum interval among all of those which
2171 * have an interval larger than SRV_CHK_INTER_THRES. This interval
2172 * will be used to spread their start-up date. Those which have
Jamie Gloudon801a0a32012-08-25 00:18:33 -04002173 * a shorter interval will start independently and will not dictate
Willy Tarreau2c43a1e2007-10-14 23:05:39 +02002174 * too short an interval for all others.
2175 */
Krzysztof Oledzkib304dc72007-10-14 23:40:01 +02002176 for (px = proxy; px; px = px->next) {
2177 for (s = px->srv; s; s = s->next) {
Willy Tarreaue7b73482013-11-21 11:50:50 +01002178 if (s->slowstart) {
2179 if ((t = task_new()) == NULL) {
2180 Alert("Starting [%s:%s] check: out of memory.\n", px->id, s->id);
2181 return -1;
2182 }
2183 /* We need a warmup task that will be called when the server
2184 * state switches from down to up.
2185 */
2186 s->warmup = t;
2187 t->process = server_warmup;
2188 t->context = s;
2189 t->expire = TICK_ETERNITY;
2190 }
2191
Willy Tarreaud8514a22013-12-11 21:10:14 +01002192 if (s->check.state & CHK_ST_CONFIGURED) {
2193 nbcheck++;
2194 if ((srv_getinter(&s->check) >= SRV_CHK_INTER_THRES) &&
2195 (!mininter || mininter > srv_getinter(&s->check)))
2196 mininter = srv_getinter(&s->check);
2197 }
Willy Tarreau15f39102013-12-11 20:41:18 +01002198
Willy Tarreaud8514a22013-12-11 21:10:14 +01002199 if (s->agent.state & CHK_ST_CONFIGURED) {
2200 nbcheck++;
2201 if ((srv_getinter(&s->agent) >= SRV_CHK_INTER_THRES) &&
2202 (!mininter || mininter > srv_getinter(&s->agent)))
2203 mininter = srv_getinter(&s->agent);
2204 }
Krzysztof Oledzkib304dc72007-10-14 23:40:01 +02002205 }
2206 }
2207
Simon Horman4a741432013-02-23 15:35:38 +09002208 if (!nbcheck)
Krzysztof Oledzkib304dc72007-10-14 23:40:01 +02002209 return 0;
2210
2211 srand((unsigned)time(NULL));
2212
2213 /*
2214 * 2- start them as far as possible from each others. For this, we will
2215 * start them after their interval set to the min interval divided by
2216 * the number of servers, weighted by the server's position in the list.
2217 */
2218 for (px = proxy; px; px = px->next) {
Simon Horman98637e52014-06-20 12:30:16 +09002219 if ((px->options2 & PR_O2_CHK_ANY) == PR_O2_EXT_CHK) {
2220 if (init_pid_list()) {
2221 Alert("Starting [%s] check: out of memory.\n", px->id);
2222 return -1;
2223 }
2224 }
2225
Krzysztof Oledzkib304dc72007-10-14 23:40:01 +02002226 for (s = px->srv; s; s = s->next) {
Simon Hormand60d6912013-11-25 10:46:36 +09002227 /* A task for the main check */
Willy Tarreauff5ae352013-12-11 20:36:34 +01002228 if (s->check.state & CHK_ST_CONFIGURED) {
Cyril Bonté99c5bf52014-08-07 01:55:38 +02002229 if (s->check.type == PR_O2_EXT_CHK) {
2230 if (!prepare_external_check(&s->check))
2231 return -1;
2232 }
Simon Hormand60d6912013-11-25 10:46:36 +09002233 if (!start_check_task(&s->check, mininter, nbcheck, srvpos))
2234 return -1;
2235 srvpos++;
2236 }
Krzysztof Oledzkib304dc72007-10-14 23:40:01 +02002237
Simon Hormand60d6912013-11-25 10:46:36 +09002238 /* A task for a auxiliary agent check */
Willy Tarreauff5ae352013-12-11 20:36:34 +01002239 if (s->agent.state & CHK_ST_CONFIGURED) {
Simon Hormand60d6912013-11-25 10:46:36 +09002240 if (!start_check_task(&s->agent, mininter, nbcheck, srvpos)) {
2241 return -1;
2242 }
2243 srvpos++;
2244 }
Krzysztof Oledzkib304dc72007-10-14 23:40:01 +02002245 }
2246 }
2247 return 0;
2248}
Willy Tarreaubaaee002006-06-26 02:48:02 +02002249
2250/*
Willy Tarreau5b3a2022012-09-28 15:01:02 +02002251 * Perform content verification check on data in s->check.buffer buffer.
Willy Tarreaubd741542010-03-16 18:46:54 +01002252 * The buffer MUST be terminated by a null byte before calling this function.
2253 * Sets server status appropriately. The caller is responsible for ensuring
2254 * that the buffer contains at least 13 characters. If <done> is zero, we may
2255 * return 0 to indicate that data is required to decide of a match.
2256 */
2257static int httpchk_expect(struct server *s, int done)
2258{
2259 static char status_msg[] = "HTTP status check returned code <000>";
2260 char status_code[] = "000";
2261 char *contentptr;
2262 int crlf;
2263 int ret;
2264
2265 switch (s->proxy->options2 & PR_O2_EXP_TYPE) {
2266 case PR_O2_EXP_STS:
2267 case PR_O2_EXP_RSTS:
Willy Tarreau1ae1b7b2012-09-28 15:28:30 +02002268 memcpy(status_code, s->check.bi->data + 9, 3);
2269 memcpy(status_msg + strlen(status_msg) - 4, s->check.bi->data + 9, 3);
Willy Tarreaubd741542010-03-16 18:46:54 +01002270
2271 if ((s->proxy->options2 & PR_O2_EXP_TYPE) == PR_O2_EXP_STS)
2272 ret = strncmp(s->proxy->expect_str, status_code, 3) == 0;
2273 else
Thierry FOURNIER09af0d62014-06-18 11:35:54 +02002274 ret = regex_exec(s->proxy->expect_regex, status_code);
Willy Tarreaubd741542010-03-16 18:46:54 +01002275
2276 /* we necessarily have the response, so there are no partial failures */
2277 if (s->proxy->options2 & PR_O2_EXP_INV)
2278 ret = !ret;
2279
Simon Horman4a741432013-02-23 15:35:38 +09002280 set_server_check_status(&s->check, ret ? HCHK_STATUS_L7OKD : HCHK_STATUS_L7STS, status_msg);
Willy Tarreaubd741542010-03-16 18:46:54 +01002281 break;
2282
2283 case PR_O2_EXP_STR:
2284 case PR_O2_EXP_RSTR:
2285 /* very simple response parser: ignore CR and only count consecutive LFs,
2286 * stop with contentptr pointing to first char after the double CRLF or
2287 * to '\0' if crlf < 2.
2288 */
2289 crlf = 0;
Willy Tarreau1ae1b7b2012-09-28 15:28:30 +02002290 for (contentptr = s->check.bi->data; *contentptr; contentptr++) {
Willy Tarreaubd741542010-03-16 18:46:54 +01002291 if (crlf >= 2)
2292 break;
2293 if (*contentptr == '\r')
2294 continue;
2295 else if (*contentptr == '\n')
2296 crlf++;
2297 else
2298 crlf = 0;
2299 }
2300
2301 /* Check that response contains a body... */
2302 if (crlf < 2) {
2303 if (!done)
2304 return 0;
2305
Simon Horman4a741432013-02-23 15:35:38 +09002306 set_server_check_status(&s->check, HCHK_STATUS_L7RSP,
Willy Tarreaubd741542010-03-16 18:46:54 +01002307 "HTTP content check could not find a response body");
2308 return 1;
2309 }
2310
2311 /* Check that response body is not empty... */
2312 if (*contentptr == '\0') {
Willy Tarreaua164fb52011-04-13 09:32:41 +02002313 if (!done)
2314 return 0;
2315
Simon Horman4a741432013-02-23 15:35:38 +09002316 set_server_check_status(&s->check, HCHK_STATUS_L7RSP,
Willy Tarreaubd741542010-03-16 18:46:54 +01002317 "HTTP content check found empty response body");
2318 return 1;
2319 }
2320
2321 /* Check the response content against the supplied string
2322 * or regex... */
2323 if ((s->proxy->options2 & PR_O2_EXP_TYPE) == PR_O2_EXP_STR)
2324 ret = strstr(contentptr, s->proxy->expect_str) != NULL;
2325 else
Thierry FOURNIER09af0d62014-06-18 11:35:54 +02002326 ret = regex_exec(s->proxy->expect_regex, contentptr);
Willy Tarreaubd741542010-03-16 18:46:54 +01002327
2328 /* if we don't match, we may need to wait more */
2329 if (!ret && !done)
2330 return 0;
2331
2332 if (ret) {
2333 /* content matched */
2334 if (s->proxy->options2 & PR_O2_EXP_INV)
Simon Horman4a741432013-02-23 15:35:38 +09002335 set_server_check_status(&s->check, HCHK_STATUS_L7RSP,
Willy Tarreaubd741542010-03-16 18:46:54 +01002336 "HTTP check matched unwanted content");
2337 else
Simon Horman4a741432013-02-23 15:35:38 +09002338 set_server_check_status(&s->check, HCHK_STATUS_L7OKD,
Willy Tarreaubd741542010-03-16 18:46:54 +01002339 "HTTP content check matched");
2340 }
2341 else {
2342 if (s->proxy->options2 & PR_O2_EXP_INV)
Simon Horman4a741432013-02-23 15:35:38 +09002343 set_server_check_status(&s->check, HCHK_STATUS_L7OKD,
Willy Tarreaubd741542010-03-16 18:46:54 +01002344 "HTTP check did not match unwanted content");
2345 else
Simon Horman4a741432013-02-23 15:35:38 +09002346 set_server_check_status(&s->check, HCHK_STATUS_L7RSP,
Willy Tarreaubd741542010-03-16 18:46:54 +01002347 "HTTP content check did not match");
2348 }
2349 break;
2350 }
2351 return 1;
2352}
2353
Baptiste Assmann5ecb77f2013-10-06 23:24:13 +02002354/*
2355 * return the id of a step in a send/expect session
2356 */
Simon Hormane16c1b32015-01-30 11:22:57 +09002357static int tcpcheck_get_step_id(struct check *check)
Baptiste Assmann5ecb77f2013-10-06 23:24:13 +02002358{
2359 struct tcpcheck_rule *cur = NULL, *next = NULL;
2360 int i = 0;
2361
Willy Tarreau213c6782014-10-02 14:51:02 +02002362 /* not even started anything yet => step 0 = initial connect */
Simon Hormane16c1b32015-01-30 11:22:57 +09002363 if (check->current_step)
Willy Tarreau213c6782014-10-02 14:51:02 +02002364 return 0;
2365
Simon Hormane16c1b32015-01-30 11:22:57 +09002366 cur = check->last_started_step;
Baptiste Assmann5ecb77f2013-10-06 23:24:13 +02002367
2368 /* no step => first step */
2369 if (cur == NULL)
2370 return 1;
2371
2372 /* increment i until current step */
Simon Hormane16c1b32015-01-30 11:22:57 +09002373 list_for_each_entry(next, check->tcpcheck_rules, list) {
Baptiste Assmann5ecb77f2013-10-06 23:24:13 +02002374 if (next->list.p == &cur->list)
2375 break;
2376 ++i;
2377 }
2378
2379 return i;
2380}
2381
2382static void tcpcheck_main(struct connection *conn)
2383{
2384 char *contentptr;
Willy Tarreauf3d34822014-12-08 12:11:28 +01002385 struct tcpcheck_rule *cur, *next;
Baptiste Assmann5ecb77f2013-10-06 23:24:13 +02002386 int done = 0, ret = 0;
Baptiste Assmann5ecb77f2013-10-06 23:24:13 +02002387 struct check *check = conn->owner;
2388 struct server *s = check->server;
2389 struct task *t = check->task;
Simon Hormane16c1b32015-01-30 11:22:57 +09002390 struct list *head = check->tcpcheck_rules;
Baptiste Assmann5ecb77f2013-10-06 23:24:13 +02002391
Willy Tarreauef953952014-10-02 14:30:14 +02002392 /* here, we know that the check is complete or that it failed */
2393 if (check->result != CHK_RES_UNKNOWN)
2394 goto out_end_tcpcheck;
2395
2396 /* We have 4 possibilities here :
2397 * 1. we've not yet attempted step 1, and step 1 is a connect, so no
2398 * connection attempt was made yet ;
2399 * 2. we've not yet attempted step 1, and step 1 is a not connect or
2400 * does not exist (no rule), so a connection attempt was made
2401 * before coming here.
2402 * 3. we're coming back after having started with step 1, so we may
2403 * be waiting for a connection attempt to complete.
2404 * 4. the connection + handshake are complete
2405 *
2406 * #2 and #3 are quite similar, we want both the connection and the
2407 * handshake to complete before going any further. Thus we must always
2408 * wait for a connection to complete unless we're before and existing
2409 * step 1.
Baptiste Assmann69e273f2013-12-11 00:52:19 +01002410 */
Willy Tarreauef953952014-10-02 14:30:14 +02002411 if ((!(conn->flags & CO_FL_CONNECTED) || (conn->flags & CO_FL_HANDSHAKE)) &&
2412 (check->current_step || LIST_ISEMPTY(head))) {
Baptiste Assmann5ecb77f2013-10-06 23:24:13 +02002413 /* we allow up to min(inter, timeout.connect) for a connection
2414 * to establish but only when timeout.check is set
2415 * as it may be to short for a full check otherwise
2416 */
2417 while (tick_is_expired(t->expire, now_ms)) {
2418 int t_con;
2419
2420 t_con = tick_add(t->expire, s->proxy->timeout.connect);
2421 t->expire = tick_add(t->expire, MS_TO_TICKS(check->inter));
2422
2423 if (s->proxy->timeout.check)
2424 t->expire = tick_first(t->expire, t_con);
2425 }
2426 return;
2427 }
2428
Willy Tarreauef953952014-10-02 14:30:14 +02002429 /* special case: option tcp-check with no rule, a connect is enough */
2430 if (LIST_ISEMPTY(head)) {
2431 set_server_check_status(check, HCHK_STATUS_L4OK, NULL);
Baptiste Assmann5ecb77f2013-10-06 23:24:13 +02002432 goto out_end_tcpcheck;
Willy Tarreauef953952014-10-02 14:30:14 +02002433 }
Baptiste Assmann5ecb77f2013-10-06 23:24:13 +02002434
Willy Tarreau213c6782014-10-02 14:51:02 +02002435 /* no step means first step initialisation */
Baptiste Assmann5ecb77f2013-10-06 23:24:13 +02002436 if (check->current_step == NULL) {
Willy Tarreau213c6782014-10-02 14:51:02 +02002437 check->last_started_step = NULL;
Baptiste Assmann5ecb77f2013-10-06 23:24:13 +02002438 check->bo->p = check->bo->data;
2439 check->bo->o = 0;
2440 check->bi->p = check->bi->data;
2441 check->bi->i = 0;
2442 cur = check->current_step = LIST_ELEM(head->n, struct tcpcheck_rule *, list);
2443 t->expire = tick_add(now_ms, MS_TO_TICKS(check->inter));
2444 if (s->proxy->timeout.check)
2445 t->expire = tick_add_ifset(now_ms, s->proxy->timeout.check);
2446 }
2447 /* keep on processing step */
2448 else {
2449 cur = check->current_step;
2450 }
2451
Willy Tarreaufbe0edf2013-12-06 16:54:31 +01002452 /* It's only the rules which will enable send/recv */
2453 __conn_data_stop_both(conn);
2454
Willy Tarreauabca5b62013-12-06 14:19:25 +01002455 while (1) {
Willy Tarreaufbe0edf2013-12-06 16:54:31 +01002456 /* we have to try to flush the output buffer before reading, at the end,
2457 * or if we're about to send a string that does not fit in the remaining space.
2458 */
2459 if (check->bo->o &&
2460 (&cur->list == head ||
2461 check->current_step->action != TCPCHK_ACT_SEND ||
2462 check->current_step->string_len >= buffer_total_space(check->bo))) {
2463
Willy Tarreau1049b1f2014-02-02 01:51:17 +01002464 if (conn->xprt->snd_buf(conn, check->bo, 0) <= 0) {
Willy Tarreaufbe0edf2013-12-06 16:54:31 +01002465 if (conn->flags & CO_FL_ERROR) {
2466 chk_report_conn_err(conn, errno, 0);
2467 __conn_data_stop_both(conn);
2468 goto out_end_tcpcheck;
2469 }
2470 goto out_need_io;
Willy Tarreauabca5b62013-12-06 14:19:25 +01002471 }
Willy Tarreauabca5b62013-12-06 14:19:25 +01002472 }
2473
Willy Tarreaufbe0edf2013-12-06 16:54:31 +01002474 /* did we reach the end ? If so, let's check that everything was sent */
2475 if (&cur->list == head) {
2476 if (check->bo->o)
2477 goto out_need_io;
Willy Tarreauabca5b62013-12-06 14:19:25 +01002478 break;
Willy Tarreaufbe0edf2013-12-06 16:54:31 +01002479 }
Willy Tarreauabca5b62013-12-06 14:19:25 +01002480
Willy Tarreauf3d34822014-12-08 12:11:28 +01002481 /* have 'next' point to the next rule or NULL if we're on the last one */
2482 next = (struct tcpcheck_rule *)cur->list.n;
2483 if (&next->list == head)
2484 next = NULL;
2485
Baptiste Assmann69e273f2013-12-11 00:52:19 +01002486 if (check->current_step->action == TCPCHK_ACT_CONNECT) {
2487 struct protocol *proto;
2488 struct xprt_ops *xprt;
2489
2490 /* mark the step as started */
2491 check->last_started_step = check->current_step;
2492 /* first, shut existing connection */
2493 conn_force_close(conn);
2494
2495 /* prepare new connection */
2496 /* initialization */
2497 conn_init(conn);
2498 conn_attach(conn, check, &check_conn_cb);
2499 conn->target = &s->obj_type;
2500
2501 /* no client address */
2502 clear_addr(&conn->addr.from);
2503
Simon Horman41f58762015-01-30 11:22:56 +09002504 if (is_addr(&check->addr)) {
Baptiste Assmann69e273f2013-12-11 00:52:19 +01002505 /* we'll connect to the check addr specified on the server */
Simon Horman41f58762015-01-30 11:22:56 +09002506 conn->addr.to = check->addr;
2507 proto = check->proto;
Willy Tarreau640556c2014-05-09 23:38:15 +02002508 }
2509 else {
Baptiste Assmann69e273f2013-12-11 00:52:19 +01002510 /* we'll connect to the addr on the server */
2511 conn->addr.to = s->addr;
Willy Tarreau640556c2014-05-09 23:38:15 +02002512 proto = s->proto;
2513 }
Baptiste Assmann69e273f2013-12-11 00:52:19 +01002514
2515 /* port */
2516 if (check->current_step->port)
2517 set_host_port(&conn->addr.to, check->current_step->port);
2518 else if (check->port)
2519 set_host_port(&conn->addr.to, check->port);
2520
2521#ifdef USE_OPENSSL
2522 if (check->current_step->conn_opts & TCPCHK_OPT_SSL) {
2523 xprt = &ssl_sock;
Baptiste Assmann69e273f2013-12-11 00:52:19 +01002524 }
2525 else {
2526 xprt = &raw_sock;
2527 }
2528#else /* USE_OPENSSL */
2529 xprt = &raw_sock;
2530#endif /* USE_OPENSSL */
2531 conn_prepare(conn, proto, xprt);
2532
2533 ret = SN_ERR_INTERNAL;
2534 if (proto->connect)
Willy Tarreauf3d34822014-12-08 12:11:28 +01002535 ret = proto->connect(conn,
2536 1 /* I/O polling is always needed */,
2537 (next && next->action == TCPCHK_ACT_EXPECT) ? 0 : 2);
Baptiste Assmann69e273f2013-12-11 00:52:19 +01002538 conn->flags |= CO_FL_WAKE_DATA;
2539 if (check->current_step->conn_opts & TCPCHK_OPT_SEND_PROXY) {
2540 conn->send_proxy_ofs = 1;
2541 conn->flags |= CO_FL_SEND_PROXY;
2542 }
2543
2544 /* It can return one of :
2545 * - SN_ERR_NONE if everything's OK
2546 * - SN_ERR_SRVTO if there are no more servers
2547 * - SN_ERR_SRVCL if the connection was refused by the server
2548 * - SN_ERR_PRXCOND if the connection has been limited by the proxy (maxconn)
2549 * - SN_ERR_RESOURCE if a system resource is lacking (eg: fd limits, ports, ...)
2550 * - SN_ERR_INTERNAL for any other purely internal errors
2551 * Additionnally, in the case of SN_ERR_RESOURCE, an emergency log will be emitted.
2552 * Note that we try to prevent the network stack from sending the ACK during the
2553 * connect() when a pure TCP check is used (without PROXY protocol).
2554 */
2555 switch (ret) {
2556 case SN_ERR_NONE:
2557 /* we allow up to min(inter, timeout.connect) for a connection
2558 * to establish but only when timeout.check is set
2559 * as it may be to short for a full check otherwise
2560 */
2561 t->expire = tick_add(now_ms, MS_TO_TICKS(check->inter));
2562
2563 if (s->proxy->timeout.check && s->proxy->timeout.connect) {
2564 int t_con = tick_add(now_ms, s->proxy->timeout.connect);
2565 t->expire = tick_first(t->expire, t_con);
2566 }
2567 break;
2568 case SN_ERR_SRVTO: /* ETIMEDOUT */
2569 case SN_ERR_SRVCL: /* ECONNREFUSED, ENETUNREACH, ... */
2570 chunk_printf(&trash, "TCPCHK error establishing connection at step %d: %s",
Simon Hormane16c1b32015-01-30 11:22:57 +09002571 tcpcheck_get_step_id(check), strerror(errno));
Baptiste Assmann69e273f2013-12-11 00:52:19 +01002572 set_server_check_status(check, HCHK_STATUS_L4CON, trash.str);
2573 goto out_end_tcpcheck;
2574 case SN_ERR_PRXCOND:
2575 case SN_ERR_RESOURCE:
2576 case SN_ERR_INTERNAL:
2577 chunk_printf(&trash, "TCPCHK error establishing connection at step %d",
Simon Hormane16c1b32015-01-30 11:22:57 +09002578 tcpcheck_get_step_id(check));
Baptiste Assmann69e273f2013-12-11 00:52:19 +01002579 set_server_check_status(check, HCHK_STATUS_SOCKERR, trash.str);
2580 goto out_end_tcpcheck;
2581 }
2582
2583 /* allow next rule */
2584 cur = (struct tcpcheck_rule *)cur->list.n;
2585 check->current_step = cur;
2586
2587 /* don't do anything until the connection is established */
2588 if (!(conn->flags & CO_FL_CONNECTED)) {
2589 /* update expire time, should be done by process_chk */
2590 /* we allow up to min(inter, timeout.connect) for a connection
2591 * to establish but only when timeout.check is set
2592 * as it may be to short for a full check otherwise
2593 */
2594 while (tick_is_expired(t->expire, now_ms)) {
2595 int t_con;
2596
2597 t_con = tick_add(t->expire, s->proxy->timeout.connect);
2598 t->expire = tick_add(t->expire, MS_TO_TICKS(check->inter));
2599
2600 if (s->proxy->timeout.check)
2601 t->expire = tick_first(t->expire, t_con);
2602 }
2603 return;
2604 }
2605
2606 } /* end 'connect' */
2607 else if (check->current_step->action == TCPCHK_ACT_SEND) {
2608 /* mark the step as started */
2609 check->last_started_step = check->current_step;
2610
Baptiste Assmann5ecb77f2013-10-06 23:24:13 +02002611 /* reset the read buffer */
2612 if (*check->bi->data != '\0') {
2613 *check->bi->data = '\0';
2614 check->bi->i = 0;
2615 }
2616
2617 if (conn->flags & (CO_FL_SOCK_WR_SH | CO_FL_DATA_WR_SH)) {
2618 conn->flags |= CO_FL_ERROR;
2619 chk_report_conn_err(conn, 0, 0);
2620 goto out_end_tcpcheck;
2621 }
2622
Willy Tarreauabca5b62013-12-06 14:19:25 +01002623 if (check->current_step->string_len >= check->bo->size) {
2624 chunk_printf(&trash, "tcp-check send : string too large (%d) for buffer size (%d) at step %d",
2625 check->current_step->string_len, check->bo->size,
Simon Hormane16c1b32015-01-30 11:22:57 +09002626 tcpcheck_get_step_id(check));
Willy Tarreauabca5b62013-12-06 14:19:25 +01002627 set_server_check_status(check, HCHK_STATUS_L7RSP, trash.str);
2628 goto out_end_tcpcheck;
2629 }
Baptiste Assmann5ecb77f2013-10-06 23:24:13 +02002630
Willy Tarreaufbe0edf2013-12-06 16:54:31 +01002631 /* do not try to send if there is no space */
2632 if (check->current_step->string_len >= buffer_total_space(check->bo))
2633 continue;
2634
Baptiste Assmann5ecb77f2013-10-06 23:24:13 +02002635 bo_putblk(check->bo, check->current_step->string, check->current_step->string_len);
2636 *check->bo->p = '\0'; /* to make gdb output easier to read */
2637
Willy Tarreauabca5b62013-12-06 14:19:25 +01002638 /* go to next rule and try to send */
Baptiste Assmann5ecb77f2013-10-06 23:24:13 +02002639 cur = (struct tcpcheck_rule *)cur->list.n;
2640 check->current_step = cur;
Baptiste Assmann5ecb77f2013-10-06 23:24:13 +02002641 } /* end 'send' */
Willy Tarreau98aec9f2013-12-06 16:16:41 +01002642 else if (check->current_step->action == TCPCHK_ACT_EXPECT) {
Willy Tarreau6aaa1b82013-12-11 17:09:34 +01002643 if (unlikely(check->result == CHK_RES_FAILED))
Baptiste Assmann5ecb77f2013-10-06 23:24:13 +02002644 goto out_end_tcpcheck;
2645
Willy Tarreau310987a2014-01-22 19:46:33 +01002646 if (conn->xprt->rcv_buf(conn, check->bi, check->bi->size) <= 0) {
Willy Tarreaufbe0edf2013-12-06 16:54:31 +01002647 if (conn->flags & (CO_FL_ERROR | CO_FL_SOCK_RD_SH | CO_FL_DATA_RD_SH)) {
2648 done = 1;
2649 if ((conn->flags & CO_FL_ERROR) && !check->bi->i) {
2650 /* Report network errors only if we got no other data. Otherwise
2651 * we'll let the upper layers decide whether the response is OK
2652 * or not. It is very common that an RST sent by the server is
2653 * reported as an error just after the last data chunk.
2654 */
2655 chk_report_conn_err(conn, errno, 0);
2656 goto out_end_tcpcheck;
2657 }
Baptiste Assmann5ecb77f2013-10-06 23:24:13 +02002658 }
Willy Tarreaufbe0edf2013-12-06 16:54:31 +01002659 else
2660 goto out_need_io;
Baptiste Assmann5ecb77f2013-10-06 23:24:13 +02002661 }
2662
Baptiste Assmann69e273f2013-12-11 00:52:19 +01002663 /* mark the step as started */
2664 check->last_started_step = check->current_step;
2665
2666
Baptiste Assmann5ecb77f2013-10-06 23:24:13 +02002667 /* Intermediate or complete response received.
2668 * Terminate string in check->bi->data buffer.
2669 */
2670 if (check->bi->i < check->bi->size) {
2671 check->bi->data[check->bi->i] = '\0';
2672 }
2673 else {
2674 check->bi->data[check->bi->i - 1] = '\0';
2675 done = 1; /* buffer full, don't wait for more data */
2676 }
2677
2678 contentptr = check->bi->data;
Baptiste Assmann5ecb77f2013-10-06 23:24:13 +02002679
2680 /* Check that response body is not empty... */
Willy Tarreauec6b0122014-05-13 17:57:29 +02002681 if (!check->bi->i) {
Baptiste Assmann5ecb77f2013-10-06 23:24:13 +02002682 if (!done)
Willy Tarreaufbe0edf2013-12-06 16:54:31 +01002683 continue;
Baptiste Assmann5ecb77f2013-10-06 23:24:13 +02002684
2685 /* empty response */
2686 chunk_printf(&trash, "TCPCHK got an empty response at step %d",
Simon Hormane16c1b32015-01-30 11:22:57 +09002687 tcpcheck_get_step_id(check));
Baptiste Assmann5ecb77f2013-10-06 23:24:13 +02002688 set_server_check_status(check, HCHK_STATUS_L7RSP, trash.str);
2689
2690 goto out_end_tcpcheck;
2691 }
2692
2693 if (!done && (cur->string != NULL) && (check->bi->i < cur->string_len) )
Willy Tarreaua970c282013-12-06 12:47:19 +01002694 continue; /* try to read more */
Baptiste Assmann5ecb77f2013-10-06 23:24:13 +02002695
Willy Tarreaua970c282013-12-06 12:47:19 +01002696 tcpcheck_expect:
Baptiste Assmann5ecb77f2013-10-06 23:24:13 +02002697 if (cur->string != NULL)
Willy Tarreauec6b0122014-05-13 17:57:29 +02002698 ret = my_memmem(contentptr, check->bi->i, cur->string, cur->string_len) != NULL;
Baptiste Assmann5ecb77f2013-10-06 23:24:13 +02002699 else if (cur->expect_regex != NULL)
Thierry FOURNIER09af0d62014-06-18 11:35:54 +02002700 ret = regex_exec(cur->expect_regex, contentptr);
Baptiste Assmann5ecb77f2013-10-06 23:24:13 +02002701
2702 if (!ret && !done)
Willy Tarreaua970c282013-12-06 12:47:19 +01002703 continue; /* try to read more */
Baptiste Assmann5ecb77f2013-10-06 23:24:13 +02002704
2705 /* matched */
2706 if (ret) {
2707 /* matched but we did not want to => ERROR */
2708 if (cur->inverse) {
2709 /* we were looking for a string */
2710 if (cur->string != NULL) {
2711 chunk_printf(&trash, "TCPCHK matched unwanted content '%s' at step %d",
Simon Hormane16c1b32015-01-30 11:22:57 +09002712 cur->string, tcpcheck_get_step_id(check));
Baptiste Assmann5ecb77f2013-10-06 23:24:13 +02002713 }
2714 else {
2715 /* we were looking for a regex */
2716 chunk_printf(&trash, "TCPCHK matched unwanted content (regex) at step %d",
Simon Hormane16c1b32015-01-30 11:22:57 +09002717 tcpcheck_get_step_id(check));
Baptiste Assmann5ecb77f2013-10-06 23:24:13 +02002718 }
2719 set_server_check_status(check, HCHK_STATUS_L7RSP, trash.str);
2720 goto out_end_tcpcheck;
2721 }
2722 /* matched and was supposed to => OK, next step */
2723 else {
2724 cur = (struct tcpcheck_rule*)cur->list.n;
2725 check->current_step = cur;
Willy Tarreau98aec9f2013-12-06 16:16:41 +01002726 if (check->current_step->action == TCPCHK_ACT_EXPECT)
Baptiste Assmann5ecb77f2013-10-06 23:24:13 +02002727 goto tcpcheck_expect;
2728 __conn_data_stop_recv(conn);
2729 }
2730 }
2731 else {
2732 /* not matched */
2733 /* not matched and was not supposed to => OK, next step */
2734 if (cur->inverse) {
2735 cur = (struct tcpcheck_rule*)cur->list.n;
2736 check->current_step = cur;
Willy Tarreau98aec9f2013-12-06 16:16:41 +01002737 if (check->current_step->action == TCPCHK_ACT_EXPECT)
Baptiste Assmann5ecb77f2013-10-06 23:24:13 +02002738 goto tcpcheck_expect;
2739 __conn_data_stop_recv(conn);
2740 }
2741 /* not matched but was supposed to => ERROR */
2742 else {
2743 /* we were looking for a string */
2744 if (cur->string != NULL) {
2745 chunk_printf(&trash, "TCPCHK did not match content '%s' at step %d",
Simon Hormane16c1b32015-01-30 11:22:57 +09002746 cur->string, tcpcheck_get_step_id(check));
Baptiste Assmann5ecb77f2013-10-06 23:24:13 +02002747 }
2748 else {
2749 /* we were looking for a regex */
2750 chunk_printf(&trash, "TCPCHK did not match content (regex) at step %d",
Simon Hormane16c1b32015-01-30 11:22:57 +09002751 tcpcheck_get_step_id(check));
Baptiste Assmann5ecb77f2013-10-06 23:24:13 +02002752 }
2753 set_server_check_status(check, HCHK_STATUS_L7RSP, trash.str);
2754 goto out_end_tcpcheck;
2755 }
2756 }
2757 } /* end expect */
2758 } /* end loop over double chained step list */
2759
2760 set_server_check_status(check, HCHK_STATUS_L7OKD, "(tcp-check)");
2761 goto out_end_tcpcheck;
2762
Willy Tarreaufbe0edf2013-12-06 16:54:31 +01002763 out_need_io:
2764 if (check->bo->o)
2765 __conn_data_want_send(conn);
2766
2767 if (check->current_step->action == TCPCHK_ACT_EXPECT)
2768 __conn_data_want_recv(conn);
Baptiste Assmann5ecb77f2013-10-06 23:24:13 +02002769 return;
2770
2771 out_end_tcpcheck:
2772 /* collect possible new errors */
2773 if (conn->flags & CO_FL_ERROR)
2774 chk_report_conn_err(conn, 0, 0);
2775
Baptiste Assmann69e273f2013-12-11 00:52:19 +01002776 /* cleanup before leaving */
Baptiste Assmann5ecb77f2013-10-06 23:24:13 +02002777 check->current_step = NULL;
2778
Willy Tarreau6aaa1b82013-12-11 17:09:34 +01002779 if (check->result == CHK_RES_FAILED)
Baptiste Assmann5ecb77f2013-10-06 23:24:13 +02002780 conn->flags |= CO_FL_ERROR;
2781
2782 __conn_data_stop_both(conn);
Baptiste Assmann5ecb77f2013-10-06 23:24:13 +02002783
2784 return;
2785}
2786
Simon Hormanb1900d52015-01-30 11:22:54 +09002787const char *init_check(struct check *check, int type)
2788{
2789 check->type = type;
2790
2791 /* Allocate buffer for requests... */
2792 if ((check->bi = calloc(sizeof(struct buffer) + global.tune.chksize, sizeof(char))) == NULL) {
2793 return "out of memory while allocating check buffer";
2794 }
2795 check->bi->size = global.tune.chksize;
2796
2797 /* Allocate buffer for responses... */
2798 if ((check->bo = calloc(sizeof(struct buffer) + global.tune.chksize, sizeof(char))) == NULL) {
2799 return "out of memory while allocating check buffer";
2800 }
2801 check->bo->size = global.tune.chksize;
2802
2803 /* Allocate buffer for partial results... */
2804 if ((check->conn = calloc(1, sizeof(struct connection))) == NULL) {
2805 return "out of memory while allocating check connection";
2806 }
2807
2808 check->conn->t.sock.fd = -1; /* no agent in progress yet */
2809
2810 return NULL;
2811}
2812
Simon Hormanbfb5d332015-01-30 11:22:55 +09002813void free_check(struct check *check)
2814{
2815 free(check->bi);
2816 free(check->bo);
2817 free(check->conn);
2818}
2819
Simon Horman0ba0e4a2015-01-30 11:23:00 +09002820void email_alert_free(struct email_alert *alert)
2821{
2822 struct tcpcheck_rule *rule, *back;
2823
2824 if (!alert)
2825 return;
2826
2827 list_for_each_entry_safe(rule, back, &alert->tcpcheck_rules, list)
2828 free(rule);
2829 free(alert);
2830}
2831
2832static struct task *process_email_alert(struct task *t)
2833{
2834 struct check *check = t->context;
2835 struct email_alertq *q;
2836
2837 q = container_of(check, typeof(*q), check);
2838
2839 if (!(check->state & CHK_ST_ENABLED)) {
2840 if (LIST_ISEMPTY(&q->email_alerts)) {
2841 /* All alerts processed, delete check */
2842 task_delete(t);
2843 task_free(t);
2844 check->task = NULL;
2845 return NULL;
2846 } else {
2847 struct email_alert *alert;
2848
2849 alert = LIST_NEXT(&q->email_alerts, typeof(alert), list);
2850 check->tcpcheck_rules = &alert->tcpcheck_rules;
2851 LIST_DEL(&alert->list);
2852
2853 check->state |= CHK_ST_ENABLED;
2854 }
2855
2856 }
2857
2858 process_chk(t);
2859
2860 if (!(check->state & CHK_ST_INPROGRESS) && check->tcpcheck_rules) {
2861 struct email_alert *alert;
2862
2863 alert = container_of(check->tcpcheck_rules, typeof(*alert), tcpcheck_rules);
2864 email_alert_free(alert);
2865
2866 check->tcpcheck_rules = NULL;
2867 check->state &= ~CHK_ST_ENABLED;
2868 }
2869 return t;
2870}
2871
2872static int init_email_alert_checks(struct server *s)
2873{
2874 int i;
2875 struct mailer *mailer;
2876 const char *err_str;
2877 struct proxy *p = s->proxy;
2878
2879 if (p->email_alert.queues)
2880 /* Already initialised, nothing to do */
2881 return 1;
2882
2883 p->email_alert.queues = calloc(p->email_alert.mailers.m->count, sizeof *p->email_alert.queues);
2884 if (!p->email_alert.queues) {
2885 err_str = "out of memory while allocating checks array";
2886 goto error_alert;
2887 }
2888
2889 for (i = 0, mailer = p->email_alert.mailers.m->mailer_list;
2890 i < p->email_alert.mailers.m->count; i++, mailer = mailer->next) {
2891 struct email_alertq *q = &p->email_alert.queues[i];
2892 struct check *check = &q->check;
2893
2894
2895 LIST_INIT(&q->email_alerts);
2896
2897 check->inter = DEF_CHKINTR; /* XXX: Would like to Skip to the next alert, if any, ASAP.
2898 * But need enough time so that timeouts don't occur
2899 * during tcp check procssing. For now just us an arbitrary default. */
2900 check->rise = DEF_AGENT_RISETIME;
2901 check->fall = DEF_AGENT_FALLTIME;
2902 err_str = init_check(check, PR_O2_TCPCHK_CHK);
2903 if (err_str) {
2904 goto error_free;
2905 }
2906
2907 check->xprt = mailer->xprt;
2908 if (!get_host_port(&mailer->addr))
2909 /* Default to submission port */
2910 check->port = 587;
2911 check->proto = mailer->proto;
2912 check->addr = mailer->addr;
2913 check->server = s;
2914 }
2915
2916 return 1;
2917
2918error_free:
2919 while (i-- > 1)
2920 task_free(p->email_alert.queues[i].check.task);
2921 free(p->email_alert.queues);
2922 p->email_alert.queues = NULL;
2923error_alert:
2924 Alert("Email alert [%s] could not be initialised: %s\n", p->id, err_str);
2925 return 0;
2926}
2927
2928
2929static int add_tcpcheck_expect_str(struct list *list, const char *str)
2930{
2931 struct tcpcheck_rule *tcpcheck;
2932
2933 tcpcheck = calloc(1, sizeof *tcpcheck);
2934 if (!tcpcheck)
2935 return 0;
2936
2937 tcpcheck->action = TCPCHK_ACT_EXPECT;
2938 tcpcheck->string = strdup(str);
2939 if (!tcpcheck->string) {
2940 free(tcpcheck);
2941 return 0;
2942 }
2943
2944 LIST_ADDQ(list, &tcpcheck->list);
2945 return 1;
2946}
2947
2948static int add_tcpcheck_send_strs(struct list *list, const char * const *strs)
2949{
2950 struct tcpcheck_rule *tcpcheck;
2951 int i;
2952
2953 tcpcheck = calloc(1, sizeof *tcpcheck);
2954 if (!tcpcheck)
2955 return 0;
2956
2957 tcpcheck->action = TCPCHK_ACT_SEND;
2958
2959 tcpcheck->string_len = 0;
2960 for (i = 0; strs[i]; i++)
2961 tcpcheck->string_len += strlen(strs[i]);
2962
2963 tcpcheck->string = malloc(tcpcheck->string_len + 1);
2964 if (!tcpcheck->string) {
2965 free(tcpcheck);
2966 return 0;
2967 }
2968 tcpcheck->string[0] = '\0';
2969
2970 for (i = 0; strs[i]; i++)
2971 strcat(tcpcheck->string, strs[i]);
2972
2973 LIST_ADDQ(list, &tcpcheck->list);
2974 return 1;
2975}
2976
2977static int enqueue_one_email_alert(struct email_alertq *q, const char *msg)
2978{
2979 struct email_alert *alert = NULL;
2980 struct tcpcheck_rule *tcpcheck;
2981 struct check *check = &q->check;
2982 struct proxy *p = check->server->proxy;
2983
2984 alert = calloc(1, sizeof *alert);
2985 if (!alert) {
2986 goto error;
2987 }
2988 LIST_INIT(&alert->tcpcheck_rules);
2989
2990 tcpcheck = calloc(1, sizeof *tcpcheck);
2991 if (!tcpcheck)
2992 goto error;
2993 tcpcheck->action = TCPCHK_ACT_CONNECT;
2994 LIST_ADDQ(&alert->tcpcheck_rules, &tcpcheck->list);
2995
2996 if (!add_tcpcheck_expect_str(&alert->tcpcheck_rules, "220 "))
2997 goto error;
2998
2999 {
3000 const char * const strs[4] = { "EHLO ", p->email_alert.myhostname, "\r\n" };
3001 if (!add_tcpcheck_send_strs(&alert->tcpcheck_rules, strs))
3002 goto error;
3003 }
3004
3005 if (!add_tcpcheck_expect_str(&alert->tcpcheck_rules, "250 "))
3006 goto error;
3007
3008 {
3009 const char * const strs[4] = { "MAIL FROM:<", p->email_alert.from, ">\r\n" };
3010 if (!add_tcpcheck_send_strs(&alert->tcpcheck_rules, strs))
3011 goto error;
3012 }
3013
3014 if (!add_tcpcheck_expect_str(&alert->tcpcheck_rules, "250 "))
3015 goto error;
3016
3017 {
3018 const char * const strs[4] = { "RCPT TO:<", p->email_alert.to, ">\r\n" };
3019 if (!add_tcpcheck_send_strs(&alert->tcpcheck_rules, strs))
3020 goto error;
3021 }
3022
3023 if (!add_tcpcheck_expect_str(&alert->tcpcheck_rules, "250 "))
3024 goto error;
3025
3026 {
3027 const char * const strs[2] = { "DATA\r\n" };
3028 if (!add_tcpcheck_send_strs(&alert->tcpcheck_rules, strs))
3029 goto error;
3030 }
3031
3032 if (!add_tcpcheck_expect_str(&alert->tcpcheck_rules, "354 "))
3033 goto error;
3034
3035 {
3036 struct tm tm;
3037 char datestr[48];
3038 const char * const strs[18] = {
3039 "From: ", p->email_alert.from, "\n",
3040 "To: ", p->email_alert.to, "\n",
3041 "Date: ", datestr, "\n",
3042 "Subject: [HAproxy Alert] ", msg, "\n",
3043 "\n",
3044 msg, "\n",
3045 ".\r\n",
3046 "\r\n",
3047 NULL
3048 };
3049
3050 get_localtime(date.tv_sec, &tm);
3051
3052 if (strftime(datestr, sizeof(datestr), "%a, %d %b %Y %T %z (%Z)", &tm) == 0) {
3053 goto error;
3054 }
3055
3056 if (!add_tcpcheck_send_strs(&alert->tcpcheck_rules, strs))
3057 goto error;
3058 }
3059
3060 if (!add_tcpcheck_expect_str(&alert->tcpcheck_rules, "250 "))
3061 goto error;
3062
3063 {
3064 const char * const strs[2] = { "QUIT\r\n" };
3065 if (!add_tcpcheck_send_strs(&alert->tcpcheck_rules, strs))
3066 goto error;
3067 }
3068
3069 if (!add_tcpcheck_expect_str(&alert->tcpcheck_rules, "221 "))
3070 goto error;
3071
3072 if (!check->task) {
3073 struct task *t;
3074
3075 if ((t = task_new()) == NULL)
3076 goto error;
3077
3078 check->task = t;
3079 t->process = process_email_alert;
3080 t->context = check;
3081
3082 /* check this in one ms */
3083 t->expire = tick_add(now_ms, MS_TO_TICKS(1));
3084 check->start = now;
3085 task_queue(t);
3086 }
3087
3088 LIST_ADDQ(&q->email_alerts, &alert->list);
3089
3090 return 1;
3091
3092error:
3093 email_alert_free(alert);
3094 return 0;
3095}
3096
3097static void enqueue_email_alert(struct proxy *p, const char *msg)
3098{
3099 int i;
3100 struct mailer *mailer;
3101
3102 for (i = 0, mailer = p->email_alert.mailers.m->mailer_list;
3103 i < p->email_alert.mailers.m->count; i++, mailer = mailer->next) {
3104 if (!enqueue_one_email_alert(&p->email_alert.queues[i], msg)) {
3105 Alert("Email alert [%s] could not be enqueued: out of memory\n", p->id);
3106 return;
3107 }
3108 }
3109
3110 return;
3111}
3112
3113/*
3114 * Send email alert if configured.
3115 */
Simon Horman64e34162015-02-06 11:11:57 +09003116void send_email_alert(struct server *s, int level, const char *format, ...)
Simon Horman0ba0e4a2015-01-30 11:23:00 +09003117{
3118 va_list argp;
3119 char buf[1024];
3120 int len;
3121 struct proxy *p = s->proxy;
3122
Simon Horman64e34162015-02-06 11:11:57 +09003123 if (!p->email_alert.mailers.m || level > p->email_alert.level ||
3124 format == NULL || !init_email_alert_checks(s))
Simon Horman0ba0e4a2015-01-30 11:23:00 +09003125 return;
3126
3127 va_start(argp, format);
3128 len = vsnprintf(buf, sizeof(buf), format, argp);
3129 va_end(argp);
3130
3131 if (len < 0) {
3132 Alert("Email alert [%s] could format message\n", p->id);
3133 return;
3134 }
3135
3136 enqueue_email_alert(p, buf);
3137}
3138
Baptiste Assmann5ecb77f2013-10-06 23:24:13 +02003139
Willy Tarreaubd741542010-03-16 18:46:54 +01003140/*
Willy Tarreaubaaee002006-06-26 02:48:02 +02003141 * Local variables:
3142 * c-indent-level: 8
3143 * c-basic-offset: 8
3144 * End:
3145 */