Coverage Report

Created: 2026-08-31 06:47

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/haproxy/src/check.c
Line
Count
Source
1
/*
2
 * Health-checks functions.
3
 *
4
 * Copyright 2000-2009 Willy Tarreau <w@1wt.eu>
5
 * Copyright 2007-2009 Krzysztof Piotr Oledzki <ole@ans.pl>
6
 *
7
 * This program is free software; you can redistribute it and/or
8
 * modify it under the terms of the GNU General Public License
9
 * as published by the Free Software Foundation; either version
10
 * 2 of the License, or (at your option) any later version.
11
 *
12
 */
13
14
#include <assert.h>
15
#include <ctype.h>
16
#include <errno.h>
17
#include <stdarg.h>
18
#include <stdio.h>
19
#include <stdlib.h>
20
#include <string.h>
21
#include <time.h>
22
#include <unistd.h>
23
#include <sys/resource.h>
24
#include <sys/socket.h>
25
#include <sys/types.h>
26
#include <sys/wait.h>
27
#include <netinet/in.h>
28
#include <netinet/tcp.h>
29
#include <arpa/inet.h>
30
31
#include <haproxy/action.h>
32
#include <haproxy/api.h>
33
#include <haproxy/arg.h>
34
#include <haproxy/cfgparse.h>
35
#include <haproxy/check.h>
36
#include <haproxy/chunk.h>
37
#include <haproxy/counters-t.h>
38
#include <haproxy/dgram.h>
39
#include <haproxy/dynbuf.h>
40
#include <haproxy/extcheck.h>
41
#include <haproxy/fd.h>
42
#include <haproxy/global.h>
43
#include <haproxy/h1.h>
44
#include <haproxy/http.h>
45
#include <haproxy/http_htx.h>
46
#include <haproxy/htx.h>
47
#include <haproxy/istbuf.h>
48
#include <haproxy/list.h>
49
#include <haproxy/log.h>
50
#include <haproxy/mailers.h>
51
#include <haproxy/port_range.h>
52
#include <haproxy/proto_tcp.h>
53
#include <haproxy/protocol.h>
54
#include <haproxy/proxy.h>
55
#include <haproxy/queue.h>
56
#include <haproxy/regex.h>
57
#include <haproxy/resolvers.h>
58
#include <haproxy/sample.h>
59
#include <haproxy/server.h>
60
#include <haproxy/ssl_sock.h>
61
#include <haproxy/task.h>
62
#include <haproxy/tcpcheck.h>
63
#include <haproxy/thread.h>
64
#include <haproxy/time.h>
65
#include <haproxy/tools.h>
66
#include <haproxy/trace.h>
67
#include <haproxy/vars.h>
68
69
/* Dummy frontend used to create all checks sessions. */
70
struct proxy checks_fe;
71
72
#if defined(USE_TRACE)
73
74
/* trace source and events */
75
static void check_trace(enum trace_level level, uint64_t mask,
76
      const struct trace_source *src,
77
      const struct ist where, const struct ist func,
78
      const void *a1, const void *a2, const void *a3, const void *a4);
79
80
/* The event representation is split like this :
81
 *   check  - check
82
 *
83
 * CHECK_EV_* macros are defined in <haproxy/check.h>
84
 */
85
static const struct trace_event check_trace_events[] = {
86
  { .mask = CHK_EV_TASK_WAKE,   .name = "task_wake",        .desc = "Check task woken up" },
87
  { .mask = CHK_EV_HCHK_START,  .name = "hchck_start",      .desc = "Health-check started" },
88
  { .mask = CHK_EV_HCHK_WAKE,   .name = "hchck_wake",       .desc = "Health-check woken up" },
89
  { .mask = CHK_EV_HCHK_RUN,    .name = "hchck_run",        .desc = "Health-check running" },
90
  { .mask = CHK_EV_HCHK_END,    .name = "hchck_end",        .desc = "Health-check terminated" },
91
  { .mask = CHK_EV_HCHK_SUCC,   .name = "hchck_succ",       .desc = "Health-check success" },
92
  { .mask = CHK_EV_HCHK_ERR,    .name = "hchck_err",        .desc = "Health-check failure" },
93
94
  { .mask = CHK_EV_TCPCHK_EVAL, .name = "tcp_check_eval",   .desc = "tcp-check rules evaluation" },
95
  { .mask = CHK_EV_TCPCHK_ERR,  .name = "tcp_check_err",    .desc = "tcp-check evaluation error" },
96
  { .mask = CHK_EV_TCPCHK_CONN, .name = "tcp_check_conn",   .desc = "tcp-check connection rule" },
97
  { .mask = CHK_EV_TCPCHK_SND,  .name = "tcp_check_send",   .desc = "tcp-check send rule" },
98
  { .mask = CHK_EV_TCPCHK_EXP,  .name = "tcp_check_expect", .desc = "tcp-check expect rule" },
99
  { .mask = CHK_EV_TCPCHK_ACT,  .name = "tcp_check_action", .desc = "tcp-check action rule" },
100
101
  { .mask = CHK_EV_RX_DATA,     .name = "rx_data",          .desc = "receipt of data" },
102
  { .mask = CHK_EV_RX_BLK,      .name = "rx_blk",           .desc = "receipt blocked" },
103
  { .mask = CHK_EV_RX_ERR,      .name = "rx_err",           .desc = "receipt error" },
104
105
  { .mask = CHK_EV_TX_DATA,     .name = "tx_data",          .desc = "transmission of data" },
106
  { .mask = CHK_EV_TX_BLK,      .name = "tx_blk",           .desc = "transmission blocked" },
107
  { .mask = CHK_EV_TX_ERR,      .name = "tx_err",           .desc = "transmission error" },
108
109
  {}
110
};
111
112
static const struct name_desc check_trace_lockon_args[4] = {
113
  /* arg1 */ { /* already used by the check */ },
114
  /* arg2 */ { },
115
  /* arg3 */ { },
116
  /* arg4 */ { }
117
};
118
119
static const struct name_desc check_trace_decoding[] = {
120
0
#define CHK_VERB_CLEAN    1
121
  { .name="clean",    .desc="only user-friendly stuff, generally suitable for level \"user\"" },
122
0
#define CHK_VERB_MINIMAL  2
123
  { .name="minimal",  .desc="report info on streams and connectors" },
124
#define CHK_VERB_SIMPLE   3
125
  { .name="simple",   .desc="add info on request and response channels" },
126
0
#define CHK_VERB_ADVANCED 4
127
  { .name="advanced", .desc="add info on channel's buffer for data and developer levels only" },
128
0
#define CHK_VERB_COMPLETE 5
129
  { .name="complete", .desc="add info on channel's buffer" },
130
  { /* end */ }
131
};
132
133
struct trace_source trace_check = {
134
  .name = IST("check"),
135
  .desc = "Health-check",
136
  .arg_def = TRC_ARG1_CHK,  // TRACE()'s first argument is always a stream
137
  .default_cb = check_trace,
138
  .known_events = check_trace_events,
139
  .lockon_args = check_trace_lockon_args,
140
  .decoding = check_trace_decoding,
141
  .report_events = ~0,  // report everything by default
142
};
143
144
#define TRACE_SOURCE &trace_check
145
INITCALL1(STG_REGISTER, trace_register_source, TRACE_SOURCE);
146
147
static inline void check_trace_buf(const struct buffer *buf, size_t ofs, size_t len)
148
0
{
149
0
  size_t block1, block2;
150
0
  int line, ptr, newptr;
151
152
0
  block1 = b_contig_data(buf, ofs);
153
0
  block2 = 0;
154
0
  if (block1 > len)
155
0
    block1 = len;
156
0
  block2 = len - block1;
157
158
0
  ofs = b_peek_ofs(buf, ofs);
159
160
0
  line = 0;
161
0
  ptr = ofs;
162
0
  while (ptr < ofs + block1) {
163
0
    newptr = dump_text_line(&trace_buf, b_orig(buf), b_size(buf), ofs + block1, &line, ptr);
164
0
    if (newptr == ptr)
165
0
      break;
166
0
    ptr = newptr;
167
0
  }
168
169
0
  line = ptr = 0;
170
0
  while (ptr < block2) {
171
0
    newptr = dump_text_line(&trace_buf, b_orig(buf), b_size(buf), block2, &line, ptr);
172
0
    if (newptr == ptr)
173
0
      break;
174
0
    ptr = newptr;
175
0
  }
176
0
}
177
178
/* trace source and events */
179
static void check_trace(enum trace_level level, uint64_t mask,
180
      const struct trace_source *src,
181
      const struct ist where, const struct ist func,
182
      const void *a1, const void *a2, const void *a3, const void *a4)
183
0
{
184
0
  const struct check *check = a1;
185
0
  const struct server *srv = (check ? check->server : NULL);
186
0
  const size_t        *val = a4;
187
0
  const char *res;
188
189
0
  if (!check || src->verbosity < CHK_VERB_CLEAN)
190
0
    return;
191
192
0
  BUG_ON(!srv);
193
0
  chunk_appendf(&trace_buf, " : [%c] SRV=%s",
194
0
          ((check->type == PR_O2_EXT_CHK) ? 'E' : (check->state & CHK_ST_AGENT ? 'A' : 'H')),
195
0
          srv->id);
196
197
0
  chunk_appendf(&trace_buf, " status=%d/%d %s exp=%d",
198
0
          (check->health >= check->rise) ? check->health - check->rise + 1 : check->health,
199
0
          (check->health >= check->rise) ? check->fall : check->rise,
200
0
          (check->health >= check->rise) ? (srv->uweight ? "UP" : "DRAIN") : "DOWN",
201
0
          (check->task->expire ? TICKS_TO_MS(check->task->expire - now_ms) : 0));
202
203
0
  switch (check->result) {
204
0
  case CHK_RES_NEUTRAL: res = "-";     break;
205
0
  case CHK_RES_FAILED:   res = "FAIL"; break;
206
0
  case CHK_RES_PASSED:   res = "PASS"; break;
207
0
  case CHK_RES_CONDPASS: res = "COND"; break;
208
0
  default:               res = "UNK";  break;
209
0
  }
210
211
0
  if (src->verbosity == CHK_VERB_CLEAN)
212
0
    return;
213
214
0
  chunk_appendf(&trace_buf, " - last=%s(%d)/%s(%d)",
215
0
          get_check_status_info(check->status), check->status,
216
0
          res, check->result);
217
218
  /* Display the value to the 4th argument (level > STATE) */
219
0
  if (src->level > TRACE_LEVEL_STATE && val)
220
0
    chunk_appendf(&trace_buf, " - VAL=%lu", (long)*val);
221
222
0
  chunk_appendf(&trace_buf, " check=%p(0x%08x)", check, check->state);
223
224
0
  if (src->verbosity == CHK_VERB_MINIMAL)
225
0
    return;
226
227
228
0
  if (check->sc) {
229
0
    struct connection *conn = sc_conn(check->sc);
230
231
0
    chunk_appendf(&trace_buf, " - conn=%p(0x%08x)", conn, conn ? conn->flags : 0);
232
0
    chunk_appendf(&trace_buf, " sc=%p(0x%08x)", check->sc, check->sc->flags);
233
0
  }
234
235
0
  if (check->type != PR_O2_TCPCHK_CHK)
236
0
    return;
237
238
0
  if (mask & CHK_EV_TCPCHK) {
239
0
    const char *type;
240
241
0
    type = tcpcheck_ruleset_type_to_str(check->tcpcheck->rs);
242
0
    if (check->current_step)
243
0
      chunk_appendf(&trace_buf, " - tcp-check=(%s,%d)", type, tcpcheck_get_step_id(check, NULL));
244
0
    else
245
0
      chunk_appendf(&trace_buf, " - tcp-check=(%s,-)", type);
246
0
  }
247
248
  /* Display bi and bo buffer info (level > USER & verbosity > SIMPLE) */
249
0
  if (src->level > TRACE_LEVEL_USER) {
250
0
    const struct buffer *buf = NULL;
251
252
0
    chunk_appendf(&trace_buf, " bi=%u@%p+%u/%u",
253
0
            (unsigned int)b_data(&check->bi), b_orig(&check->bi),
254
0
            (unsigned int)b_head_ofs(&check->bi), (unsigned int)b_size(&check->bi));
255
0
    chunk_appendf(&trace_buf, " bo=%u@%p+%u/%u",
256
0
            (unsigned int)b_data(&check->bo), b_orig(&check->bo),
257
0
            (unsigned int)b_head_ofs(&check->bo), (unsigned int)b_size(&check->bo));
258
259
0
    if (src->verbosity >= CHK_VERB_ADVANCED && (mask & (CHK_EV_RX)))
260
0
      buf = (b_is_null(&check->bi) ? NULL : &check->bi);
261
0
    else if (src->verbosity >= CHK_VERB_ADVANCED && (mask & (CHK_EV_TX)))
262
0
      buf = (b_is_null(&check->bo) ? NULL : &check->bo);
263
264
0
    if (buf) {
265
0
      if ((check->tcpcheck->rs->flags & TCPCHK_RULES_PROTO_CHK) == TCPCHK_RULES_HTTP_CHK) {
266
0
        int full = (src->verbosity == CHK_VERB_COMPLETE);
267
268
0
        chunk_memcat(&trace_buf, "\n\t", 2);
269
0
        htx_dump(&trace_buf, htxbuf(buf), full);
270
0
      }
271
0
      else {
272
0
        int max = ((src->verbosity == CHK_VERB_COMPLETE) ? 1024 : 256);
273
274
0
        chunk_memcat(&trace_buf, "\n", 1);
275
0
        if (b_data(buf) > max) {
276
0
          check_trace_buf(buf, 0, max);
277
0
          chunk_memcat(&trace_buf, "  ...\n", 6);
278
0
        }
279
0
        else
280
0
          check_trace_buf(buf, 0, b_data(buf));
281
0
      }
282
283
0
    }
284
0
  }
285
286
0
}
287
288
#endif /* USE_TRACE */
289
290
/**************************************************************************/
291
/************************ Handle check results ****************************/
292
/**************************************************************************/
293
struct check_status {
294
  short result;     /* one of SRV_CHK_* */
295
  char *info;     /* human readable short info */
296
  char *desc;     /* long description */
297
};
298
299
struct analyze_status {
300
  char *desc;       /* description */
301
  unsigned char lr[HANA_OBS_SIZE];  /* result for l4/l7: 0 = ignore, 1 - error, 2 - OK */
302
};
303
304
static const struct check_status check_statuses[HCHK_STATUS_SIZE] = {
305
  [HCHK_STATUS_UNKNOWN] = { CHK_RES_UNKNOWN,  "UNK",     "Unknown" },
306
  [HCHK_STATUS_INI] = { CHK_RES_UNKNOWN,  "INI",     "Initializing" },
307
  [HCHK_STATUS_START] = { /* SPECIAL STATUS*/ },
308
309
  /* Below we have finished checks */
310
  [HCHK_STATUS_CHECKED] = { CHK_RES_NEUTRAL,  "CHECKED", "No status change" },
311
  [HCHK_STATUS_HANA]  = { CHK_RES_FAILED,   "HANA",    "Health analyze" },
312
313
  [HCHK_STATUS_SOCKERR] = { CHK_RES_FAILED,   "SOCKERR", "Socket error" },
314
315
  [HCHK_STATUS_L4OK]  = { CHK_RES_PASSED,   "L4OK",    "Layer4 check passed" },
316
  [HCHK_STATUS_L4TOUT]  = { CHK_RES_FAILED,   "L4TOUT",  "Layer4 timeout" },
317
  [HCHK_STATUS_L4CON] = { CHK_RES_FAILED,   "L4CON",   "Layer4 connection problem" },
318
319
  [HCHK_STATUS_L6OK]  = { CHK_RES_PASSED,   "L6OK",    "Layer6 check passed" },
320
  [HCHK_STATUS_L6TOUT]  = { CHK_RES_FAILED,   "L6TOUT",  "Layer6 timeout" },
321
  [HCHK_STATUS_L6RSP] = { CHK_RES_FAILED,   "L6RSP",   "Layer6 invalid response" },
322
323
  [HCHK_STATUS_L7TOUT]  = { CHK_RES_FAILED,   "L7TOUT",  "Layer7 timeout" },
324
  [HCHK_STATUS_L7RSP] = { CHK_RES_FAILED,   "L7RSP",   "Layer7 invalid response" },
325
326
  [HCHK_STATUS_L57DATA] = { /* DUMMY STATUS */ },
327
328
  [HCHK_STATUS_L7OKD] = { CHK_RES_PASSED,   "L7OK",    "Layer7 check passed" },
329
  [HCHK_STATUS_L7OKCD]  = { CHK_RES_CONDPASS, "L7OKC",   "Layer7 check conditionally passed" },
330
  [HCHK_STATUS_L7STS] = { CHK_RES_FAILED,   "L7STS",   "Layer7 wrong status" },
331
332
  [HCHK_STATUS_PROCERR] = { CHK_RES_FAILED,   "PROCERR",  "External check error" },
333
  [HCHK_STATUS_PROCTOUT]  = { CHK_RES_FAILED,   "PROCTOUT", "External check timeout" },
334
  [HCHK_STATUS_PROCOK]  = { CHK_RES_PASSED,   "PROCOK",   "External check passed" },
335
};
336
337
static const struct analyze_status analyze_statuses[HANA_STATUS_SIZE] = {   /* 0: ignore, 1: error, 2: OK */
338
  [HANA_STATUS_UNKNOWN]   = { "Unknown",                         { 0, 0 }},
339
340
  [HANA_STATUS_L4_OK]   = { "L4 successful connection",        { 2, 0 }},
341
  [HANA_STATUS_L4_ERR]    = { "L4 unsuccessful connection",      { 1, 1 }},
342
343
  [HANA_STATUS_HTTP_OK]   = { "Correct http response",           { 0, 2 }},
344
  [HANA_STATUS_HTTP_STS]    = { "Wrong http response",             { 0, 1 }},
345
  [HANA_STATUS_HTTP_HDRRSP] = { "Invalid http response (headers)", { 0, 1 }},
346
  [HANA_STATUS_HTTP_RSP]    = { "Invalid http response",           { 0, 1 }},
347
348
  [HANA_STATUS_HTTP_READ_ERROR] = { "Read error (http)",               { 0, 1 }},
349
  [HANA_STATUS_HTTP_READ_TIMEOUT] = { "Read timeout (http)",             { 0, 1 }},
350
  [HANA_STATUS_HTTP_BROKEN_PIPE]  = { "Close from server (http)",        { 0, 1 }},
351
};
352
353
/* checks if <err> is a real error for errno or one that can be ignored, and
354
 * return 0 for these ones or <err> for real ones.
355
 */
356
static inline int unclean_errno(int err)
357
0
{
358
0
  if (err == EAGAIN || err == EWOULDBLOCK || err == EINPROGRESS ||
359
0
      err == EISCONN || err == EALREADY)
360
0
    return 0;
361
0
  return err;
362
0
}
363
364
/* Converts check_status code to result code */
365
short get_check_status_result(short check_status)
366
0
{
367
0
  if (check_status < HCHK_STATUS_SIZE)
368
0
    return check_statuses[check_status].result;
369
0
  else
370
0
    return check_statuses[HCHK_STATUS_UNKNOWN].result;
371
0
}
372
373
/* Converts check_status code to description */
374
0
const char *get_check_status_description(short check_status) {
375
376
0
  const char *desc;
377
378
0
  if (check_status < HCHK_STATUS_SIZE)
379
0
    desc = check_statuses[check_status].desc;
380
0
  else
381
0
    desc = NULL;
382
383
0
  if (desc && *desc)
384
0
    return desc;
385
0
  else
386
0
    return check_statuses[HCHK_STATUS_UNKNOWN].desc;
387
0
}
388
389
/* Converts check_status code to short info */
390
const char *get_check_status_info(short check_status)
391
0
{
392
0
  const char *info;
393
394
0
  if (check_status < HCHK_STATUS_SIZE)
395
0
    info = check_statuses[check_status].info;
396
0
  else
397
0
    info = NULL;
398
399
0
  if (info && *info)
400
0
    return info;
401
0
  else
402
0
    return check_statuses[HCHK_STATUS_UNKNOWN].info;
403
0
}
404
405
/* Convert analyze_status to description */
406
0
const char *get_analyze_status(short analyze_status) {
407
408
0
  const char *desc;
409
410
0
  if (analyze_status < HANA_STATUS_SIZE)
411
0
    desc = analyze_statuses[analyze_status].desc;
412
0
  else
413
0
    desc = NULL;
414
415
0
  if (desc && *desc)
416
0
    return desc;
417
0
  else
418
0
    return analyze_statuses[HANA_STATUS_UNKNOWN].desc;
419
0
}
420
421
/* append check info to buffer msg */
422
void check_append_info(struct buffer *msg, struct check *check)
423
0
{
424
0
  if (!check)
425
0
    return;
426
0
  chunk_appendf(msg, ", reason: %s", get_check_status_description(check->status));
427
428
0
  if (check->status >= HCHK_STATUS_L57DATA)
429
0
    chunk_appendf(msg, ", code: %d", check->code);
430
431
0
  if (check->desc[0]) {
432
0
    struct buffer src;
433
434
0
    chunk_appendf(msg, ", info: \"");
435
436
0
    chunk_initlen(&src, check->desc, 0, strlen(check->desc));
437
0
    chunk_asciiencode(msg, &src, '"');
438
439
0
    chunk_appendf(msg, "\"");
440
0
  }
441
442
0
  if (check->duration >= 0)
443
0
    chunk_appendf(msg, ", check duration: %ldms", check->duration);
444
0
}
445
446
/* Sets check->status, update check->duration and fill check->result with an
447
 * adequate CHK_RES_* value. The new check->health is computed based on the
448
 * result.
449
 *
450
 * Shows information in logs about failed health check if server is UP or
451
 * succeeded health checks if server is DOWN.
452
 */
453
void set_server_check_status(struct check *check, short status, const char *desc)
454
0
{
455
0
  struct server *s = check->server;
456
0
  short prev_status = check->status;
457
0
  int report = (status != prev_status) ? 1 : 0;
458
459
0
  TRACE_POINT(CHK_EV_HCHK_RUN, check);
460
461
0
  if (status == HCHK_STATUS_START) {
462
0
    check->result = CHK_RES_UNKNOWN;  /* no result yet */
463
0
    check->desc[0] = '\0';
464
0
    check->start = now_ns;
465
466
    /* Reset unique_id. */
467
0
    pool_free(pool_head_uniqueid, istptr(check->unique_id));
468
0
    check->unique_id = IST_NULL;
469
470
0
    return;
471
0
  }
472
473
0
  if (!check->status)
474
0
    return;
475
476
0
  if (desc && *desc) {
477
0
    strncpy(check->desc, desc, HCHK_DESC_LEN-1);
478
0
    check->desc[HCHK_DESC_LEN-1] = '\0';
479
0
  } else
480
0
    check->desc[0] = '\0';
481
482
0
  check->status = status;
483
0
  if (check_statuses[status].result)
484
0
    check->result = check_statuses[status].result;
485
486
0
  if (status == HCHK_STATUS_HANA)
487
0
    check->duration = -1;
488
0
  else if (check->start) {
489
    /* set_server_check_status() may be called more than once */
490
0
    check->duration = ns_to_ms(now_ns - check->start);
491
0
    check->start = 0;
492
0
  }
493
494
  /* no change is expected if no state change occurred */
495
0
  if (check->result == CHK_RES_NEUTRAL)
496
0
    return;
497
498
  /* If the check was really just sending a mail, it won't have an
499
   * associated server, so we're done now.
500
   */
501
0
  if (!s)
502
0
      return;
503
504
0
  switch (check->result) {
505
0
  case CHK_RES_FAILED:
506
    /* Failure to connect to the agent as a secondary check should not
507
     * cause the server to be marked down.
508
     */
509
0
    if ((!(check->state & CHK_ST_AGENT) ||
510
0
        (check->status >= HCHK_STATUS_L57DATA)) &&
511
0
        (check->health > 0)) {
512
0
      if (s->counters.shared.tg)
513
0
        _HA_ATOMIC_INC(&s->counters.shared.tg[tgid - 1]->failed_checks);
514
0
      report = 1;
515
0
      check->health--;
516
0
      if (check->health < check->rise)
517
0
        check->health = 0;
518
0
    }
519
0
    break;
520
521
0
  case CHK_RES_PASSED:
522
0
  case CHK_RES_CONDPASS:
523
0
    if (check->health < check->rise + check->fall - 1) {
524
0
      report = 1;
525
0
      check->health++;
526
527
0
      if (check->health >= check->rise)
528
0
        check->health = check->rise + check->fall - 1; /* OK now */
529
0
    }
530
531
    /* clear consecutive_errors if observing is enabled */
532
0
    if (s->onerror)
533
0
      HA_ATOMIC_STORE(&s->consecutive_errors, 0);
534
0
    break;
535
536
0
  default:
537
0
    break;
538
0
  }
539
540
0
  if (report)
541
0
    srv_event_hdl_publish_check(s, check);
542
543
0
  if (s->proxy->options2 & PR_O2_LOGHCHKS && report) {
544
0
    chunk_printf(&trash,
545
0
                 "%s check for %sserver %s/%s %s%s",
546
0
           (check->state & CHK_ST_AGENT) ? "Agent" : "Health",
547
0
                 s->flags & SRV_F_BACKUP ? "backup " : "",
548
0
                 s->proxy->id, s->id,
549
0
                 (check->result == CHK_RES_CONDPASS) ? "conditionally ":"",
550
0
                 (check->result >= CHK_RES_PASSED)   ? "succeeded" : "failed");
551
552
0
    check_append_info(&trash, check);
553
554
0
    chunk_appendf(&trash, ", status: %d/%d %s",
555
0
                 (check->health >= check->rise) ? check->health - check->rise + 1 : check->health,
556
0
                 (check->health >= check->rise) ? check->fall : check->rise,
557
0
           (check->health >= check->rise) ? (s->uweight ? "UP" : "DRAIN") : "DOWN");
558
559
0
    ha_warning("%s.\n", trash.area);
560
0
    send_log(s->proxy, LOG_NOTICE, "%s.\n", trash.area);
561
0
  }
562
0
}
563
564
static inline enum srv_op_st_chg_cause check_notify_cause(struct check *check)
565
0
{
566
0
  struct server *s = check->server;
567
568
  /* We only report a cause for the check if we did not do so previously */
569
0
  if (!s->track && !(s->proxy->options2 & PR_O2_LOGHCHKS))
570
0
    return (check->state & CHK_ST_AGENT) ? SRV_OP_STCHGC_AGENT : SRV_OP_STCHGC_HEALTH;
571
0
  return SRV_OP_STCHGC_NONE;
572
0
}
573
574
/* Marks the check <check>'s server down if the current check is already failed
575
 * and the server is not down yet nor in maintenance.
576
 */
577
void check_notify_failure(struct check *check)
578
0
{
579
0
  struct server *s = check->server;
580
581
  /* The agent secondary check should only cause a server to be marked
582
   * as down if check->status is HCHK_STATUS_L7STS, which indicates
583
   * that the agent returned "fail", "stopped" or "down".
584
   * The implication here is that failure to connect to the agent
585
   * as a secondary check should not cause the server to be marked
586
   * down. */
587
0
  if ((check->state & CHK_ST_AGENT) && check->status != HCHK_STATUS_L7STS)
588
0
    return;
589
590
0
  if (check->health > 0)
591
0
    return;
592
593
0
  TRACE_STATE("health-check failed, set server DOWN", CHK_EV_HCHK_END|CHK_EV_HCHK_ERR, check);
594
0
  srv_set_stopped(s, check_notify_cause(check));
595
0
}
596
597
/* Marks the check <check> as valid and tries to set its server up, provided
598
 * it isn't in maintenance, it is not tracking a down server and other checks
599
 * comply. The rule is simple : by default, a server is up, unless any of the
600
 * following conditions is true :
601
 *   - health check failed (check->health < rise)
602
 *   - agent check failed (agent->health < rise)
603
 *   - the server tracks a down server (track && track->state == STOPPED)
604
 * Note that if the server has a slowstart, it will switch to STARTING instead
605
 * of RUNNING. Also, only the health checks support the nolb mode, so the
606
 * agent's success may not take the server out of this mode.
607
 */
608
void check_notify_success(struct check *check)
609
0
{
610
0
  struct server *s = check->server;
611
612
0
  if (s->next_admin & SRV_ADMF_MAINT)
613
0
    return;
614
615
0
  if (s->track && s->track->next_state == SRV_ST_STOPPED)
616
0
    return;
617
618
0
  if ((s->check.state & CHK_ST_ENABLED) && (s->check.health < s->check.rise))
619
0
    return;
620
621
0
  if ((s->agent.state & CHK_ST_ENABLED) && (s->agent.health < s->agent.rise))
622
0
    return;
623
624
0
  if ((check->state & CHK_ST_AGENT) && s->next_state == SRV_ST_STOPPING)
625
0
    return;
626
627
0
  TRACE_STATE("health-check succeeded, set server RUNNING", CHK_EV_HCHK_END|CHK_EV_HCHK_SUCC, check);
628
0
  srv_set_running(s, check_notify_cause(check));
629
0
}
630
631
/* Marks the check <check> as valid and tries to set its server into stopping mode
632
 * if it was running or starting, and provided it isn't in maintenance and other
633
 * checks comply. The conditions for the server to be marked in stopping mode are
634
 * the same as for it to be turned up. Also, only the health checks support the
635
 * nolb mode.
636
 */
637
void check_notify_stopping(struct check *check)
638
0
{
639
0
  struct server *s = check->server;
640
641
0
  if (s->next_admin & SRV_ADMF_MAINT)
642
0
    return;
643
644
0
  if (check->state & CHK_ST_AGENT)
645
0
    return;
646
647
0
  if (s->track && s->track->next_state == SRV_ST_STOPPED)
648
0
    return;
649
650
0
  if ((s->check.state & CHK_ST_ENABLED) && (s->check.health < s->check.rise))
651
0
    return;
652
653
0
  if ((s->agent.state & CHK_ST_ENABLED) && (s->agent.health < s->agent.rise))
654
0
    return;
655
656
0
  TRACE_STATE("health-check condionnaly succeeded, set server STOPPING", CHK_EV_HCHK_END|CHK_EV_HCHK_SUCC, check);
657
0
  srv_set_stopping(s, check_notify_cause(check));
658
0
}
659
660
/* note: use health_adjust() only, which first checks that the observe mode is
661
 * enabled. This will take the server lock if needed.
662
 */
663
void __health_adjust(struct server *s, short status)
664
0
{
665
0
  int failed;
666
667
0
  if (s->observe >= HANA_OBS_SIZE)
668
0
    return;
669
670
0
  if (status >= HANA_STATUS_SIZE || !analyze_statuses[status].desc)
671
0
    return;
672
673
0
  switch (analyze_statuses[status].lr[s->observe - 1]) {
674
0
    case 1:
675
0
      failed = 1;
676
0
      break;
677
678
0
    case 2:
679
0
      failed = 0;
680
0
      break;
681
682
0
    default:
683
0
      return;
684
0
  }
685
686
0
  if (!failed) {
687
    /* good: clear consecutive_errors */
688
0
    HA_ATOMIC_STORE(&s->consecutive_errors, 0);
689
0
    return;
690
0
  }
691
692
0
  if (HA_ATOMIC_ADD_FETCH(&s->consecutive_errors, 1) < s->consecutive_errors_limit)
693
0
    return;
694
695
0
  chunk_printf(&trash, "Detected %d consecutive errors, last one was: %s",
696
0
               HA_ATOMIC_LOAD(&s->consecutive_errors), get_analyze_status(status));
697
698
0
  HA_SPIN_LOCK(SERVER_LOCK, &s->lock);
699
700
  /* force fastinter for upcoming check
701
   * (does nothing if fastinter is not enabled)
702
   */
703
0
  s->check.state |= CHK_ST_FASTINTER;
704
705
0
  switch (s->onerror) {
706
0
    case HANA_ONERR_FASTINTER:
707
    /* force fastinter - nothing to do here as all modes force it */
708
0
      break;
709
710
0
    case HANA_ONERR_SUDDTH:
711
    /* simulate a pre-fatal failed health check */
712
0
      if (s->check.health > s->check.rise)
713
0
        s->check.health = s->check.rise + 1;
714
715
0
      __fallthrough;
716
717
0
    case HANA_ONERR_FAILCHK:
718
    /* simulate a failed health check */
719
0
      set_server_check_status(&s->check, HCHK_STATUS_HANA,
720
0
            trash.area);
721
0
      check_notify_failure(&s->check);
722
0
      break;
723
724
0
    case HANA_ONERR_MARKDWN:
725
    /* mark server down */
726
0
      s->check.health = s->check.rise;
727
0
      set_server_check_status(&s->check, HCHK_STATUS_HANA,
728
0
            trash.area);
729
0
      check_notify_failure(&s->check);
730
0
      break;
731
732
0
    default:
733
      /* write a warning? */
734
0
      break;
735
0
  }
736
737
0
  HA_SPIN_UNLOCK(SERVER_LOCK, &s->lock);
738
739
0
  HA_ATOMIC_STORE(&s->consecutive_errors, 0);
740
0
  if (s->counters.shared.tg)
741
0
    _HA_ATOMIC_INC(&s->counters.shared.tg[tgid - 1]->failed_hana);
742
743
0
  if (s->check.fastinter) {
744
    /* timer might need to be advanced, it might also already be
745
     * running in another thread. Let's just wake the task up, it
746
     * will automatically adjust its timer.
747
     */
748
0
    task_wakeup(s->check.task, TASK_WOKEN_MSG);
749
0
  }
750
0
}
751
752
/* Checks the connection. If an error has already been reported or the socket is
753
 * closed, keep errno intact as it is supposed to contain the valid error code.
754
 * If no error is reported, check the socket's error queue using getsockopt().
755
 * Warning, this must be done only once when returning from poll, and never
756
 * after an I/O error was attempted, otherwise the error queue might contain
757
 * inconsistent errors. If an error is detected, the CO_FL_ERROR is set on the
758
 * socket. Returns non-zero if an error was reported, zero if everything is
759
 * clean (including a properly closed socket).
760
 */
761
static int retrieve_errno_from_socket(struct connection *conn)
762
0
{
763
0
  int skerr;
764
0
  socklen_t lskerr = sizeof(skerr);
765
766
0
  if (conn->flags & CO_FL_ERROR && (unclean_errno(errno) || !conn->ctrl))
767
0
    return 1;
768
769
0
  if (!conn_ctrl_ready(conn))
770
0
    return 0;
771
772
0
  BUG_ON(conn->flags & CO_FL_FDLESS);
773
774
0
  if (getsockopt(conn->handle.fd, SOL_SOCKET, SO_ERROR, &skerr, &lskerr) == 0)
775
0
    errno = skerr;
776
777
0
  errno = unclean_errno(errno);
778
779
0
  if (!errno) {
780
    /* we could not retrieve an error, that does not mean there is
781
     * none. Just don't change anything and only report the prior
782
     * error if any.
783
     */
784
0
    if (conn->flags & CO_FL_ERROR)
785
0
      return 1;
786
0
    else
787
0
      return 0;
788
0
  }
789
790
0
  conn->flags |= CO_FL_ERROR | CO_FL_SOCK_WR_SH | CO_FL_SOCK_RD_SH;
791
0
  return 1;
792
0
}
793
794
/* Tries to collect as much information as possible on the connection status,
795
 * and adjust the server status accordingly. It may make use of <errno_bck>
796
 * if non-null when the caller is absolutely certain of its validity (eg:
797
 * checked just after a syscall). If the caller doesn't have a valid errno,
798
 * it can pass zero, and retrieve_errno_from_socket() will be called to try
799
 * to extract errno from the socket. If no error is reported, it will consider
800
 * the <expired> flag. This is intended to be used when a connection error was
801
 * reported in conn->flags or when a timeout was reported in <expired>. The
802
 * function takes care of not updating a server status which was already set.
803
 * All situations where at least one of <expired> or CO_FL_ERROR are set
804
 * produce a status.
805
 */
806
void chk_report_conn_err(struct check *check, int errno_bck, int expired)
807
0
{
808
0
  struct stconn *sc = check->sc;
809
0
  struct connection *conn = sc_conn(sc);
810
0
  const char *err_msg;
811
0
  struct buffer *chk;
812
0
  int step;
813
814
0
  if (check->result != CHK_RES_UNKNOWN) {
815
0
    return;
816
0
  }
817
818
0
  errno = unclean_errno(errno_bck);
819
0
  if (conn && !errno)
820
0
    retrieve_errno_from_socket(conn);
821
822
0
  TRACE_ENTER(CHK_EV_HCHK_END|CHK_EV_HCHK_ERR, check, 0, 0, (size_t[]){expired});
823
824
  /* we'll try to build a meaningful error message depending on the
825
   * context of the error possibly present in conn->err_code, and the
826
   * socket error possibly collected above. This is useful to know the
827
   * exact step of the L6 layer (eg: SSL handshake).
828
   */
829
0
  chk = get_trash_chunk();
830
831
0
  if (check->type == PR_O2_TCPCHK_CHK &&
832
0
      (check->tcpcheck->rs->flags & TCPCHK_RULES_PROTO_CHK) == TCPCHK_RULES_TCP_CHK) {
833
0
    step = tcpcheck_get_step_id(check, NULL);
834
0
    if (!step) {
835
0
      TRACE_DEVEL("initial connection failure", CHK_EV_HCHK_END|CHK_EV_HCHK_ERR, check);
836
0
      chunk_printf(chk, " at initial connection step of tcp-check");
837
0
    }
838
0
    else {
839
0
      chunk_printf(chk, " at step %d of tcp-check", step);
840
      /* we were looking for a string */
841
0
      if (check->current_step && check->current_step->action == TCPCHK_ACT_CONNECT) {
842
0
        if (check->current_step->connect.port)
843
0
          chunk_appendf(chk, " (connect port %d)" ,check->current_step->connect.port);
844
0
        else
845
0
          chunk_appendf(chk, " (connect)");
846
0
        TRACE_DEVEL("connection failure", CHK_EV_HCHK_END|CHK_EV_HCHK_ERR, check);
847
0
      }
848
0
      else if (check->current_step && check->current_step->action == TCPCHK_ACT_EXPECT) {
849
0
        struct tcpcheck_expect *expect = &check->current_step->expect;
850
851
0
        switch (expect->type) {
852
0
        case TCPCHK_EXPECT_STRING:
853
0
          chunk_appendf(chk, " (expect string '%.*s')", (unsigned int)istlen(expect->data), istptr(expect->data));
854
0
          break;
855
0
        case TCPCHK_EXPECT_BINARY:
856
0
          chunk_appendf(chk, " (expect binary '");
857
0
          dump_binary(chk, istptr(expect->data), (int)istlen(expect->data));
858
0
          chunk_appendf(chk, "')");
859
0
          break;
860
0
        case TCPCHK_EXPECT_STRING_REGEX:
861
0
          chunk_appendf(chk, " (expect regex)");
862
0
          break;
863
0
        case TCPCHK_EXPECT_BINARY_REGEX:
864
0
          chunk_appendf(chk, " (expect binary regex)");
865
0
          break;
866
0
        case TCPCHK_EXPECT_STRING_LF:
867
0
          chunk_appendf(chk, " (expect log-format string)");
868
0
          break;
869
0
        case TCPCHK_EXPECT_BINARY_LF:
870
0
          chunk_appendf(chk, " (expect log-format binary)");
871
0
          break;
872
0
        case TCPCHK_EXPECT_HTTP_STATUS:
873
0
          chunk_appendf(chk, " (expect HTTP status codes)");
874
0
          break;
875
0
        case TCPCHK_EXPECT_HTTP_STATUS_REGEX:
876
0
          chunk_appendf(chk, " (expect HTTP status regex)");
877
0
          break;
878
0
        case TCPCHK_EXPECT_HTTP_HEADER:
879
0
          chunk_appendf(chk, " (expect HTTP header pattern)");
880
0
          break;
881
0
        case TCPCHK_EXPECT_HTTP_BODY:
882
0
          chunk_appendf(chk, " (expect HTTP body content '%.*s')", (unsigned int)istlen(expect->data), istptr(expect->data));
883
0
          break;
884
0
        case TCPCHK_EXPECT_HTTP_BODY_REGEX:
885
0
          chunk_appendf(chk, " (expect HTTP body regex)");
886
0
          break;
887
0
        case TCPCHK_EXPECT_HTTP_BODY_LF:
888
0
          chunk_appendf(chk, " (expect log-format HTTP body)");
889
0
          break;
890
0
        case TCPCHK_EXPECT_CUSTOM:
891
0
          chunk_appendf(chk, " (expect custom function)");
892
0
          break;
893
0
        case TCPCHK_EXPECT_UNDEF:
894
0
          chunk_appendf(chk, " (undefined expect!)");
895
0
          break;
896
0
        }
897
0
        TRACE_DEVEL("expect rule failed", CHK_EV_HCHK_END|CHK_EV_HCHK_ERR, check);
898
0
      }
899
0
      else if (check->current_step && check->current_step->action == TCPCHK_ACT_SEND) {
900
0
        chunk_appendf(chk, " (send)");
901
0
        TRACE_DEVEL("send rule failed", CHK_EV_HCHK_END|CHK_EV_HCHK_ERR, check);
902
0
      }
903
904
0
      if (check->current_step && check->current_step->comment)
905
0
        chunk_appendf(chk, " comment: '%s'", check->current_step->comment);
906
0
    }
907
0
  }
908
909
0
  if (conn && conn->err_code) {
910
0
    if (unclean_errno(errno))
911
0
      chunk_printf(&trash, "%s (%s)%s", conn_err_code_str(conn), strerror(errno),
912
0
             chk->area);
913
0
    else
914
0
      chunk_printf(&trash, "%s%s", conn_err_code_str(conn),
915
0
             chk->area);
916
0
    err_msg = trash.area;
917
0
  }
918
0
  else {
919
0
    if (unclean_errno(errno)) {
920
0
      chunk_printf(&trash, "%s%s", strerror(errno),
921
0
             chk->area);
922
0
      err_msg = trash.area;
923
0
    }
924
0
    else {
925
0
      err_msg = chk->area;
926
0
    }
927
0
  }
928
929
0
  if (check->state & CHK_ST_PORT_MISS) {
930
    /* NOTE: this is reported after <fall> tries */
931
0
    set_server_check_status(check, HCHK_STATUS_SOCKERR, err_msg);
932
0
  }
933
934
0
  if (!conn || !conn->ctrl) {
935
    /* error before any connection attempt (connection allocation error or no control layer) */
936
0
    set_server_check_status(check, HCHK_STATUS_SOCKERR, err_msg);
937
0
  }
938
0
  else if (conn->flags & CO_FL_WAIT_L4_CONN) {
939
    /* L4 not established (yet) */
940
0
    if (conn->flags & CO_FL_ERROR || sc_ep_test(sc, SE_FL_ERROR))
941
0
      set_server_check_status(check, HCHK_STATUS_L4CON, err_msg);
942
0
    else if (expired)
943
0
      set_server_check_status(check, HCHK_STATUS_L4TOUT, err_msg);
944
945
    /*
946
     * might be due to a server IP change.
947
     * Let's trigger a DNS resolution if none are currently running.
948
     */
949
0
    if (check->server)
950
0
      resolv_trigger_resolution(check->server->resolv_requester);
951
952
0
  }
953
0
  else if (conn->flags & CO_FL_WAIT_L6_CONN) {
954
    /* L6 not established (yet) */
955
0
    if (conn->flags & CO_FL_ERROR || sc_ep_test(sc, SE_FL_ERROR))
956
0
      set_server_check_status(check, HCHK_STATUS_L6RSP, err_msg);
957
0
    else if (expired)
958
0
      set_server_check_status(check, HCHK_STATUS_L6TOUT, err_msg);
959
0
  }
960
0
  else if (conn->flags & CO_FL_ERROR || sc_ep_test(sc, SE_FL_ERROR)) {
961
    /* I/O error after connection was established and before we could diagnose */
962
0
    set_server_check_status(check, HCHK_STATUS_SOCKERR, err_msg);
963
0
  }
964
0
  else if (expired) {
965
0
    enum healthcheck_status tout = HCHK_STATUS_L7TOUT;
966
967
    /* connection established but expired check */
968
0
    if (check->current_step && check->current_step->action == TCPCHK_ACT_EXPECT &&
969
0
        check->current_step->expect.tout_status != HCHK_STATUS_UNKNOWN)
970
0
      tout = check->current_step->expect.tout_status;
971
0
    set_server_check_status(check, tout, err_msg);
972
0
  }
973
974
0
  if (check->result == CHK_RES_UNKNOWN) {
975
    /* No other reason found, report a socket error (may be an internal or a ressournce error) */
976
0
    set_server_check_status(check, HCHK_STATUS_SOCKERR, err_msg);
977
0
  }
978
979
0
  TRACE_LEAVE(CHK_EV_HCHK_END|CHK_EV_HCHK_ERR, check);
980
0
  return;
981
0
}
982
983
984
/* Builds the server state header used by HTTP health-checks */
985
int httpchk_build_status_header(struct server *s, struct buffer *buf)
986
0
{
987
0
  int sv_state;
988
0
  int ratio;
989
0
  char addr[46];
990
0
  char port[6];
991
0
  const char *srv_hlt_st[7] = { "DOWN", "DOWN %d/%d",
992
0
              "UP %d/%d", "UP",
993
0
              "NOLB %d/%d", "NOLB",
994
0
              "no check" };
995
0
  unsigned long last_change = s->last_change;
996
997
0
  if (!(s->check.state & CHK_ST_ENABLED))
998
0
    sv_state = 6;
999
0
  else if (s->cur_state != SRV_ST_STOPPED) {
1000
0
    if (s->check.health == s->check.rise + s->check.fall - 1)
1001
0
      sv_state = 3; /* UP */
1002
0
    else
1003
0
      sv_state = 2; /* going down */
1004
1005
0
    if (s->cur_state == SRV_ST_STOPPING)
1006
0
      sv_state += 2;
1007
0
  } else {
1008
0
    if (s->check.health)
1009
0
      sv_state = 1; /* going up */
1010
0
    else
1011
0
      sv_state = 0; /* DOWN */
1012
0
  }
1013
1014
0
  chunk_appendf(buf, srv_hlt_st[sv_state],
1015
0
          (s->cur_state != SRV_ST_STOPPED) ? (s->check.health - s->check.rise + 1) : (s->check.health),
1016
0
          (s->cur_state != SRV_ST_STOPPED) ? (s->check.fall) : (s->check.rise));
1017
1018
0
  addr_to_str(&s->addr, addr, sizeof(addr));
1019
0
  if (s->addr.ss_family == AF_INET || s->addr.ss_family == AF_INET6)
1020
0
    snprintf(port, sizeof(port), "%u", s->svc_port);
1021
0
  else
1022
0
    *port = 0;
1023
1024
0
  chunk_appendf(buf, "; address=%s; port=%s; name=%s/%s; node=%s; weight=%d/%d; scur=%d/%d; qcur=%d",
1025
0
          addr, port, s->proxy->id, s->id,
1026
0
          global.node,
1027
0
          (s->cur_eweight * s->proxy->lbprm.wmult + s->proxy->lbprm.wdiv - 1) / s->proxy->lbprm.wdiv,
1028
0
          (s->proxy->lbprm.tot_weight * s->proxy->lbprm.wmult + s->proxy->lbprm.wdiv - 1) / s->proxy->lbprm.wdiv,
1029
0
          s->cur_sess, s->proxy->beconn - s->proxy->queueslength,
1030
0
          s->queueslength);
1031
1032
0
  if ((s->cur_state == SRV_ST_STARTING) &&
1033
0
      ns_to_sec(now_ns) < last_change + s->slowstart &&
1034
0
      ns_to_sec(now_ns) >= last_change) {
1035
0
    ratio = MAX(1, 100 * (ns_to_sec(now_ns) - last_change) / s->slowstart);
1036
0
    chunk_appendf(buf, "; throttle=%d%%", ratio);
1037
0
  }
1038
1039
0
  return b_data(buf);
1040
0
}
1041
1042
/**************************************************************************/
1043
/***************** Health-checks based on connections *********************/
1044
/**************************************************************************/
1045
/* This function handles connection status updates including errors. If
1046
 * necessary, it wakes the check task up.
1047
 */
1048
struct task *srv_chk_io_cb(struct task *t, void *ctx, unsigned int state)
1049
0
{
1050
0
  struct stconn *sc = ctx;
1051
0
  struct connection *conn;
1052
0
  struct check *check = __sc_check(sc);
1053
0
  int ret = 0;
1054
1055
0
  BUG_ON(!check->server);
1056
1057
0
  TRACE_ENTER(CHK_EV_HCHK_WAKE, check);
1058
0
  if (check->result != CHK_RES_UNKNOWN)
1059
0
    goto end;
1060
1061
0
  HA_SPIN_LOCK(SERVER_LOCK, &check->server->lock);
1062
1063
  /* we may have to make progress on the TCP checks */
1064
0
  ret = tcpcheck_main(check);
1065
1066
0
  sc = check->sc;
1067
0
  conn = sc_conn(sc);
1068
1069
0
  if (unlikely(!conn || conn->flags & CO_FL_ERROR || sc_ep_test(sc, SE_FL_ERROR))) {
1070
    /* We may get error reports bypassing the I/O handlers, typically
1071
     * the case when sending a pure TCP check which fails, then the I/O
1072
     * handlers above are not called. This is completely handled by the
1073
     * main processing task so let's simply wake it up. If we get here,
1074
     * we expect errno to still be valid.
1075
     */
1076
0
    TRACE_ERROR("report connection error", CHK_EV_HCHK_WAKE|CHK_EV_HCHK_END|CHK_EV_HCHK_ERR, check);
1077
0
    chk_report_conn_err(check, errno, 0);
1078
0
    task_wakeup(check->task, TASK_WOKEN_IO);
1079
0
  }
1080
1081
0
  if (check->result != CHK_RES_UNKNOWN || ret == -1) {
1082
    /* Check complete or aborted. Wake the check task up to be sure
1083
     * the result is handled ASAP. */
1084
0
    ret = -1;
1085
0
    task_wakeup(check->task, TASK_WOKEN_IO);
1086
0
  }
1087
0
  else {
1088
    /* Check in progress. Queue it to eventually handle timeout
1089
     * update */
1090
0
    task_queue(check->task);
1091
0
  }
1092
1093
0
  HA_SPIN_UNLOCK(SERVER_LOCK, &check->server->lock);
1094
1095
0
  end:
1096
0
  TRACE_LEAVE(CHK_EV_HCHK_WAKE, check);
1097
0
  return t;
1098
0
}
1099
1100
/* returns <0, 0, >0 if check thread 1 is respectively less loaded than,
1101
 * equally as, or more loaded than thread 2. This is made to decide on
1102
 * migrations so a margin is applied in either direction. For ease of
1103
 * remembering the direction, consider this returns load1 - load2.
1104
 */
1105
static inline int check_thread_cmp_load(int thr1, int thr2)
1106
0
{
1107
0
  uint t1_load = _HA_ATOMIC_LOAD(&ha_thread_ctx[thr1].rq_total);
1108
0
  uint t1_act  = _HA_ATOMIC_LOAD(&ha_thread_ctx[thr1].active_checks);
1109
0
  uint t2_load = _HA_ATOMIC_LOAD(&ha_thread_ctx[thr2].rq_total);
1110
0
  uint t2_act  = _HA_ATOMIC_LOAD(&ha_thread_ctx[thr2].active_checks);
1111
1112
  /* twice as more active checks is a significant difference */
1113
0
  if (t1_act * 2 < t2_act)
1114
0
    return -1;
1115
1116
0
  if (t2_act * 2 < t1_act)
1117
0
    return 1;
1118
1119
  /* twice as more rqload with more checks is also a significant
1120
   * difference.
1121
   */
1122
0
  if (t1_act <= t2_act && t1_load * 2 < t2_load)
1123
0
    return -1;
1124
1125
0
  if (t2_act <= t1_act && t2_load * 2 < t1_load)
1126
0
    return 1;
1127
1128
  /* otherwise they're roughly equal */
1129
0
  return 0;
1130
0
}
1131
1132
/* returns <0, 0, >0 if check thread 1's active checks count is respectively
1133
 * higher than, equal, or lower than thread 2's. This is made to decide on
1134
 * forced migrations upon overload, so only a very little margin is applied
1135
 * here (~1%). For ease of remembering the direction, consider this returns
1136
 * active1 - active2.
1137
 */
1138
static inline int check_thread_cmp_active(int thr1, int thr2)
1139
0
{
1140
0
  uint t1_act  = _HA_ATOMIC_LOAD(&ha_thread_ctx[thr1].active_checks);
1141
0
  uint t2_act  = _HA_ATOMIC_LOAD(&ha_thread_ctx[thr2].active_checks);
1142
1143
0
  if (t1_act * 128 >= t2_act * 129)
1144
0
    return 1;
1145
0
  if (t2_act * 128 >= t1_act * 129)
1146
0
    return -1;
1147
0
  return 0;
1148
0
}
1149
1150
1151
/* manages a server health-check that uses a connection. Returns
1152
 * the time the task accepts to wait, or TIME_ETERNITY for infinity.
1153
 *
1154
 * Please do NOT place any return statement in this function and only leave
1155
 * via the out_unlock label.
1156
 */
1157
struct task *process_chk_conn(struct task *t, void *context, unsigned int state)
1158
0
{
1159
0
  struct check *check = context;
1160
0
  struct proxy *proxy = check->proxy;
1161
0
  struct stconn *sc;
1162
0
  struct connection *conn;
1163
0
  int rv;
1164
0
  int expired = tick_is_expired(t->expire, now_ms);
1165
1166
0
  TRACE_ENTER(CHK_EV_TASK_WAKE, check);
1167
1168
0
  if (check->state & CHK_ST_SLEEPING) {
1169
    /* This check just restarted. It's still time to verify if
1170
     * we're on an overloaded thread or if a more suitable one is
1171
     * available. This helps spread the load over the available
1172
     * threads, without migrating too often. For this we'll check
1173
     * our load, and pick a random thread, check if it has less
1174
     * than half of the current thread's load, and if so we'll
1175
     * bounce the task there. It's possible because it's not yet
1176
     * tied to the current thread. The other thread will not bounce
1177
     * the task again because we're setting CHK_ST_READY indicating
1178
     * a migration.
1179
     */
1180
0
    uint run_checks = _HA_ATOMIC_LOAD(&th_ctx->running_checks);
1181
0
    uint my_load = HA_ATOMIC_LOAD(&th_ctx->rq_total);
1182
0
    uint attempts = MIN(global.nbthread, 3);
1183
1184
0
    if (check->state & CHK_ST_READY) {
1185
      /* check was migrated, active already counted */
1186
0
      activity[tid].check_adopted++;
1187
0
    }
1188
0
    else {
1189
      /* first wakeup, let's check if another thread is less loaded
1190
       * than this one in order to smooth the load. If the current
1191
       * thread is not yet overloaded, we attempt an opportunistic
1192
       * migration to another thread that is not full and that is
1193
       * significantly less loaded. And if the current thread is
1194
       * already overloaded, we attempt a forced migration to a
1195
       * thread with less active checks. We try at most 3 random
1196
       * other thread.
1197
       */
1198
0
      while (attempts-- > 0 &&
1199
0
             (!LIST_ISEMPTY(&th_ctx->queued_checks) || my_load >= 3) &&
1200
0
             _HA_ATOMIC_LOAD(&th_ctx->active_checks) >= 3) {
1201
0
        uint new_tid  = statistical_prng_range(global.nbthread);
1202
1203
0
        if (new_tid == tid)
1204
0
          continue;
1205
1206
0
        ALREADY_CHECKED(new_tid);
1207
1208
0
        if (check_thread_cmp_active(tid, new_tid) > 0 &&
1209
0
            (run_checks >= global.tune.max_checks_per_thread ||
1210
0
             check_thread_cmp_load(tid, new_tid) > 0)) {
1211
          /* Found one. Let's migrate the task over there. We have to
1212
           * remove it from the WQ first and kill its expire time
1213
           * otherwise the scheduler will reinsert it and trigger a
1214
           * BUG_ON() as we're not allowed to call task_queue() for a
1215
           * foreign thread. The recipient will restore the expiration.
1216
           */
1217
0
          check->state |= CHK_ST_READY;
1218
0
          HA_ATOMIC_INC(&ha_thread_ctx[new_tid].active_checks);
1219
0
          task_unlink_wq(t);
1220
0
          t->expire = TICK_ETERNITY;
1221
0
          task_set_thread(t, new_tid);
1222
0
          task_wakeup(t, TASK_WOKEN_MSG);
1223
0
          TRACE_LEAVE(CHK_EV_TASK_WAKE, check);
1224
0
          return t;
1225
0
        }
1226
0
      }
1227
      /* check just woke up, count it as active */
1228
0
      _HA_ATOMIC_INC(&th_ctx->active_checks);
1229
0
    }
1230
1231
    /* OK we're keeping it so this check is ours now */
1232
0
    task_set_thread(t, tid);
1233
0
    check->state &= ~CHK_ST_SLEEPING;
1234
1235
    /* if we just woke up and the thread is full of running, or
1236
     * already has others waiting, we might have to wait in queue
1237
     * (for health checks only). This means !SLEEPING && !READY.
1238
     */
1239
0
    if (check->server &&
1240
0
        (!LIST_ISEMPTY(&th_ctx->queued_checks) ||
1241
0
         (global.tune.max_checks_per_thread &&
1242
0
          _HA_ATOMIC_LOAD(&th_ctx->running_checks) >= global.tune.max_checks_per_thread))) {
1243
0
      TRACE_DEVEL("health-check queued", CHK_EV_TASK_WAKE, check);
1244
0
      t->expire = TICK_ETERNITY;
1245
0
      LIST_APPEND(&th_ctx->queued_checks, &check->check_queue);
1246
1247
      /* reset fastinter flag (if set) so that srv_getinter()
1248
       * only returns fastinter if server health is degraded
1249
       */
1250
0
      check->state &= ~CHK_ST_FASTINTER;
1251
0
      goto out_leave;
1252
0
    }
1253
1254
    /* OK let's run, now we cannot roll back anymore */
1255
0
    check->state |= CHK_ST_READY;
1256
0
    activity[tid].check_started++;
1257
0
    _HA_ATOMIC_INC(&th_ctx->running_checks);
1258
0
  }
1259
1260
  /* at this point, CHK_ST_SLEEPING = 0 and CHK_ST_READY = 1*/
1261
1262
0
  if (check->server)
1263
0
    HA_SPIN_LOCK(SERVER_LOCK, &check->server->lock);
1264
1265
0
  if (!(check->state & (CHK_ST_INPROGRESS|CHK_ST_IN_ALLOC|CHK_ST_OUT_ALLOC))) {
1266
    /* This task might have bounced from another overloaded thread, it
1267
     * needs an expiration timer that was supposed to be now, but that
1268
     * was erased during the bounce.
1269
     */
1270
0
    if (!tick_isset(t->expire)) {
1271
0
      t->expire = tick_add(now_ms, 0);
1272
0
      expired = 0;
1273
0
    }
1274
0
  }
1275
1276
0
  if (unlikely(check->state & CHK_ST_PURGE)) {
1277
0
    TRACE_STATE("health-check state to purge", CHK_EV_TASK_WAKE, check);
1278
0
  }
1279
0
  else if (!(check->state & (CHK_ST_INPROGRESS))) {
1280
    /* no check currently running, but we might have been woken up
1281
     * before the timer's expiration to update it according to a
1282
     * new state (e.g. fastinter), in which case we'll reprogram
1283
     * the new timer.
1284
     */
1285
0
    if (!tick_is_expired(t->expire, now_ms)) { /* woke up too early */
1286
0
      if (check->server) {
1287
0
        int new_exp = tick_add(now_ms, MS_TO_TICKS(srv_getinter(check)));
1288
1289
0
        if (tick_is_expired(new_exp, t->expire)) {
1290
0
          TRACE_STATE("health-check was advanced", CHK_EV_TASK_WAKE, check);
1291
0
          goto update_timer;
1292
0
        }
1293
0
      }
1294
1295
0
      TRACE_STATE("health-check wake up too early", CHK_EV_TASK_WAKE, check);
1296
0
      goto out_unlock;
1297
0
    }
1298
1299
    /* we don't send any health-checks when the proxy is
1300
     * stopped, the server should not be checked or the check
1301
     * is disabled.
1302
     */
1303
0
    if (((check->state & (CHK_ST_ENABLED | CHK_ST_PAUSED)) != CHK_ST_ENABLED) ||
1304
0
        (proxy->flags & (PR_FL_DISABLED|PR_FL_STOPPED))) {
1305
0
      TRACE_STATE("health-check paused or disabled", CHK_EV_TASK_WAKE, check);
1306
0
      goto reschedule;
1307
0
    }
1308
1309
    /* we'll initiate a new check */
1310
0
    set_server_check_status(check, HCHK_STATUS_START, NULL);
1311
1312
0
    check->state |= CHK_ST_INPROGRESS;
1313
0
    TRACE_STATE("init new health-check", CHK_EV_TASK_WAKE|CHK_EV_HCHK_START, check);
1314
1315
0
    check->current_step = NULL;
1316
1317
0
    check->sc = sc_new_from_check(check);
1318
0
    if (!check->sc) {
1319
0
      set_server_check_status(check, HCHK_STATUS_SOCKERR, NULL);
1320
0
      goto end;
1321
0
    }
1322
0
    tcpcheck_main(check);
1323
0
    expired = 0;
1324
0
  }
1325
1326
  /* there was a test running.
1327
   * First, let's check whether there was an uncaught error,
1328
   * which can happen on connect timeout or error.
1329
   */
1330
0
  if (check->result == CHK_RES_UNKNOWN && likely(!(check->state & CHK_ST_PURGE))) {
1331
0
    sc = check->sc;
1332
0
    conn = sc_conn(sc);
1333
1334
    /* Here the connection must be defined. Otherwise the
1335
     * error would have already been detected
1336
     */
1337
0
    if ((conn && ((conn->flags & CO_FL_ERROR) || sc_ep_test(sc, SE_FL_ERROR))) || expired) {
1338
0
      TRACE_ERROR("report connection error", CHK_EV_TASK_WAKE|CHK_EV_HCHK_END|CHK_EV_HCHK_ERR, check);
1339
0
      chk_report_conn_err(check, 0, expired);
1340
0
    }
1341
0
    else {
1342
0
      if (check->state & CHK_ST_CLOSE_CONN) {
1343
0
        TRACE_DEVEL("closing current connection", CHK_EV_TASK_WAKE|CHK_EV_HCHK_RUN, check);
1344
0
        check->state &= ~CHK_ST_CLOSE_CONN;
1345
0
        if (!sc_reset_endp(check->sc)) {
1346
          /* error will be handled by tcpcheck_main().
1347
           * On success, remove all flags except SE_FL_DETACHED
1348
           */
1349
0
          sc_ep_clr(check->sc, ~SE_FL_DETACHED);
1350
0
        }
1351
0
        tcpcheck_main(check);
1352
0
      }
1353
0
      if (check->result == CHK_RES_UNKNOWN) {
1354
0
        TRACE_DEVEL("health-check not expired", CHK_EV_TASK_WAKE|CHK_EV_HCHK_RUN, check);
1355
0
        goto out_unlock; /* timeout not reached, wait again */
1356
0
      }
1357
0
    }
1358
0
  }
1359
1360
  /* check complete or aborted */
1361
0
  TRACE_STATE("health-check complete or aborted", CHK_EV_TASK_WAKE|CHK_EV_HCHK_END, check);
1362
1363
  /* check->sc may be NULL when the healthcheck is purged */
1364
0
  check->current_step = NULL;
1365
0
  sc = check->sc;
1366
0
  conn = (sc ? sc_conn(sc) : NULL);
1367
1368
0
  if (conn && conn->xprt) {
1369
    /* The check was aborted and the connection was not yet closed.
1370
     * This can happen upon timeout, or when an external event such
1371
     * as a failed response coupled with "observe layer7" caused the
1372
     * server state to be suddenly changed.
1373
     */
1374
0
    se_shutdown(sc->sedesc, SE_SHR_DRAIN|SE_SHW_SILENT);
1375
0
  }
1376
1377
0
  if (sc) {
1378
0
    sc_destroy(sc);
1379
0
    check->sc = NULL;
1380
0
  }
1381
1382
0
  if (check->sess != NULL) {
1383
0
    vars_prune(&check->vars, check->sess, NULL);
1384
0
    session_free(check->sess);
1385
0
    check->sess = NULL;
1386
0
  }
1387
1388
0
  end:
1389
0
  if (check->server && likely(!(check->state & CHK_ST_PURGE))) {
1390
0
    if (check->result == CHK_RES_FAILED) {
1391
      /* a failure or timeout detected */
1392
0
      TRACE_DEVEL("report failure", CHK_EV_TASK_WAKE|CHK_EV_HCHK_END|CHK_EV_HCHK_ERR, check);
1393
0
      check_notify_failure(check);
1394
0
    }
1395
0
    else if (check->result == CHK_RES_CONDPASS) {
1396
      /* check is OK but asks for stopping mode */
1397
0
      TRACE_DEVEL("report conditional success", CHK_EV_TASK_WAKE|CHK_EV_HCHK_END|CHK_EV_HCHK_SUCC, check);
1398
0
      check_notify_stopping(check);
1399
0
    }
1400
0
    else if (check->result == CHK_RES_PASSED) {
1401
      /* a success was detected */
1402
0
      TRACE_DEVEL("report success", CHK_EV_TASK_WAKE|CHK_EV_HCHK_END|CHK_EV_HCHK_SUCC, check);
1403
0
      check_notify_success(check);
1404
0
    }
1405
0
  }
1406
1407
0
  b_dequeue(&check->buf_wait);
1408
1409
0
  check_release_buf(check, &check->bi);
1410
0
  check_release_buf(check, &check->bo);
1411
1412
0
  if (unlikely(LIST_INLIST(&check->check_queue))) {
1413
    /*
1414
     * If that check is still queued, and we're about to
1415
     * purge it, then remove it from the queue, as it is
1416
     * about to be freed.
1417
     * This can happen if a server is deleted while the check
1418
     * is queued.
1419
     */
1420
0
    if (check->state & CHK_ST_PURGE)
1421
0
      LIST_DEL_INIT(&check->check_queue);
1422
0
  }
1423
0
  else
1424
0
    _HA_ATOMIC_DEC(&th_ctx->running_checks);
1425
0
  _HA_ATOMIC_DEC(&th_ctx->active_checks);
1426
0
  check->state &= ~(CHK_ST_INPROGRESS|CHK_ST_IN_ALLOC|CHK_ST_OUT_ALLOC);
1427
0
  check->state &= ~CHK_ST_READY;
1428
0
  check->state |= CHK_ST_SLEEPING;
1429
1430
0
 update_timer:
1431
  /* when going to sleep, we need to check if other checks are waiting
1432
   * for a slot. If so we pick them out of the queue and wake them up.
1433
   */
1434
0
  if (check->server && (check->state & CHK_ST_SLEEPING)) {
1435
0
    if (!LIST_ISEMPTY(&th_ctx->queued_checks) &&
1436
0
        _HA_ATOMIC_LOAD(&th_ctx->running_checks) < global.tune.max_checks_per_thread) {
1437
0
      struct check *next_chk = LIST_ELEM(th_ctx->queued_checks.n, struct check *, check_queue);
1438
1439
      /* wake up pending task */
1440
0
      LIST_DEL_INIT(&next_chk->check_queue);
1441
1442
0
      activity[tid].check_started++;
1443
0
      _HA_ATOMIC_INC(&th_ctx->running_checks);
1444
0
      next_chk->state |= CHK_ST_READY;
1445
      /* now running */
1446
0
      task_wakeup(next_chk->task, TASK_WOKEN_RES);
1447
0
    }
1448
0
  }
1449
1450
0
  if (check->server) {
1451
0
    rv = 0;
1452
0
    if (global.spread_checks > 0) {
1453
0
      rv = srv_getinter(check) * global.spread_checks / 100;
1454
0
      rv -= (int) (2 * rv * (statistical_prng() / 4294967295.0));
1455
0
    }
1456
0
    t->expire = tick_add(now_ms, MS_TO_TICKS(srv_getinter(check) + rv));
1457
    /* reset fastinter flag (if set) so that srv_getinter()
1458
     * only returns fastinter if server health is degraded
1459
     */
1460
0
    check->state &= ~CHK_ST_FASTINTER;
1461
0
  }
1462
1463
0
 reschedule:
1464
0
  if (proxy->flags & (PR_FL_DISABLED|PR_FL_STOPPED))
1465
0
    t->expire = TICK_ETERNITY;
1466
0
  else {
1467
0
    while (tick_is_expired(t->expire, now_ms))
1468
0
      t->expire = tick_add(t->expire, MS_TO_TICKS(check->inter));
1469
0
  }
1470
1471
0
 out_unlock:
1472
0
  if (check->server)
1473
0
    HA_SPIN_UNLOCK(SERVER_LOCK, &check->server->lock);
1474
1475
0
 out_leave:
1476
0
  TRACE_LEAVE(CHK_EV_TASK_WAKE, check);
1477
1478
  /* Free the check if set to PURGE. After this, the check instance may be
1479
   * freed via the srv_drop invocation, so it must not be accessed after
1480
   * this point.
1481
   */
1482
0
  if (unlikely(check->state & CHK_ST_PURGE)) {
1483
0
    free_check(check);
1484
0
    if (check->server)
1485
0
      srv_drop(check->server);
1486
1487
0
    t = NULL;
1488
0
  }
1489
1490
0
  return t;
1491
0
}
1492
1493
1494
/**************************************************************************/
1495
/************************** Init/deinit checks ****************************/
1496
/**************************************************************************/
1497
/*
1498
 * Tries to grab a buffer and to re-enables processing on check <target>. The
1499
 * check flags are used to figure what buffer was requested. It returns 1 if the
1500
 * allocation succeeds, in which case the I/O tasklet is woken up, or 0 if it's
1501
 * impossible to wake up and we prefer to be woken up later.
1502
 */
1503
int check_buf_available(void *target)
1504
0
{
1505
0
  struct check *check = target;
1506
1507
0
  BUG_ON(!check->sc);
1508
1509
0
  if ((check->state & CHK_ST_IN_ALLOC) && b_alloc(&check->bi, DB_CHANNEL)) {
1510
0
    TRACE_STATE("unblocking check, input buffer allocated", CHK_EV_TCPCHK_EXP|CHK_EV_RX_BLK, check);
1511
0
    check->state &= ~CHK_ST_IN_ALLOC;
1512
0
    tasklet_wakeup(check->sc->wait_event.tasklet);
1513
0
    return 1;
1514
0
  }
1515
0
  if ((check->state & CHK_ST_OUT_ALLOC) && b_alloc(&check->bo, DB_CHANNEL)) {
1516
0
    TRACE_STATE("unblocking check, output buffer allocated", CHK_EV_TCPCHK_SND|CHK_EV_TX_BLK, check);
1517
0
    check->state &= ~CHK_ST_OUT_ALLOC;
1518
0
    tasklet_wakeup(check->sc->wait_event.tasklet);
1519
0
    return 1;
1520
0
  }
1521
1522
0
  return 0;
1523
0
}
1524
1525
/*
1526
 * Allocate a buffer. If it fails, it adds the check in buffer wait queue.
1527
 */
1528
struct buffer *check_get_buf(struct check *check, struct buffer *bptr, unsigned int small_buffer)
1529
0
{
1530
0
  struct buffer *buf = NULL;
1531
1532
0
  if (small_buffer == 0 || (buf = b_alloc_small(bptr)) == NULL) {
1533
0
    if (likely(!LIST_INLIST(&check->buf_wait.list)) &&
1534
0
        unlikely((buf = b_alloc(bptr, DB_CHANNEL)) == NULL)) {
1535
0
      b_queue(DB_CHANNEL, &check->buf_wait, check, check_buf_available);
1536
0
    }
1537
0
  }
1538
0
  return buf;
1539
0
}
1540
1541
/*
1542
 * Release a buffer, if any, and try to wake up entities waiting in the buffer
1543
 * wait queue.
1544
 */
1545
void check_release_buf(struct check *check, struct buffer *bptr)
1546
0
{
1547
0
  if (bptr->size) {
1548
0
    int defbuf = b_is_default(bptr);
1549
1550
0
    b_free(bptr);
1551
0
    if (defbuf)
1552
0
      offer_buffers(check->buf_wait.target, 1);
1553
0
  }
1554
0
}
1555
1556
const char *init_check(struct check *check, int type)
1557
0
{
1558
0
  check->type = type;
1559
1560
0
  check->bi = BUF_NULL;
1561
0
  check->bo = BUF_NULL;
1562
0
  LIST_INIT(&check->buf_wait.list);
1563
0
  LIST_INIT(&check->check_queue);
1564
0
  return NULL;
1565
0
}
1566
1567
/* Liberates the resources allocated for a check.
1568
 *
1569
 * This function must only be run by the thread owning the check.
1570
 */
1571
void free_check(struct check *check)
1572
0
{
1573
  /* For agent-check, free the rules / vars from the server. This is not
1574
   * done for health-check : the proxy is the owner of the rules / vars
1575
   * in this case.
1576
   */
1577
0
  if (check->state & CHK_ST_AGENT || check->tcpcheck->healthcheck) {
1578
0
    free_tcpcheck_vars(&check->tcpcheck->preset_vars);
1579
0
    ha_free(&check->tcpcheck->healthcheck);
1580
0
    ha_free(&check->tcpcheck);
1581
0
  }
1582
1583
0
  LIST_DEL_INIT(&check->check_queue);
1584
0
  pool_free(pool_head_uniqueid, istptr(check->unique_id));
1585
0
  check->unique_id = IST_NULL;
1586
0
  ha_free(&check->pool_conn_name);
1587
0
  ha_free(&check->sni);
1588
0
  ha_free(&check->alpn_str);
1589
0
  task_destroy(check->task);
1590
1591
0
  check_release_buf(check, &check->bi);
1592
0
  check_release_buf(check, &check->bo);
1593
0
  if (check->sc) {
1594
0
    sc_destroy(check->sc);
1595
0
    check->sc = NULL;
1596
0
  }
1597
0
}
1598
1599
/* This function must be used in order to free a started check. The check will
1600
 * be scheduled for a next execution in order to properly close and free all
1601
 * check elements.
1602
 *
1603
 * Non thread-safe.
1604
 */
1605
void check_purge(struct check *check)
1606
0
{
1607
0
  check->state |= CHK_ST_PURGE;
1608
0
  task_wakeup(check->task, TASK_WOKEN_OTHER);
1609
0
}
1610
1611
/* manages a server health-check. Returns the time the task accepts to wait, or
1612
 * TIME_ETERNITY for infinity.
1613
 */
1614
struct task *process_chk(struct task *t, void *context, unsigned int state)
1615
0
{
1616
0
  struct check *check = context;
1617
1618
0
  if (check->type == PR_O2_EXT_CHK)
1619
0
    return process_chk_proc(t, context, state);
1620
0
  return process_chk_conn(t, context, state);
1621
1622
0
}
1623
1624
1625
int start_check_task(struct check *check, int mininter,
1626
          int nbcheck, int srvpos)
1627
0
{
1628
0
  struct task *t;
1629
1630
  /* task for the check. Process-based checks exclusively run on thread 1. */
1631
0
  if (check->type == PR_O2_EXT_CHK)
1632
0
    t = task_new_on(0);
1633
0
  else
1634
0
    t = task_new_anywhere();
1635
1636
0
  if (!t)
1637
0
    goto fail_alloc_task;
1638
1639
0
  check->task = t;
1640
0
  t->process = process_chk;
1641
0
  t->context = check;
1642
1643
0
  if (mininter < srv_getinter(check))
1644
0
    mininter = srv_getinter(check);
1645
1646
0
  if (global.spread_checks > 0) {
1647
0
    int rnd;
1648
1649
0
    rnd  = srv_getinter(check) * global.spread_checks / 100;
1650
0
    rnd -= (int) (2 * rnd * (ha_random32() / 4294967295.0));
1651
0
    mininter += rnd;
1652
0
  }
1653
1654
0
  if (global.max_spread_checks && mininter > global.max_spread_checks)
1655
0
    mininter = global.max_spread_checks;
1656
1657
  /* check this every ms */
1658
0
  t->expire = tick_add(now_ms, MS_TO_TICKS(mininter * srvpos / nbcheck));
1659
0
  check->start = now_ns;
1660
0
  task_queue(t);
1661
1662
0
  return 1;
1663
1664
0
  fail_alloc_task:
1665
0
  ha_alert("Starting [%s:%s] check: out of memory.\n",
1666
0
     check->server->proxy->id, check->server->id);
1667
0
  return 0;
1668
0
}
1669
1670
/*
1671
 * Start health-check.
1672
 * Returns 0 if OK, ERR_FATAL on error, and prints the error in this case.
1673
 */
1674
static int start_checks()
1675
0
{
1676
0
  struct proxy *px;
1677
0
  struct server *s;
1678
0
  char *errmsg = NULL;
1679
0
  int nbcheck=0, mininter=0, srvpos=0;
1680
1681
  /* 0- init the dummy frontend used to create all checks sessions */
1682
0
  if (!setup_new_proxy(&checks_fe, "CHECKS-FE", PR_CAP_FE | PR_CAP_BE | PR_CAP_INT, &errmsg)) {
1683
0
    ha_alert("error during checks frontend creation: %s\n", errmsg);
1684
0
    ha_free(&errmsg);
1685
0
    return ERR_ALERT | ERR_FATAL;
1686
0
  }
1687
0
        checks_fe.mode = PR_MODE_TCP;
1688
0
  checks_fe.maxconn = 0;
1689
0
  checks_fe.conn_retries = CONN_RETRIES;
1690
0
  checks_fe.options2 |= PR_O2_INDEPSTR | PR_O2_SMARTCON | PR_O2_SMARTACC;
1691
0
  checks_fe.timeout.client = TICK_ETERNITY;
1692
1693
  /* 1- count the checkers to run simultaneously.
1694
   * We also determine the minimum interval among all of those which
1695
   * have an interval larger than SRV_CHK_INTER_THRES. This interval
1696
   * will be used to spread their start-up date. Those which have
1697
   * a shorter interval will start independently and will not dictate
1698
   * too short an interval for all others.
1699
   */
1700
0
  list_for_each_entry(px, &main_proxies, el) {
1701
0
    list_for_each_entry(s, &px->servers, el_px) {
1702
0
      if ((px->options2 & PR_O2_USE_SBUF_CHECK) &&
1703
0
          (s->check.tcpcheck->rs && s->check.tcpcheck->rs->flags & TCPCHK_RULES_MAY_USE_SBUF))
1704
0
        s->check.state |= CHK_ST_USE_SMALL_BUFF;
1705
1706
0
      if (s->check.state & CHK_ST_CONFIGURED) {
1707
0
        nbcheck++;
1708
0
        if ((srv_getinter(&s->check) >= SRV_CHK_INTER_THRES) &&
1709
0
            (!mininter || mininter > srv_getinter(&s->check)))
1710
0
          mininter = srv_getinter(&s->check);
1711
0
      }
1712
1713
0
      if (s->agent.state & CHK_ST_CONFIGURED) {
1714
0
        nbcheck++;
1715
0
        if ((srv_getinter(&s->agent) >= SRV_CHK_INTER_THRES) &&
1716
0
            (!mininter || mininter > srv_getinter(&s->agent)))
1717
0
          mininter = srv_getinter(&s->agent);
1718
0
      }
1719
0
    }
1720
0
  }
1721
1722
0
  if (!nbcheck)
1723
0
    return ERR_NONE;
1724
1725
0
  srand((unsigned)time(NULL));
1726
1727
  /* 2- start them as far as possible from each other. For this, we will
1728
   * start them after their interval is set to the min interval divided
1729
   * by the number of servers, weighted by the server's position in the
1730
   * list.
1731
   */
1732
0
  list_for_each_entry(px, &main_proxies, el) {
1733
0
    if ((px->options2 & PR_O2_CHK_ANY) == PR_O2_EXT_CHK) {
1734
0
      if (init_pid_list()) {
1735
0
        ha_alert("Starting [%s] check: out of memory.\n", px->id);
1736
0
        return ERR_ALERT | ERR_FATAL;
1737
0
      }
1738
0
    }
1739
1740
0
    list_for_each_entry(s, &px->servers, el_px) {
1741
      /* A task for the main check */
1742
0
      if (s->check.state & CHK_ST_CONFIGURED) {
1743
0
        if (s->check.type == PR_O2_EXT_CHK) {
1744
0
          if (!prepare_external_check(&s->check))
1745
0
            return ERR_ALERT | ERR_FATAL;
1746
0
        }
1747
0
        if (!start_check_task(&s->check, mininter, nbcheck, srvpos))
1748
0
          return ERR_ALERT | ERR_FATAL;
1749
0
        srvpos++;
1750
0
      }
1751
1752
      /* A task for a auxiliary agent check */
1753
0
      if (s->agent.state & CHK_ST_CONFIGURED) {
1754
0
        if (!start_check_task(&s->agent, mininter, nbcheck, srvpos)) {
1755
0
          return ERR_ALERT | ERR_FATAL;
1756
0
        }
1757
0
        srvpos++;
1758
0
      }
1759
0
    }
1760
0
  }
1761
0
  return ERR_NONE;
1762
0
}
1763
1764
/* called during deinit */
1765
static void clear_checks()
1766
0
{
1767
0
  if (checks_fe.id)
1768
0
    deinit_proxy(&checks_fe);
1769
0
}
1770
1771
/*
1772
 * Return value:
1773
 *   the port to be used for the health check
1774
 *   0 in case no port could be found for the check
1775
 */
1776
static int srv_check_healthcheck_port(struct check *chk)
1777
0
{
1778
0
  int i = 0;
1779
0
  struct server *srv = NULL;
1780
1781
0
  srv = chk->server;
1782
1783
  /* by default, we use the health check port configured */
1784
0
  if (chk->port > 0)
1785
0
    return chk->port;
1786
1787
  /* try to get the port from check_core.addr if check.port not set */
1788
0
  i = get_host_port(&chk->addr);
1789
0
  if (i > 0)
1790
0
    return i;
1791
1792
  /* try to get the port from server address */
1793
  /* prevent MAPPORTS from working at this point, since checks could
1794
   * not be performed in such case (MAPPORTS impose a relative ports
1795
   * based on live traffic)
1796
   */
1797
0
  if (srv->flags & SRV_F_MAPPORTS)
1798
0
    return 0;
1799
1800
0
  i = srv->svc_port; /* by default */
1801
0
  if (i > 0)
1802
0
    return i;
1803
1804
0
  return 0;
1805
0
}
1806
1807
/* Initializes an health-check attached to the server <srv>. Non-zero is returned
1808
 * if an error occurred.
1809
 */
1810
int init_srv_check(struct server *srv)
1811
0
{
1812
0
  const char *err;
1813
0
  struct tcpcheck_rule *r;
1814
0
  int ret = ERR_NONE;
1815
0
  int check_type;
1816
1817
0
  if (!srv->do_check || !(srv->proxy->cap & PR_CAP_BE))
1818
0
    goto out;
1819
1820
0
  if (!srv->check.type && (srv->proxy->options2 & PR_O2_CHK_ANY) != PR_O2_TCPCHK_CHK)
1821
0
    goto init;
1822
1823
0
  check_type = srv->check.tcpcheck->rs->flags & TCPCHK_RULES_PROTO_CHK;
1824
1825
0
  if (!(srv->flags & SRV_F_DYNAMIC)) {
1826
    /* If neither a port nor an addr was specified and no check
1827
     * transport layer is forced, then the transport layer used by
1828
     * the checks is the same as for the production traffic.
1829
     * Otherwise we use raw_sock by default, unless one is
1830
     * specified.
1831
     */
1832
0
    if (!srv->check.port && !is_addr(&srv->check.addr)) {
1833
0
      if ((!srv->check.use_ssl && srv->use_ssl != -1) ||
1834
0
          (srv->check.use_ssl == srv->use_ssl))
1835
0
        srv->check.xprt = srv->xprt;
1836
0
      else if (srv->check.use_ssl == 1)
1837
0
        srv->check.xprt = xprt_get(XPRT_SSL);
1838
0
      srv->check.send_proxy |= (srv->pp_opts);
1839
0
      srv->check.addr_type = srv->addr_type;
1840
0
      srv->check.alt_proto = srv->alt_proto;
1841
0
    } else {
1842
      /* Only port was specified, so let's go with TCP */
1843
0
      if (!is_addr(&srv->check.addr)) {
1844
0
        srv->check.addr_type.proto_type = PROTO_TYPE_STREAM;
1845
0
        srv->check.addr_type.xprt_type = PROTO_TYPE_STREAM;
1846
0
      }
1847
0
      if (net_addr_type_is_quic(&srv->check.addr_type))
1848
0
        srv->check.xprt = xprt_get(XPRT_QUIC);
1849
0
      else
1850
0
        if (srv->check.use_ssl == 1)
1851
0
          srv->check.xprt = xprt_get(XPRT_SSL);
1852
0
    }
1853
0
  }
1854
0
  else {
1855
    /* For dynamic servers, check-ssl and check-send-proxy must be
1856
     * explicitly defined even if the check port was not
1857
     * overridden.
1858
     */
1859
0
    if (!is_addr(&srv->check.addr)) {
1860
0
      if (srv->check.port) {
1861
0
        srv->check.addr_type.proto_type = PROTO_TYPE_STREAM;
1862
0
        srv->check.addr_type.xprt_type = PROTO_TYPE_STREAM;
1863
0
        srv->check.alt_proto = 0;
1864
0
      } else {
1865
0
        srv->check.addr_type = srv->addr_type;
1866
0
        srv->check.alt_proto = srv->alt_proto;
1867
0
      }
1868
0
    }
1869
0
    if (net_addr_type_is_quic(&srv->check.addr_type))
1870
0
      srv->check.xprt = xprt_get(XPRT_QUIC);
1871
0
    else if (srv->check.use_ssl == 1)
1872
0
      srv->check.xprt = xprt_get(XPRT_SSL);
1873
0
  }
1874
1875
  /* Inherit the mux protocol from the server if not already defined for
1876
   * the check
1877
   */
1878
0
  if (srv->mux_proto && !srv->check.mux_proto &&
1879
0
      ((srv->mux_proto->mode == PROTO_MODE_HTTP && check_type == TCPCHK_RULES_HTTP_CHK) ||
1880
0
       (srv->mux_proto->mode == PROTO_MODE_SPOP && check_type == TCPCHK_RULES_SPOP_CHK) ||
1881
0
       (srv->mux_proto->mode == PROTO_MODE_TCP && check_type != TCPCHK_RULES_HTTP_CHK)) &&
1882
0
       (net_addr_type_is_quic(&srv->check.addr_type) == srv_is_quic(srv))) {
1883
0
    srv->check.mux_proto = srv->mux_proto;
1884
0
  }
1885
  /* test that check proto is valid if explicitly defined */
1886
0
  else if (srv->check.mux_proto &&
1887
0
           ((srv->check.mux_proto->mode == PROTO_MODE_HTTP && check_type != TCPCHK_RULES_HTTP_CHK) ||
1888
0
      (srv->check.mux_proto->mode == PROTO_MODE_SPOP && check_type != TCPCHK_RULES_SPOP_CHK) ||
1889
0
            (srv->check.mux_proto->mode == PROTO_MODE_TCP && check_type == TCPCHK_RULES_HTTP_CHK))) {
1890
0
    ha_alert("config: %s '%s': server '%s' uses an incompatible MUX protocol for the selected check type\n",
1891
0
             proxy_type_str(srv->proxy), srv->proxy->id, srv->id);
1892
0
    ret |= ERR_ALERT | ERR_FATAL;
1893
0
    goto out;
1894
0
  }
1895
1896
  /* validate <srv> server health-check settings */
1897
1898
0
  if (net_addr_type_is_quic(&srv->check.addr_type)) {
1899
0
    if (srv->check.mux_proto && srv->check.mux_proto != get_mux_proto(ist("quic"))) {
1900
0
      ha_alert("config: %s '%s': QUIC server '%s' uses an incompatible MUX protocol for checks.\n",
1901
0
               proxy_type_str(srv->proxy), srv->proxy->id, srv->id);
1902
0
      ret |= ERR_ALERT | ERR_FATAL;
1903
0
      goto out;
1904
0
    }
1905
1906
0
    if (srv->check.use_ssl < 0) {
1907
0
      ha_alert("config: %s '%s': SSL is mandatory for checks on QUIC server '%s'.\n",
1908
0
               proxy_type_str(srv->proxy), srv->proxy->id, srv->id);
1909
0
      ret |= ERR_ALERT | ERR_FATAL;
1910
0
    }
1911
1912
0
    if (srv->check.send_proxy) {
1913
0
      ha_alert("config: %s '%s': cannot use PROXY protocol for checks on QUIC server '%s'.\n",
1914
0
               proxy_type_str(srv->proxy), srv->proxy->id, srv->id);
1915
0
      ret |= ERR_ALERT | ERR_FATAL;
1916
0
    }
1917
0
  }
1918
0
  else {
1919
0
    if (srv->check.mux_proto && srv->check.mux_proto == get_mux_proto(ist("quic"))) {
1920
0
      ha_alert("config: %s '%s': QUIC checks on non-QUIC server '%s' is not yet supported.\n",
1921
0
               proxy_type_str(srv->proxy), srv->proxy->id, srv->id);
1922
0
      ret |= ERR_ALERT | ERR_FATAL;
1923
0
      goto out;
1924
0
    }
1925
0
  }
1926
1927
  /* We need at least a service port, a check port or the first tcp-check
1928
   * rule must be a 'connect' one when checking an IPv4/IPv6 server.
1929
   */
1930
0
  if ((srv_check_healthcheck_port(&srv->check) != 0) ||
1931
0
      (!is_inet_addr(&srv->check.addr) && (is_addr(&srv->check.addr) || !is_inet_addr(&srv->addr))))
1932
0
    goto init;
1933
1934
0
  if (LIST_ISEMPTY(&srv->check.tcpcheck->rs->rules)) {
1935
0
    ha_alert("config: %s '%s': server '%s' has neither service port nor check port.\n",
1936
0
       proxy_type_str(srv->proxy), srv->proxy->id, srv->id);
1937
0
    ret |= ERR_ALERT | ERR_ABORT;
1938
0
    goto out;
1939
0
  }
1940
1941
  /* search the first action (connect / send / expect) in the list */
1942
0
  r = get_first_tcpcheck_rule(srv->check.tcpcheck->rs);
1943
0
  if (!r || (r->action != TCPCHK_ACT_CONNECT) || (!r->connect.port && !get_host_port(&r->connect.addr))) {
1944
0
    ha_alert("config: %s '%s': server '%s' has neither service port nor check port "
1945
0
       "nor tcp_check rule 'connect' with port information.\n",
1946
0
       proxy_type_str(srv->proxy), srv->proxy->id, srv->id);
1947
0
    ret |= ERR_ALERT | ERR_ABORT;
1948
0
    goto out;
1949
0
  }
1950
1951
  /* scan the tcp-check ruleset to ensure a port has been configured */
1952
0
  list_for_each_entry(r, &srv->check.tcpcheck->rs->rules, list) {
1953
0
    if ((r->action == TCPCHK_ACT_CONNECT) && (!r->connect.port && !get_host_port(&r->connect.addr))) {
1954
0
      ha_alert("config: %s '%s': server '%s' has neither service port nor check port, "
1955
0
         "and a tcp_check rule 'connect' with no port information.\n",
1956
0
         proxy_type_str(srv->proxy), srv->proxy->id, srv->id);
1957
0
      ret |= ERR_ALERT | ERR_ABORT;
1958
0
      goto out;
1959
0
    }
1960
0
  }
1961
1962
0
  init:
1963
0
  err = init_check(&srv->check, srv->check.type ? srv->check.type : (srv->proxy->options2 & PR_O2_CHK_ANY));
1964
0
  if (err) {
1965
0
    ha_alert("config: %s '%s': unable to init check for server '%s' (%s).\n",
1966
0
       proxy_type_str(srv->proxy), srv->proxy->id, srv->id, err);
1967
0
    ret |= ERR_ALERT | ERR_ABORT;
1968
0
    goto out;
1969
0
  }
1970
0
  srv->check.state |= CHK_ST_CONFIGURED | CHK_ST_ENABLED | CHK_ST_SLEEPING;
1971
0
  srv_take(srv);
1972
1973
  /* Only increment maxsock for servers from the configuration. Dynamic
1974
   * servers at the moment are not taken into account for the estimation
1975
   * of the resources limits.
1976
   */
1977
0
  if (global.mode & MODE_STARTING)
1978
0
    global.maxsock++;
1979
1980
0
  out:
1981
0
  return ret;
1982
0
}
1983
1984
/* Initializes an agent-check attached to the server <srv>. Non-zero is returned
1985
 * if an error occurred.
1986
 */
1987
int init_srv_agent_check(struct server *srv)
1988
0
{
1989
0
  struct tcpcheck_rule *chk;
1990
0
  const char *err;
1991
0
  int ret = ERR_NONE;
1992
1993
0
  if (!srv->do_agent || !(srv->proxy->cap & PR_CAP_BE))
1994
0
    goto out;
1995
1996
  /* If there is no connect rule preceding all send / expect rules, an
1997
   * implicit one is inserted before all others.
1998
   */
1999
0
  chk = get_first_tcpcheck_rule(srv->agent.tcpcheck->rs);
2000
0
  if (!chk || chk->action != TCPCHK_ACT_CONNECT) {
2001
0
    chk = calloc(1, sizeof(*chk));
2002
0
    if (!chk) {
2003
0
      ha_alert("%s '%s': unable to add implicit tcp-check connect rule"
2004
0
         " to agent-check for server '%s' (out of memory).\n",
2005
0
         proxy_type_str(srv->proxy), srv->proxy->id, srv->id);
2006
0
      ret |= ERR_ALERT | ERR_FATAL;
2007
0
      goto out;
2008
0
    }
2009
0
    chk->action = TCPCHK_ACT_CONNECT;
2010
0
    chk->connect.options = (TCPCHK_OPT_DEFAULT_CONNECT|TCPCHK_OPT_IMPLICIT);
2011
0
    LIST_INSERT(&srv->agent.tcpcheck->rs->rules, &chk->list);
2012
0
  }
2013
2014
  /* <chk> is always defined here and it is a CONNECT action. If there is
2015
   * a preset variable, it means there is an agent string defined and data
2016
   * will be sent after the connect.
2017
   */
2018
0
  if (!LIST_ISEMPTY(&srv->agent.tcpcheck->preset_vars))
2019
0
    chk->connect.options |= TCPCHK_OPT_HAS_DATA;
2020
2021
2022
0
  err = init_check(&srv->agent, PR_O2_TCPCHK_CHK);
2023
0
  if (err) {
2024
0
    ha_alert("config: %s '%s': unable to init agent-check for server '%s' (%s).\n",
2025
0
       proxy_type_str(srv->proxy), srv->proxy->id, srv->id, err);
2026
0
    ret |= ERR_ALERT | ERR_ABORT;
2027
0
    goto out;
2028
0
  }
2029
2030
0
  if (!srv->agent.inter)
2031
0
    srv->agent.inter = srv->check.inter;
2032
2033
0
  srv->agent.state |= CHK_ST_CONFIGURED | CHK_ST_ENABLED | CHK_ST_SLEEPING | CHK_ST_AGENT;
2034
0
  srv_take(srv);
2035
2036
  /* Only increment maxsock for servers from the configuration. Dynamic
2037
   * servers at the moment are not taken into account for the estimation
2038
   * of the resources limits.
2039
   */
2040
0
  if (global.mode & MODE_STARTING)
2041
0
    global.maxsock++;
2042
2043
0
  out:
2044
0
  return ret;
2045
0
}
2046
2047
static void deinit_srv_check(struct server *srv)
2048
0
{
2049
0
  if (srv->check.state & CHK_ST_CONFIGURED) {
2050
0
    free_check(&srv->check);
2051
    /* it is safe to drop now since the main server reference is still held by the proxy */
2052
0
    srv_drop(srv);
2053
0
  }
2054
0
  srv->check.state &= ~CHK_ST_CONFIGURED & ~CHK_ST_ENABLED;
2055
0
  srv->do_check = 0;
2056
0
}
2057
2058
2059
static void deinit_srv_agent_check(struct server *srv)
2060
0
{
2061
0
  if (srv->agent.state & CHK_ST_CONFIGURED) {
2062
0
    free_check(&srv->agent);
2063
    /* it is safe to drop now since the main server reference is still held by the proxy */
2064
0
    srv_drop(srv);
2065
0
  }
2066
2067
0
  srv->agent.state &= ~CHK_ST_CONFIGURED & ~CHK_ST_ENABLED & ~CHK_ST_AGENT;
2068
0
  srv->do_agent = 0;
2069
0
}
2070
2071
REGISTER_POST_SERVER_CHECK(init_srv_check);
2072
REGISTER_POST_SERVER_CHECK(init_srv_agent_check);
2073
REGISTER_POST_CHECK(start_checks);
2074
2075
REGISTER_SERVER_DEINIT(deinit_srv_check);
2076
REGISTER_SERVER_DEINIT(deinit_srv_agent_check);
2077
REGISTER_POST_DEINIT(clear_checks);
2078
2079
/* perform minimal initializations */
2080
static void init_checks()
2081
0
{
2082
0
  int i;
2083
2084
0
  for (i = 0; i < MAX_THREADS; i++)
2085
0
    LIST_INIT(&ha_thread_ctx[i].queued_checks);
2086
0
}
2087
2088
INITCALL0(STG_PREPARE, init_checks);
2089
2090
/**************************************************************************/
2091
/************************** Check sample fetches **************************/
2092
/**************************************************************************/
2093
2094
static struct sample_fetch_kw_list smp_kws = {ILH, {
2095
  { /* END */ },
2096
}};
2097
2098
INITCALL1(STG_REGISTER, sample_register_fetches, &smp_kws);
2099
2100
2101
/**************************************************************************/
2102
/************************ Check's parsing functions ***********************/
2103
/**************************************************************************/
2104
/* Parse the "addr" server keyword */
2105
static int srv_parse_addr(char **args, int *cur_arg, struct proxy *curpx, struct server *srv,
2106
        char **errmsg)
2107
0
{
2108
0
  struct sockaddr_storage *sk;
2109
0
  struct net_addr_type addr_type;
2110
0
  int port1, port2, err_code = 0;
2111
0
  int alt = 0;
2112
2113
2114
0
  if (!*args[*cur_arg+1]) {
2115
0
    memprintf(errmsg, "'%s' expects <ipv4|ipv6> as argument.", args[*cur_arg]);
2116
0
    goto error;
2117
0
  }
2118
2119
0
  sk = str2sa_range(args[*cur_arg+1], NULL, &port1, &port2, NULL, NULL, &addr_type, errmsg, NULL, NULL, &alt,
2120
0
                    PA_O_RESOLVE | PA_O_PORT_OK | PA_O_STREAM | PA_O_CONNECT);
2121
0
  if (!sk) {
2122
0
    memprintf(errmsg, "'%s' : %s", args[*cur_arg], *errmsg);
2123
0
    goto error;
2124
0
  }
2125
2126
0
  srv->check.addr = *sk;
2127
0
  srv->check.addr_type = addr_type;
2128
0
  srv->check.alt_proto = alt;
2129
  /* if agentaddr was never set, we can use addr */
2130
0
  if (!(srv->flags & SRV_F_AGENTADDR))
2131
0
    srv->agent.addr = *sk;
2132
2133
0
  out:
2134
0
  return err_code;
2135
2136
0
 error:
2137
0
  err_code |= ERR_ALERT | ERR_FATAL;
2138
0
  goto out;
2139
0
}
2140
2141
/* Parse the "agent-addr" server keyword */
2142
static int srv_parse_agent_addr(char **args, int *cur_arg, struct proxy *curpx, struct server *srv,
2143
        char **errmsg)
2144
0
{
2145
0
  struct sockaddr_storage sk;
2146
0
  int err_code = 0;
2147
2148
0
  if (!*(args[*cur_arg+1])) {
2149
0
    memprintf(errmsg, "'%s' expects an address as argument.", args[*cur_arg]);
2150
0
    goto error;
2151
0
  }
2152
0
  memset(&sk, 0, sizeof(sk));
2153
0
  if (str2ip(args[*cur_arg + 1], &sk) == NULL) {
2154
0
    memprintf(errmsg, "parsing agent-addr failed. Check if '%s' is correct address.", args[*cur_arg+1]);
2155
0
    goto error;
2156
0
  }
2157
0
  set_srv_agent_addr(srv, &sk);
2158
  /* Agent currently only uses TCP */
2159
0
  srv->agent.addr_type.proto_type = PROTO_TYPE_STREAM;
2160
0
  srv->agent.addr_type.xprt_type = PROTO_TYPE_STREAM;
2161
0
  srv->agent.alt_proto = 0;
2162
0
  out:
2163
0
  return err_code;
2164
2165
0
  error:
2166
0
  err_code |= ERR_ALERT | ERR_FATAL;
2167
0
  goto out;
2168
0
}
2169
2170
/* Parse the "agent-check" server keyword */
2171
static int srv_parse_agent_check(char **args, int *cur_arg, struct proxy *curpx, struct server *srv,
2172
         char **errmsg)
2173
0
{
2174
0
  struct tcpcheck_ruleset *rs = NULL;
2175
0
  struct tcpcheck *tc = srv->agent.tcpcheck;
2176
0
  struct tcpcheck_rule *chk;
2177
0
  int err_code = 0;
2178
2179
0
  if (srv->do_agent)
2180
0
    goto out;
2181
2182
0
  if (!(curpx->cap & PR_CAP_BE)) {
2183
0
    memprintf(errmsg, "'%s' ignored because %s '%s' has no backend capability",
2184
0
        args[*cur_arg], proxy_type_str(curpx), curpx->id);
2185
0
    return ERR_WARN;
2186
0
  }
2187
2188
0
  if (!tc) {
2189
0
    tc = calloc(1, sizeof(*tc));
2190
0
    if (!tc) {
2191
0
      memprintf(errmsg, "out of memory.");
2192
0
      goto error;
2193
0
    }
2194
0
    LIST_INIT(&tc->preset_vars);
2195
0
    srv->agent.tcpcheck = tc;
2196
0
  }
2197
2198
0
  rs = find_tcpcheck_ruleset("*agent-check");
2199
0
  if (rs)
2200
0
    goto ruleset_found;
2201
2202
0
  rs = create_tcpcheck_ruleset("*agent-check");
2203
0
  if (rs == NULL) {
2204
0
    memprintf(errmsg, "out of memory.");
2205
0
    goto error;
2206
0
  }
2207
2208
0
  chk = parse_tcpcheck_send((char *[]){"tcp-check", "send-lf", "%[var(check.agent_string)]", ""},
2209
0
          1, curpx, &rs->rules, srv->conf.file, srv->conf.line, errmsg);
2210
0
  if (!chk) {
2211
0
    memprintf(errmsg, "'%s': %s", args[*cur_arg], *errmsg);
2212
0
    goto error;
2213
0
  }
2214
0
  chk->index = 0;
2215
0
  LIST_APPEND(&rs->rules, &chk->list);
2216
2217
0
  chk = parse_tcpcheck_expect((char *[]){"tcp-check", "expect", "custom", ""},
2218
0
                        1, curpx, &rs->rules, TCPCHK_RULES_AGENT_CHK,
2219
0
            srv->conf.file, srv->conf.line, errmsg);
2220
0
  if (!chk) {
2221
0
    memprintf(errmsg, "'%s': %s", args[*cur_arg], *errmsg);
2222
0
    goto error;
2223
0
  }
2224
0
  chk->expect.custom = tcpcheck_agent_expect_reply;
2225
0
  chk->index = 1;
2226
0
  LIST_APPEND(&rs->rules, &chk->list);
2227
2228
0
  ruleset_found:
2229
0
  tc->rs = rs;
2230
0
  tc->flags &= ~TCPCHK_FL_UNUSED_RS;
2231
0
  rs->flags |= TCPCHK_RULES_AGENT_CHK;
2232
0
  srv->do_agent = 1;
2233
2234
0
  out:
2235
0
  return err_code;
2236
2237
0
  error:
2238
0
  deinit_srv_agent_check(srv);
2239
0
  free_tcpcheck_ruleset(rs);
2240
0
  err_code |= ERR_ALERT | ERR_FATAL;
2241
0
  goto out;
2242
0
}
2243
2244
/* Parse the "agent-inter" server keyword */
2245
static int srv_parse_agent_inter(char **args, int *cur_arg, struct proxy *curpx, struct server *srv,
2246
         char **errmsg)
2247
0
{
2248
0
  const char *err = NULL;
2249
0
  unsigned int delay;
2250
0
  int err_code = 0;
2251
2252
0
  if (!*(args[*cur_arg+1])) {
2253
0
    memprintf(errmsg, "'%s' expects a delay as argument.", args[*cur_arg]);
2254
0
    goto error;
2255
0
  }
2256
2257
0
  err = parse_time_err(args[*cur_arg+1], &delay, TIME_UNIT_MS);
2258
0
  if (err == PARSE_TIME_OVER) {
2259
0
    memprintf(errmsg, "timer overflow in argument <%s> to <%s> of server %s, maximum value is 2147483647 ms (~24.8 days).",
2260
0
        args[*cur_arg+1], args[*cur_arg], srv->id);
2261
0
    goto error;
2262
0
  }
2263
0
  else if (err == PARSE_TIME_UNDER) {
2264
0
    memprintf(errmsg, "timer underflow in argument <%s> to <%s> of server %s, minimum non-null value is 1 ms.",
2265
0
        args[*cur_arg+1], args[*cur_arg], srv->id);
2266
0
    goto error;
2267
0
  }
2268
0
  else if (err) {
2269
0
    memprintf(errmsg, "unexpected character '%c' in 'agent-inter' argument of server %s.",
2270
0
        *err, srv->id);
2271
0
    goto error;
2272
0
  }
2273
0
  if (delay <= 0) {
2274
0
    memprintf(errmsg, "invalid value %d for argument '%s' of server %s.",
2275
0
        delay, args[*cur_arg], srv->id);
2276
0
    goto error;
2277
0
  }
2278
0
  srv->agent.inter = delay;
2279
2280
0
  if (warn_if_lower(args[*cur_arg+1], 100)) {
2281
0
    memprintf(errmsg, "'%s %u' in server '%s' is suspiciously small for a value in milliseconds. Please use an explicit unit ('%ums') if that was the intent",
2282
0
              args[*cur_arg], delay, srv->id, delay);
2283
0
    err_code |= ERR_WARN;
2284
0
  }
2285
2286
0
  out:
2287
0
  return err_code;
2288
2289
0
  error:
2290
0
  err_code |= ERR_ALERT | ERR_FATAL;
2291
0
  goto out;
2292
0
}
2293
2294
/* Parse the "agent-port" server keyword */
2295
static int srv_parse_agent_port(char **args, int *cur_arg, struct proxy *curpx, struct server *srv,
2296
        char **errmsg)
2297
0
{
2298
0
  int err_code = 0;
2299
2300
0
  if (!*(args[*cur_arg+1])) {
2301
0
    memprintf(errmsg, "'%s' expects a port number as argument.", args[*cur_arg]);
2302
0
    goto error;
2303
0
  }
2304
2305
  /* Only increment maxsock for servers from the configuration. Dynamic
2306
   * servers at the moment are not taken into account for the estimation
2307
   * of the resources limits.
2308
   */
2309
0
  if (global.mode & MODE_STARTING)
2310
0
    global.maxsock++;
2311
2312
0
  set_srv_agent_port(srv, atol(args[*cur_arg + 1]));
2313
2314
0
  out:
2315
0
  return err_code;
2316
2317
0
  error:
2318
0
  err_code |= ERR_ALERT | ERR_FATAL;
2319
0
  goto out;
2320
0
}
2321
2322
int set_srv_agent_send(struct server *srv, const char *send)
2323
0
{
2324
0
  struct tcpcheck *tc = srv->agent.tcpcheck;
2325
0
  struct tcpcheck_var *var = NULL;
2326
0
  char *str;
2327
2328
0
  str = strdup(send);
2329
0
  var = create_tcpcheck_var(ist("check.agent_string"));
2330
0
  if (str == NULL || var == NULL)
2331
0
    goto error;
2332
2333
0
  free_tcpcheck_vars(&tc->preset_vars);
2334
2335
0
  var->data.type = SMP_T_STR;
2336
0
  var->data.u.str.area = str;
2337
0
  var->data.u.str.data = strlen(str);
2338
0
  LIST_INIT(&var->list);
2339
0
  LIST_APPEND(&tc->preset_vars, &var->list);
2340
2341
0
  return 1;
2342
2343
0
  error:
2344
0
  free(str);
2345
0
  free(var);
2346
0
  return 0;
2347
0
}
2348
2349
/* Parse the "agent-send" server keyword */
2350
static int srv_parse_agent_send(char **args, int *cur_arg, struct proxy *curpx, struct server *srv,
2351
        char **errmsg)
2352
0
{
2353
0
  struct tcpcheck *tc = srv->agent.tcpcheck;
2354
0
  int err_code = 0;
2355
2356
0
  if (!*(args[*cur_arg+1])) {
2357
0
    memprintf(errmsg, "'%s' expects a string as argument.", args[*cur_arg]);
2358
0
    goto error;
2359
0
  }
2360
2361
0
  if (!tc) {
2362
0
    tc = calloc(1, sizeof(*tc));
2363
0
    if (!tc) {
2364
0
      memprintf(errmsg, "out of memory.");
2365
0
      goto error;
2366
0
    }
2367
0
    LIST_INIT(&tc->preset_vars);
2368
0
    srv->agent.tcpcheck = tc;
2369
0
  }
2370
2371
0
  if (!set_srv_agent_send(srv, args[*cur_arg+1])) {
2372
0
    memprintf(errmsg, "out of memory.");
2373
0
    goto error;
2374
0
  }
2375
2376
0
  out:
2377
0
  return err_code;
2378
2379
0
  error:
2380
0
  deinit_srv_agent_check(srv);
2381
0
  err_code |= ERR_ALERT | ERR_FATAL;
2382
0
  goto out;
2383
0
}
2384
2385
/* Parse the "no-agent-send" server keyword */
2386
static int srv_parse_no_agent_check(char **args, int *cur_arg, struct proxy *curpx, struct server *srv,
2387
            char **errmsg)
2388
0
{
2389
0
  deinit_srv_agent_check(srv);
2390
0
  return 0;
2391
0
}
2392
2393
/* Parse the "check" server keyword */
2394
static int srv_parse_check(char **args, int *cur_arg, struct proxy *curpx, struct server *srv,
2395
         char **errmsg)
2396
0
{
2397
0
  if (!(curpx->cap & PR_CAP_BE)) {
2398
0
    memprintf(errmsg, "'%s' ignored because %s '%s' has no backend capability",
2399
0
        args[*cur_arg], proxy_type_str(curpx), curpx->id);
2400
0
    return ERR_WARN;
2401
0
  }
2402
2403
0
  srv->do_check = 1;
2404
0
  return 0;
2405
0
}
2406
2407
/* Parse the "check-send-proxy" server keyword */
2408
static int srv_parse_check_send_proxy(char **args, int *cur_arg, struct proxy *curpx, struct server *srv,
2409
              char **errmsg)
2410
0
{
2411
0
  srv->check.send_proxy = 1;
2412
0
  return 0;
2413
0
}
2414
2415
/* Parse the "check-via-socks4" server keyword */
2416
static int srv_parse_check_via_socks4(char **args, int *cur_arg, struct proxy *curpx, struct server *srv,
2417
              char **errmsg)
2418
0
{
2419
0
  srv->check.via_socks4 = 1;
2420
0
  return 0;
2421
0
}
2422
2423
/* Parse the "no-check" server keyword */
2424
static int srv_parse_no_check(char **args, int *cur_arg, struct proxy *curpx, struct server *srv,
2425
            char **errmsg)
2426
0
{
2427
0
  deinit_srv_check(srv);
2428
0
  return 0;
2429
0
}
2430
2431
/* Parse the "no-check-reuse-pool" server keyword */
2432
static int srv_parse_no_check_reuse_pool(char **args, int *cur_arg,
2433
                                         struct proxy *curpx, struct server *srv,
2434
                                         char **errmsg)
2435
0
{
2436
0
  srv->check.reuse_pool = 0;
2437
0
  return 0;
2438
0
}
2439
2440
/* Parse the "no-check-send-proxy" server keyword */
2441
static int srv_parse_no_check_send_proxy(char **args, int *cur_arg, struct proxy *curpx, struct server *srv,
2442
           char **errmsg)
2443
0
{
2444
0
  srv->check.send_proxy = 0;
2445
0
  return 0;
2446
0
}
2447
2448
/* parse the "check-pool-conn-name" server keyword */
2449
static int srv_parse_check_pool_conn_name(char **args, int *cur_arg,
2450
                                          struct proxy *px,
2451
                                          struct server *newsrv, char **err)
2452
0
{
2453
0
  int err_code = 0;
2454
2455
0
  if (!*args[*cur_arg + 1]) {
2456
0
    memprintf(err, "'%s' : missing value", args[*cur_arg]);
2457
0
    goto error;
2458
0
  }
2459
2460
0
  ha_free(&newsrv->check.pool_conn_name);
2461
0
  newsrv->check.pool_conn_name = strdup(args[*cur_arg + 1]);
2462
0
  if (!newsrv->check.pool_conn_name) {
2463
0
    memprintf(err, "'%s' : out of memory", args[*cur_arg]);
2464
0
    return ERR_ALERT | ERR_FATAL;
2465
0
  }
2466
2467
0
  out:
2468
0
  return err_code;
2469
2470
0
  error:
2471
0
  err_code |= ERR_ALERT | ERR_FATAL;
2472
0
  goto out;
2473
0
}
2474
2475
2476
/* parse the "check-proto" server keyword */
2477
static int srv_parse_check_proto(char **args, int *cur_arg,
2478
         struct proxy *px, struct server *newsrv, char **err)
2479
0
{
2480
0
  int err_code = 0;
2481
2482
0
  if (!*args[*cur_arg + 1]) {
2483
0
    memprintf(err, "'%s' : missing value", args[*cur_arg]);
2484
0
    goto error;
2485
0
  }
2486
0
  newsrv->check.mux_proto = get_mux_proto(ist(args[*cur_arg + 1]));
2487
0
  if (!newsrv->check.mux_proto) {
2488
0
    memprintf(err, "'%s' :  unknown MUX protocol '%s'", args[*cur_arg], args[*cur_arg+1]);
2489
0
    goto error;
2490
0
  }
2491
2492
0
  out:
2493
0
  return err_code;
2494
2495
0
  error:
2496
0
  err_code |= ERR_ALERT | ERR_FATAL;
2497
0
  goto out;
2498
0
}
2499
2500
/* Parse the "check-reuse-pool" server keyword */
2501
static int srv_parse_check_reuse_pool(char **args, int *cur_arg,
2502
                                      struct proxy *curpx, struct server *srv,
2503
                                      char **errmsg)
2504
0
{
2505
0
  srv->check.reuse_pool = 1;
2506
0
  return 0;
2507
0
}
2508
2509
2510
/* Parse the "rise" server keyword */
2511
static int srv_parse_check_rise(char **args, int *cur_arg, struct proxy *curpx, struct server *srv,
2512
        char **errmsg)
2513
0
{
2514
0
  int err_code = 0;
2515
2516
0
  if (!*args[*cur_arg + 1]) {
2517
0
    memprintf(errmsg, "'%s' expects an integer argument.", args[*cur_arg]);
2518
0
    goto error;
2519
0
  }
2520
2521
0
  srv->check.rise = atol(args[*cur_arg+1]);
2522
0
  if (srv->check.rise <= 0) {
2523
0
    memprintf(errmsg, "'%s' has to be > 0.", args[*cur_arg]);
2524
0
    goto error;
2525
0
  }
2526
2527
0
  if (srv->check.health)
2528
0
    srv->check.health = srv->check.rise;
2529
2530
0
  out:
2531
0
  return err_code;
2532
2533
0
  error:
2534
0
  deinit_srv_agent_check(srv);
2535
0
  err_code |= ERR_ALERT | ERR_FATAL;
2536
0
  goto out;
2537
0
}
2538
2539
/* Parse the "fall" server keyword */
2540
static int srv_parse_check_fall(char **args, int *cur_arg, struct proxy *curpx, struct server *srv,
2541
        char **errmsg)
2542
0
{
2543
0
  int err_code = 0;
2544
2545
0
  if (!*args[*cur_arg + 1]) {
2546
0
    memprintf(errmsg, "'%s' expects an integer argument.", args[*cur_arg]);
2547
0
    goto error;
2548
0
  }
2549
2550
0
  srv->check.fall = atol(args[*cur_arg+1]);
2551
0
  if (srv->check.fall <= 0) {
2552
0
    memprintf(errmsg, "'%s' has to be > 0.", args[*cur_arg]);
2553
0
    goto error;
2554
0
  }
2555
2556
0
  out:
2557
0
  return err_code;
2558
2559
0
  error:
2560
0
  deinit_srv_agent_check(srv);
2561
0
  err_code |= ERR_ALERT | ERR_FATAL;
2562
0
  goto out;
2563
0
}
2564
2565
/* Parse the "inter" server keyword */
2566
static int srv_parse_check_inter(char **args, int *cur_arg, struct proxy *curpx, struct server *srv,
2567
         char **errmsg)
2568
0
{
2569
0
  const char *err = NULL;
2570
0
  unsigned int delay;
2571
0
  int err_code = 0;
2572
2573
0
  if (!*(args[*cur_arg+1])) {
2574
0
    memprintf(errmsg, "'%s' expects a delay as argument.", args[*cur_arg]);
2575
0
    goto error;
2576
0
  }
2577
2578
0
  err = parse_time_err(args[*cur_arg+1], &delay, TIME_UNIT_MS);
2579
0
  if (err == PARSE_TIME_OVER) {
2580
0
    memprintf(errmsg, "timer overflow in argument <%s> to <%s> of server %s, maximum value is 2147483647 ms (~24.8 days).",
2581
0
        args[*cur_arg+1], args[*cur_arg], srv->id);
2582
0
    goto error;
2583
0
  }
2584
0
  else if (err == PARSE_TIME_UNDER) {
2585
0
    memprintf(errmsg, "timer underflow in argument <%s> to <%s> of server %s, minimum non-null value is 1 ms.",
2586
0
        args[*cur_arg+1], args[*cur_arg], srv->id);
2587
0
    goto error;
2588
0
  }
2589
0
  else if (err) {
2590
0
    memprintf(errmsg, "unexpected character '%c' in 'agent-inter' argument of server %s.",
2591
0
        *err, srv->id);
2592
0
    goto error;
2593
0
  }
2594
0
  if (delay <= 0) {
2595
0
    memprintf(errmsg, "invalid value %d for argument '%s' of server %s.",
2596
0
        delay, args[*cur_arg], srv->id);
2597
0
    goto error;
2598
0
  }
2599
0
  srv->check.inter = delay;
2600
2601
0
  if (warn_if_lower(args[*cur_arg+1], 100)) {
2602
0
    memprintf(errmsg, "'%s %u' in server '%s' is suspiciously small for a value in milliseconds. Please use an explicit unit ('%ums') if that was the intent",
2603
0
              args[*cur_arg], delay, srv->id, delay);
2604
0
    err_code |= ERR_WARN;
2605
0
  }
2606
2607
0
  out:
2608
0
  return err_code;
2609
2610
0
  error:
2611
0
  err_code |= ERR_ALERT | ERR_FATAL;
2612
0
  goto out;
2613
0
}
2614
2615
2616
/* Parse the "fastinter" server keyword */
2617
static int srv_parse_check_fastinter(char **args, int *cur_arg, struct proxy *curpx, struct server *srv,
2618
             char **errmsg)
2619
0
{
2620
0
  const char *err = NULL;
2621
0
  unsigned int delay;
2622
0
  int err_code = 0;
2623
2624
0
  if (!*(args[*cur_arg+1])) {
2625
0
    memprintf(errmsg, "'%s' expects a delay as argument.", args[*cur_arg]);
2626
0
    goto error;
2627
0
  }
2628
2629
0
  err = parse_time_err(args[*cur_arg+1], &delay, TIME_UNIT_MS);
2630
0
  if (err == PARSE_TIME_OVER) {
2631
0
    memprintf(errmsg, "timer overflow in argument <%s> to <%s> of server %s, maximum value is 2147483647 ms (~24.8 days).",
2632
0
        args[*cur_arg+1], args[*cur_arg], srv->id);
2633
0
    goto error;
2634
0
  }
2635
0
  else if (err == PARSE_TIME_UNDER) {
2636
0
    memprintf(errmsg, "timer underflow in argument <%s> to <%s> of server %s, minimum non-null value is 1 ms.",
2637
0
        args[*cur_arg+1], args[*cur_arg], srv->id);
2638
0
    goto error;
2639
0
  }
2640
0
  else if (err) {
2641
0
    memprintf(errmsg, "unexpected character '%c' in 'agent-inter' argument of server %s.",
2642
0
        *err, srv->id);
2643
0
    goto error;
2644
0
  }
2645
0
  if (delay <= 0) {
2646
0
    memprintf(errmsg, "invalid value %d for argument '%s' of server %s.",
2647
0
        delay, args[*cur_arg], srv->id);
2648
0
    goto error;
2649
0
  }
2650
0
  srv->check.fastinter = delay;
2651
2652
0
  if (warn_if_lower(args[*cur_arg+1], 100)) {
2653
0
    memprintf(errmsg, "'%s %u' in server '%s' is suspiciously small for a value in milliseconds. Please use an explicit unit ('%ums') if that was the intent",
2654
0
              args[*cur_arg], delay, srv->id, delay);
2655
0
    err_code |= ERR_WARN;
2656
0
  }
2657
2658
0
  out:
2659
0
  return err_code;
2660
2661
0
  error:
2662
0
  err_code |= ERR_ALERT | ERR_FATAL;
2663
0
  goto out;
2664
0
}
2665
2666
2667
/* Parse the "downinter" server keyword */
2668
static int srv_parse_check_downinter(char **args, int *cur_arg, struct proxy *curpx, struct server *srv,
2669
             char **errmsg)
2670
0
{
2671
0
  const char *err = NULL;
2672
0
  unsigned int delay;
2673
0
  int err_code = 0;
2674
2675
0
  if (!*(args[*cur_arg+1])) {
2676
0
    memprintf(errmsg, "'%s' expects a delay as argument.", args[*cur_arg]);
2677
0
    goto error;
2678
0
  }
2679
2680
0
  err = parse_time_err(args[*cur_arg+1], &delay, TIME_UNIT_MS);
2681
0
  if (err == PARSE_TIME_OVER) {
2682
0
    memprintf(errmsg, "timer overflow in argument <%s> to <%s> of server %s, maximum value is 2147483647 ms (~24.8 days).",
2683
0
        args[*cur_arg+1], args[*cur_arg], srv->id);
2684
0
    goto error;
2685
0
  }
2686
0
  else if (err == PARSE_TIME_UNDER) {
2687
0
    memprintf(errmsg, "timer underflow in argument <%s> to <%s> of server %s, minimum non-null value is 1 ms.",
2688
0
        args[*cur_arg+1], args[*cur_arg], srv->id);
2689
0
    goto error;
2690
0
  }
2691
0
  else if (err) {
2692
0
    memprintf(errmsg, "unexpected character '%c' in 'agent-inter' argument of server %s.",
2693
0
        *err, srv->id);
2694
0
    goto error;
2695
0
  }
2696
0
  if (delay <= 0) {
2697
0
    memprintf(errmsg, "invalid value %d for argument '%s' of server %s.",
2698
0
        delay, args[*cur_arg], srv->id);
2699
0
    goto error;
2700
0
  }
2701
0
  srv->check.downinter = delay;
2702
2703
0
  if (warn_if_lower(args[*cur_arg+1], 100)) {
2704
0
    memprintf(errmsg, "'%s %u' in server '%s' is suspiciously small for a value in milliseconds. Please use an explicit unit ('%ums') if that was the intent",
2705
0
              args[*cur_arg], delay, srv->id, delay);
2706
0
    err_code |= ERR_WARN;
2707
0
  }
2708
2709
0
  out:
2710
0
  return err_code;
2711
2712
0
  error:
2713
0
  err_code |= ERR_ALERT | ERR_FATAL;
2714
0
  goto out;
2715
0
}
2716
2717
/* Parse the "port" server keyword */
2718
static int srv_parse_check_port(char **args, int *cur_arg, struct proxy *curpx, struct server *srv,
2719
        char **errmsg)
2720
0
{
2721
0
  int err_code = 0;
2722
2723
0
  if (!*(args[*cur_arg+1])) {
2724
0
    memprintf(errmsg, "'%s' expects a port number as argument.", args[*cur_arg]);
2725
0
    goto error;
2726
0
  }
2727
2728
  /* Only increment maxsock for servers from the configuration. Dynamic
2729
   * servers at the moment are not taken into account for the estimation
2730
   * of the resources limits.
2731
   */
2732
0
  if (global.mode & MODE_STARTING)
2733
0
    global.maxsock++;
2734
2735
0
  srv->check.port = atol(args[*cur_arg+1]);
2736
  /* if agentport was never set, we can use port */
2737
0
  if (!(srv->flags & SRV_F_AGENTPORT))
2738
0
    srv->agent.port = srv->check.port;
2739
2740
0
  out:
2741
0
  return err_code;
2742
2743
0
  error:
2744
0
  err_code |= ERR_ALERT | ERR_FATAL;
2745
0
  goto out;
2746
0
}
2747
2748
/* config parser for global "tune.max-checks-per-thread" */
2749
static int check_parse_global_max_checks(char **args, int section_type, struct proxy *curpx,
2750
                                       const struct proxy *defpx, const char *file, int line,
2751
                                       char **err)
2752
0
{
2753
0
  if (too_many_args(1, args, err, NULL))
2754
0
    return -1;
2755
0
  global.tune.max_checks_per_thread = atoi(args[1]);
2756
0
  return 0;
2757
0
}
2758
2759
/* register "global" section keywords */
2760
static struct cfg_kw_list chk_cfg_kws = {ILH, {
2761
  { CFG_GLOBAL, "tune.max-checks-per-thread", check_parse_global_max_checks },
2762
  { 0, NULL, NULL }
2763
}};
2764
2765
INITCALL1(STG_REGISTER, cfg_register_keywords, &chk_cfg_kws);
2766
2767
/* register "server" line keywords */
2768
static struct srv_kw_list srv_kws = { "CHK", { }, {
2769
  { "addr",                srv_parse_addr,                1,  1,  1 }, /* IP address to send health to or to probe from agent-check */
2770
  { "agent-addr",          srv_parse_agent_addr,          1,  1,  1 }, /* Enable an auxiliary agent check */
2771
  { "agent-check",         srv_parse_agent_check,         0,  1,  1 }, /* Enable agent checks */
2772
  { "agent-inter",         srv_parse_agent_inter,         1,  1,  1 }, /* Set the interval between two agent checks */
2773
  { "agent-port",          srv_parse_agent_port,          1,  1,  1 }, /* Set the TCP port used for agent checks. */
2774
  { "agent-send",          srv_parse_agent_send,          1,  1,  1 }, /* Set string to send to agent. */
2775
  { "check",               srv_parse_check,               0,  1,  1 }, /* Enable health checks */
2776
  { "check-pool-conn-name", srv_parse_check_pool_conn_name, 1, 1, 1 }, /* */
2777
  { "check-proto",         srv_parse_check_proto,         1,  1,  1 }, /* Set the mux protocol for health checks  */
2778
  { "check-reuse-pool",    srv_parse_check_reuse_pool,    0,  1,  1 }, /* Allows to reuse idle connections for checks */
2779
  { "check-send-proxy",    srv_parse_check_send_proxy,    0,  1,  1 }, /* Enable PROXY protocol for health checks */
2780
  { "check-via-socks4",    srv_parse_check_via_socks4,    0,  1,  1 }, /* Enable socks4 proxy for health checks */
2781
  { "no-agent-check",      srv_parse_no_agent_check,      0,  1,  0 }, /* Do not enable any auxiliary agent check */
2782
  { "no-check",            srv_parse_no_check,            0,  1,  0 }, /* Disable health checks */
2783
  { "no-check-reuse-pool", srv_parse_no_check_reuse_pool, 0,  1,  0 }, /* Disable PROXY protocol for health checks */
2784
  { "no-check-send-proxy", srv_parse_no_check_send_proxy, 0,  1,  0 }, /* Disable PROXY protocol for health checks */
2785
  { "rise",                srv_parse_check_rise,          1,  1,  1 }, /* Set rise value for health checks */
2786
  { "fall",                srv_parse_check_fall,          1,  1,  1 }, /* Set fall value for health checks */
2787
  { "inter",               srv_parse_check_inter,         1,  1,  1 }, /* Set inter value for health checks */
2788
  { "fastinter",           srv_parse_check_fastinter,     1,  1,  1 }, /* Set fastinter value for health checks */
2789
  { "downinter",           srv_parse_check_downinter,     1,  1,  1 }, /* Set downinter value for health checks */
2790
  { "port",                srv_parse_check_port,          1,  1,  1 }, /* Set the TCP port used for health checks. */
2791
  { NULL, NULL, 0 },
2792
}};
2793
2794
INITCALL1(STG_REGISTER, srv_register_keywords, &srv_kws);
2795
2796
/*
2797
 * Local variables:
2798
 *  c-indent-level: 8
2799
 *  c-basic-offset: 8
2800
 * End:
2801
 */