blob: 468cfd311c3a8685a3c00c8015f933ce9b2ccdfd [file] [log] [blame]
Christopher Faulet3e3d3be2021-02-16 13:31:30 +01001/*
2 * Server-state management functions.
3 *
4 * Copyright (C) 2021 HAProxy Technologies, Christopher Faulet <cfaulet@haproxy.com>
5 *
6 * This program is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU General Public License
8 * as published by the Free Software Foundation; either version
9 * 2 of the License, or (at your option) any later version.
10 *
11 */
12
13#include <errno.h>
14
15#include <import/eb64tree.h>
16#include <import/xxhash.h>
17
18#include <haproxy/api.h>
19#include <haproxy/backend.h>
20#include <haproxy/cfgparse.h>
21#include <haproxy/check.h>
22#include <haproxy/errors.h>
23#include <haproxy/global.h>
24#include <haproxy/log.h>
25#include <haproxy/port_range.h>
26#include <haproxy/proxy.h>
27#include <haproxy/resolvers.h>
28#include <haproxy/server.h>
29#include <haproxy/ssl_sock.h>
30
31
32/* Update a server state using the parameters available in the params list.
33 * The caller must provide a supported version
34 * Grabs the server lock during operation.
35 */
36static void srv_state_srv_update(struct server *srv, int version, char **params)
37{
38 char *p;
39 struct buffer *msg;
40 const char *warning;
41
42 /* fields since version 1
43 * and common to all other upcoming versions
44 */
45 enum srv_state srv_op_state;
46 enum srv_admin srv_admin_state;
47 unsigned srv_uweight, srv_iweight;
48 unsigned long srv_last_time_change;
49 short srv_check_status;
50 enum chk_result srv_check_result;
51 int srv_check_health;
52 int srv_check_state, srv_agent_state;
53 int bk_f_forced_id;
54 int srv_f_forced_id;
55 int fqdn_set_by_cli;
56 const char *fqdn;
57 const char *port_st;
58 unsigned int port_svc;
59 char *srvrecord;
60 char *addr;
61 int partial_apply = 0;
62#ifdef USE_OPENSSL
63 int use_ssl;
64#endif
65
66 fqdn = NULL;
67 port_svc = 0;
68 msg = alloc_trash_chunk();
69 if (!msg)
70 goto end;
71
72 HA_SPIN_LOCK(SERVER_LOCK, &srv->lock);
73
74 /* Only version 1 supported for now, don't check it. Fields are :
75 * srv_addr: params[0]
76 * srv_op_state: params[1]
77 * srv_admin_state: params[2]
78 * srv_uweight: params[3]
79 * srv_iweight: params[4]
80 * srv_last_time_change: params[5]
81 * srv_check_status: params[6]
82 * srv_check_result: params[7]
83 * srv_check_health: params[8]
84 * srv_check_state: params[9]
85 * srv_agent_state: params[10]
86 * bk_f_forced_id: params[11]
87 * srv_f_forced_id: params[12]
88 * srv_fqdn: params[13]
89 * srv_port: params[14]
90 * srvrecord: params[15]
91 * srv_use_ssl: params[16]
92 * srv_check_port: params[17]
93 * srv_check_addr: params[18]
94 * srv_agent_addr: params[19]
95 * srv_agent_port: params[20]
96 */
97
98 /* validating srv_op_state */
99 p = NULL;
100 errno = 0;
101 srv_op_state = strtol(params[1], &p, 10);
102 if ((p == params[1]) || errno == EINVAL || errno == ERANGE ||
103 (srv_op_state != SRV_ST_STOPPED &&
104 srv_op_state != SRV_ST_STARTING &&
105 srv_op_state != SRV_ST_RUNNING &&
106 srv_op_state != SRV_ST_STOPPING)) {
107 chunk_appendf(msg, ", invalid srv_op_state value '%s'", params[1]);
108 }
109
110 /* validating srv_admin_state */
111 p = NULL;
112 errno = 0;
113 srv_admin_state = strtol(params[2], &p, 10);
114 fqdn_set_by_cli = !!(srv_admin_state & SRV_ADMF_HMAINT);
115
116 /* inherited statuses will be recomputed later.
117 * Also disable SRV_ADMF_HMAINT flag (set from stats socket fqdn).
118 */
119 srv_admin_state &= ~SRV_ADMF_IDRAIN & ~SRV_ADMF_IMAINT & ~SRV_ADMF_HMAINT & ~SRV_ADMF_RMAINT;
120
121 if ((p == params[2]) || errno == EINVAL || errno == ERANGE ||
122 (srv_admin_state != 0 &&
123 srv_admin_state != SRV_ADMF_FMAINT &&
124 srv_admin_state != SRV_ADMF_CMAINT &&
125 srv_admin_state != (SRV_ADMF_CMAINT | SRV_ADMF_FMAINT) &&
126 srv_admin_state != (SRV_ADMF_CMAINT | SRV_ADMF_FDRAIN) &&
127 srv_admin_state != SRV_ADMF_FDRAIN)) {
128 chunk_appendf(msg, ", invalid srv_admin_state value '%s'", params[2]);
129 }
130
131 /* validating srv_uweight */
132 p = NULL;
133 errno = 0;
134 srv_uweight = strtol(params[3], &p, 10);
135 if ((p == params[3]) || errno == EINVAL || errno == ERANGE || (srv_uweight > SRV_UWGHT_MAX))
136 chunk_appendf(msg, ", invalid srv_uweight value '%s'", params[3]);
137
138 /* validating srv_iweight */
139 p = NULL;
140 errno = 0;
141 srv_iweight = strtol(params[4], &p, 10);
142 if ((p == params[4]) || errno == EINVAL || errno == ERANGE || (srv_iweight > SRV_UWGHT_MAX))
143 chunk_appendf(msg, ", invalid srv_iweight value '%s'", params[4]);
144
145 /* validating srv_last_time_change */
146 p = NULL;
147 errno = 0;
148 srv_last_time_change = strtol(params[5], &p, 10);
149 if ((p == params[5]) || errno == EINVAL || errno == ERANGE)
150 chunk_appendf(msg, ", invalid srv_last_time_change value '%s'", params[5]);
151
152 /* validating srv_check_status */
153 p = NULL;
154 errno = 0;
155 srv_check_status = strtol(params[6], &p, 10);
156 if (p == params[6] || errno == EINVAL || errno == ERANGE ||
157 (srv_check_status >= HCHK_STATUS_SIZE))
158 chunk_appendf(msg, ", invalid srv_check_status value '%s'", params[6]);
159
160 /* validating srv_check_result */
161 p = NULL;
162 errno = 0;
163 srv_check_result = strtol(params[7], &p, 10);
164 if ((p == params[7]) || errno == EINVAL || errno == ERANGE ||
165 (srv_check_result != CHK_RES_UNKNOWN &&
166 srv_check_result != CHK_RES_NEUTRAL &&
167 srv_check_result != CHK_RES_FAILED &&
168 srv_check_result != CHK_RES_PASSED &&
169 srv_check_result != CHK_RES_CONDPASS)) {
170 chunk_appendf(msg, ", invalid srv_check_result value '%s'", params[7]);
171 }
172
173 /* validating srv_check_health */
174 p = NULL;
175 errno = 0;
176 srv_check_health = strtol(params[8], &p, 10);
177 if (p == params[8] || errno == EINVAL || errno == ERANGE)
178 chunk_appendf(msg, ", invalid srv_check_health value '%s'", params[8]);
179
180 /* validating srv_check_state */
181 p = NULL;
182 errno = 0;
183 srv_check_state = strtol(params[9], &p, 10);
184 if (p == params[9] || errno == EINVAL || errno == ERANGE ||
185 (srv_check_state & ~(CHK_ST_INPROGRESS | CHK_ST_CONFIGURED | CHK_ST_ENABLED | CHK_ST_PAUSED | CHK_ST_AGENT)))
186 chunk_appendf(msg, ", invalid srv_check_state value '%s'", params[9]);
187
188 /* validating srv_agent_state */
189 p = NULL;
190 errno = 0;
191 srv_agent_state = strtol(params[10], &p, 10);
192 if (p == params[10] || errno == EINVAL || errno == ERANGE ||
193 (srv_agent_state & ~(CHK_ST_INPROGRESS | CHK_ST_CONFIGURED | CHK_ST_ENABLED | CHK_ST_PAUSED | CHK_ST_AGENT)))
194 chunk_appendf(msg, ", invalid srv_agent_state value '%s'", params[10]);
195
196 /* validating bk_f_forced_id */
197 p = NULL;
198 errno = 0;
199 bk_f_forced_id = strtol(params[11], &p, 10);
200 if (p == params[11] || errno == EINVAL || errno == ERANGE || !((bk_f_forced_id == 0) || (bk_f_forced_id == 1)))
201 chunk_appendf(msg, ", invalid bk_f_forced_id value '%s'", params[11]);
202
203 /* validating srv_f_forced_id */
204 p = NULL;
205 errno = 0;
206 srv_f_forced_id = strtol(params[12], &p, 10);
207 if (p == params[12] || errno == EINVAL || errno == ERANGE || !((srv_f_forced_id == 0) || (srv_f_forced_id == 1)))
208 chunk_appendf(msg, ", invalid srv_f_forced_id value '%s'", params[12]);
209
210 /* validating srv_fqdn */
211 fqdn = params[13];
212 if (fqdn && *fqdn == '-')
213 fqdn = NULL;
214 if (fqdn && (strlen(fqdn) > DNS_MAX_NAME_SIZE || invalid_domainchar(fqdn))) {
215 chunk_appendf(msg, ", invalid srv_fqdn value '%s'", params[13]);
216 fqdn = NULL;
217 }
218
219 port_st = params[14];
220 if (port_st) {
221 port_svc = strl2uic(port_st, strlen(port_st));
222 if (port_svc > USHRT_MAX) {
223 chunk_appendf(msg, ", invalid srv_port value '%s'", port_st);
224 port_st = NULL;
225 }
226 }
227
228 /* SRV record
229 * NOTE: in HAProxy, SRV records must start with an underscore '_'
230 */
231 srvrecord = params[15];
232 if (srvrecord && *srvrecord != '_')
233 srvrecord = NULL;
234
235 /* don't apply anything if one error has been detected */
236 if (msg->data)
237 goto out;
238 partial_apply = 1;
239
240 /* recover operational state and apply it to this server
241 * and all servers tracking this one */
242 srv->check.health = srv_check_health;
243 switch (srv_op_state) {
244 case SRV_ST_STOPPED:
245 srv->check.health = 0;
246 srv_set_stopped(srv, "changed from server-state after a reload", NULL);
247 break;
248 case SRV_ST_STARTING:
249 /* If rise == 1 there is no STARTING state, let's switch to
250 * RUNNING
251 */
252 if (srv->check.rise == 1) {
253 srv->check.health = srv->check.rise + srv->check.fall - 1;
254 srv_set_running(srv, "", NULL);
255 break;
256 }
257 if (srv->check.health < 1 || srv->check.health >= srv->check.rise)
258 srv->check.health = srv->check.rise - 1;
259 srv->next_state = srv_op_state;
260 break;
261 case SRV_ST_STOPPING:
262 /* If fall == 1 there is no STOPPING state, let's switch to
263 * STOPPED
264 */
265 if (srv->check.fall == 1) {
266 srv->check.health = 0;
267 srv_set_stopped(srv, "changed from server-state after a reload", NULL);
268 break;
269 }
270 if (srv->check.health < srv->check.rise ||
271 srv->check.health > srv->check.rise + srv->check.fall - 2)
272 srv->check.health = srv->check.rise;
273 srv_set_stopping(srv, "changed from server-state after a reload", NULL);
274 break;
275 case SRV_ST_RUNNING:
276 srv->check.health = srv->check.rise + srv->check.fall - 1;
277 srv_set_running(srv, "", NULL);
278 break;
279 }
280
281 /* When applying server state, the following rules apply:
282 * - in case of a configuration change, we apply the setting from the new
283 * configuration, regardless of old running state
284 * - if no configuration change, we apply old running state only if old running
285 * state is different from new configuration state
286 */
287 /* configuration has changed */
288 if ((srv_admin_state & SRV_ADMF_CMAINT) != (srv->next_admin & SRV_ADMF_CMAINT)) {
289 if (srv->next_admin & SRV_ADMF_CMAINT)
290 srv_adm_set_maint(srv);
291 else
292 srv_adm_set_ready(srv);
293 }
294 /* configuration is the same, let's compate old running state and new conf state */
295 else {
296 if (srv_admin_state & SRV_ADMF_FMAINT && !(srv->next_admin & SRV_ADMF_CMAINT))
297 srv_adm_set_maint(srv);
298 else if (!(srv_admin_state & SRV_ADMF_FMAINT) && (srv->next_admin & SRV_ADMF_CMAINT))
299 srv_adm_set_ready(srv);
300 }
301 /* apply drain mode if server is currently enabled */
302 if (!(srv->next_admin & SRV_ADMF_FMAINT) && (srv_admin_state & SRV_ADMF_FDRAIN)) {
303 /* The SRV_ADMF_FDRAIN flag is inherited when srv->iweight is 0
304 * (srv->iweight is the weight set up in configuration).
305 * There are two possible reasons for FDRAIN to have been present :
306 * - previous config weight was zero
307 * - "set server b/s drain" was sent to the CLI
308 *
309 * In the first case, we simply want to drop this drain state
310 * if the new weight is not zero anymore, meaning the administrator
311 * has intentionally turned the weight back to a positive value to
312 * enable the server again after an operation. In the second case,
313 * the drain state was forced on the CLI regardless of the config's
314 * weight so we don't want a change to the config weight to lose this
315 * status. What this means is :
316 * - if previous weight was 0 and new one is >0, drop the DRAIN state.
317 * - if the previous weight was >0, keep it.
318 */
319 if (srv_iweight > 0 || srv->iweight == 0)
320 srv_adm_set_drain(srv);
321 }
322
323 srv->last_change = date.tv_sec - srv_last_time_change;
324 srv->check.status = srv_check_status;
325 srv->check.result = srv_check_result;
326
327 /* Only case we want to apply is removing ENABLED flag which could have been
328 * done by the "disable health" command over the stats socket
329 */
330 if ((srv->check.state & CHK_ST_CONFIGURED) &&
331 (srv_check_state & CHK_ST_CONFIGURED) &&
332 !(srv_check_state & CHK_ST_ENABLED))
333 srv->check.state &= ~CHK_ST_ENABLED;
334
335 /* Only case we want to apply is removing ENABLED flag which could have been
336 * done by the "disable agent" command over the stats socket
337 */
338 if ((srv->agent.state & CHK_ST_CONFIGURED) &&
339 (srv_agent_state & CHK_ST_CONFIGURED) &&
340 !(srv_agent_state & CHK_ST_ENABLED))
341 srv->agent.state &= ~CHK_ST_ENABLED;
342
343 /* We want to apply the previous 'running' weight (srv_uweight) only if there
344 * was no change in the configuration: both previous and new iweight are equals
345 *
346 * It means that a configuration file change has precedence over a unix socket change
347 * for server's weight
348 *
349 * by default, HAProxy applies the following weight when parsing the configuration
350 * srv->uweight = srv->iweight
351 */
352 if (srv_iweight == srv->iweight) {
353 srv->uweight = srv_uweight;
354 }
355 server_recalc_eweight(srv, 1);
356
357 /* load server IP address */
358 if (strcmp(params[0], "-") != 0)
359 srv->lastaddr = strdup(params[0]);
360
361 if (fqdn && srv->hostname) {
362 if (strcmp(srv->hostname, fqdn) == 0) {
363 /* Here we reset the 'set from stats socket FQDN' flag
364 * to support such transitions:
365 * Let's say initial FQDN value is foo1 (in configuration file).
366 * - FQDN changed from stats socket, from foo1 to foo2 value,
367 * - FQDN changed again from file configuration (with the same previous value
368 set from stats socket, from foo1 to foo2 value),
369 * - reload for any other reason than a FQDN modification,
370 * the configuration file FQDN matches the fqdn server state file value.
371 * So we must reset the 'set from stats socket FQDN' flag to be consistent with
372 * any further FQDN modification.
373 */
374 srv->next_admin &= ~SRV_ADMF_HMAINT;
375 }
376 else {
377 /* If the FDQN has been changed from stats socket,
378 * apply fqdn state file value (which is the value set
379 * from stats socket).
380 * Also ensure the runtime resolver will process this resolution.
381 */
382 if (fqdn_set_by_cli) {
383 srv_set_fqdn(srv, fqdn, 0);
384 srv->flags &= ~SRV_F_NO_RESOLUTION;
385 srv->next_admin |= SRV_ADMF_HMAINT;
386 }
387 }
388 }
389 /* If all the conditions below are validated, this means
390 * we're evaluating a server managed by SRV resolution
391 */
392 else if (fqdn && !srv->hostname && srvrecord) {
393 int res;
394
395 /* we can't apply previous state if SRV record has changed */
396 if (srv->srvrq && strcmp(srv->srvrq->name, srvrecord) != 0) {
397 chunk_appendf(msg, ", SRV record mismatch between configuration ('%s') and state file ('%s) for server '%s'. Previous state not applied", srv->srvrq->name, srvrecord, srv->id);
398 goto out;
399 }
400
401 /* create or find a SRV resolution for this srv record */
402 if (srv->srvrq == NULL && (srv->srvrq = find_srvrq_by_name(srvrecord, srv->proxy)) == NULL)
403 srv->srvrq = new_resolv_srvrq(srv, srvrecord);
404 if (srv->srvrq == NULL) {
405 chunk_appendf(msg, ", can't create or find SRV resolution '%s' for server '%s'", srvrecord, srv->id);
406 goto out;
407 }
408
409 /* prepare DNS resolution for this server */
410 res = srv_prepare_for_resolution(srv, fqdn);
411 if (res == -1) {
412 chunk_appendf(msg, ", can't allocate memory for DNS resolution for server '%s'", srv->id);
413 goto out;
414 }
415
416 /* Unset SRV_F_MAPPORTS for SRV records.
417 * SRV_F_MAPPORTS is unfortunately set by parse_server()
418 * because no ports are provided in the configuration file.
419 * This is because HAProxy will use the port found into the SRV record.
420 */
421 srv->flags &= ~SRV_F_MAPPORTS;
422 }
423
424 if (port_st)
425 srv->svc_port = port_svc;
426
427
428 if (params[16]) {
429#ifdef USE_OPENSSL
430 use_ssl = strtol(params[16], &p, 10);
431
432 /* configure ssl if connection has been initiated at startup */
433 if (srv->ssl_ctx.ctx != NULL)
434 ssl_sock_set_srv(srv, use_ssl);
435#endif
436 }
437
438 port_st = NULL;
439 if (params[17] && strcmp(params[17], "0") != 0)
440 port_st = params[17];
441 addr = NULL;
442 if (params[18] && strcmp(params[18], "-") != 0)
443 addr = params[18];
444 if (addr || port_st) {
445 warning = srv_update_check_addr_port(srv, addr, port_st);
446 if (warning) {
447 chunk_appendf(msg, ", %s", warning);
448 goto out;
449 }
450 }
451
452 port_st = NULL;
453 if (params[20] && strcmp(params[20], "0") != 0)
454 port_st = params[20];
455 addr = NULL;
456 if (params[19] && strcmp(params[19], "-") != 0)
457 addr = params[19];
458 if (addr || port_st) {
459 warning = srv_update_agent_addr_port(srv, addr, port_st);
460 if (warning) {
461 chunk_appendf(msg, ", %s", warning);
462 goto out;
463 }
464 }
465
466 out:
467 HA_SPIN_UNLOCK(SERVER_LOCK, &srv->lock);
468 if (msg->data) {
469 if (partial_apply == 1)
470 ha_warning("server-state partially applied for server '%s/%s'%s\n",
471 srv->proxy->id, srv->id, msg->area);
472 else
473 ha_warning("server-state application failed for server '%s/%s'%s\n",
474 srv->proxy->id, srv->id, msg->area);
475 }
476 end:
477 free_trash_chunk(msg);
478}
479
480/*
481 * Loop on the proxy's servers and try to load its state from <st_tree> using
482 * srv_state_srv_update(). The proxy name and the server name are concatenated
483 * to form the key. If found the entry is removed from the tree.
484 */
485static void srv_state_px_update(const struct proxy *px, int vsn, struct eb_root *st_tree)
486{
487 struct server_state_line *st_line;
488 struct eb64_node *node;
489 struct server *srv;
490 unsigned long key;
491
492 for (srv = px->srv; srv; srv = srv->next) {
493 chunk_printf(&trash, "%s %s", px->id, srv->id);
494 key = XXH3(trash.area, trash.data, 0);
495 node = eb64_lookup(st_tree, key);
496 if (!node)
497 continue; /* next server */
498 st_line = eb64_entry(node, typeof(*st_line), node);
499 srv_state_srv_update(srv, vsn, st_line->params+4);
500
501 /* the node may be released now */
502 eb64_delete(node);
503 free(st_line->line);
504 free(st_line);
505 }
506}
507
508/*
509 * read next line from file <f> and return the server state version if one found.
510 * If no version is found, then 0 is returned
511 * Note that this should be the first read on <f>
512 */
513static int srv_state_get_version(FILE *f) {
514 char mybuf[SRV_STATE_LINE_MAXLEN];
515 char *endptr;
516 long int vsn;
517
518 /* first character of first line of the file must contain the version of the export */
519 if (fgets(mybuf, SRV_STATE_LINE_MAXLEN, f) == NULL)
520 return 0;
521
522 vsn = strtol(mybuf, &endptr, 10);
523 if (endptr == mybuf || *endptr != '\n') {
524 /* Empty or truncated line */
525 return 0;
526 }
527
528 if (vsn < SRV_STATE_FILE_VERSION_MIN || vsn > SRV_STATE_FILE_VERSION_MAX) {
529 /* Wrong version number */
530 return 0;
531 }
532
533 return vsn;
534}
535
536
537/*
538 * parses server state line stored in <buf> and supposedly in version <version>.
539 * Set <params> accordingly on success. It returns 1 on success, 0 if the line
540 * must be ignored and -1 on error.
541 * The caller must provide a supported version
542 */
543static int srv_state_parse_line(char *buf, const int version, char **params)
544{
545 int buflen, arg, ret;
546 char *cur;
547
548 buflen = strlen(buf);
549 cur = buf;
550 ret = 1; /* be optimistic and pretend a success */
551
552 /* we need at least one character and a non-truncated line */
553 if (buflen == 0 || buf[buflen - 1] != '\n') {
554 ret = -1;
555 goto out;
556 }
557
558 /* skip blank characters at the beginning of the line */
559 while (isblank((unsigned char)*cur))
560 ++cur;
561
562 /* ignore empty or commented lines */
563 if (!*cur || *cur == '\n' || *cur == '#') {
564 ret = 0;
565 goto out;
566 }
567
568 /* Removes trailing '\n' to ease parsing */
569 buf[buflen - 1] = '\0';
570
571 /* we're now ready to move the line into <params> */
572 memset(params, 0, SRV_STATE_FILE_MAX_FIELDS * sizeof(*params));
573 arg = 0;
574 while (*cur) {
575 /* first of all, stop if there are too many fields */
576 if (arg >= SRV_STATE_FILE_MAX_FIELDS)
577 break;
578
579 /* then skip leading spaces */
580 while (*cur && isblank((unsigned char)*cur)) {
581 ++cur;
582 if (!*cur)
583 break;
584 }
585
586 /*
587 * idx:
588 * be_id: params[0]
589 * be_name: params[1]
590 * srv_id: params[2]
591 * srv_name: params[3]
592 * v1
593 * srv_addr: params[4]
594 * srv_op_state: params[5]
595 * srv_admin_state: params[6]
596 * srv_uweight: params[7]
597 * srv_iweight: params[8]
598 * srv_last_time_change: params[9]
599 * srv_check_status: params[10]
600 * srv_check_result: params[11]
601 * srv_check_health: params[12]
602 * srv_check_state: params[13]
603 * srv_agent_state: params[14]
604 * bk_f_forced_id: params[15]
605 * srv_f_forced_id: params[16]
606 * srv_fqdn: params[17]
607 * srv_port: params[18]
608 * srvrecord: params[19]
609 *
610 * srv_use_ssl: params[20] (optional field)
611 * srv_check_port: params[21] (optional field)
612 * srv_check_addr: params[22] (optional field)
613 * srv_agent_addr: params[23] (optional field)
614 * srv_agent_port: params[24] (optional field)
615 *
616 */
617 params[arg++] = cur;
618
619 /* look for the end of the current field */
620 while (*cur && !isblank((unsigned char)*cur)) {
621 ++cur;
622 if (!*cur)
623 break;
624 }
625
626 /* otherwise, cut the field and move to the next one */
627 *cur++ = '\0';
628 }
629
630 /* if the number of fields does not match the version, then return an error */
631 if (version == 1 &&
632 (arg < SRV_STATE_FILE_MIN_FIELDS_VERSION_1 ||
633 arg > SRV_STATE_FILE_MAX_FIELDS_VERSION_1))
634 ret = -1;
635
636 out:
637 return ret;
638}
639
640
641/*
642 * parses a server state line using srv_state_parse_line() and store the result
643 * in <st_tree>. If an error occurred during the parsing, the line is
644 * ignored. if <px> is defined, it is used to check the backend id/name against
645 * the parsed params and to compute the key of the line.
646 */
647static int srv_state_parse_and_store_line(char *line, int vsn, struct eb_root *st_tree,
648 struct proxy *px)
649{
650 struct server_state_line *st_line;
651 int ret = 0;
652
653 /* store line in tree and duplicate the line */
654 st_line = calloc(1, sizeof(*st_line));
655 if (st_line == NULL)
656 goto skip_line;
657 st_line->line = strdup(line);
658 if (st_line->line == NULL)
659 goto skip_line;
660
661 ret = srv_state_parse_line(st_line->line, vsn, st_line->params);
662 if (ret <= 0)
663 goto skip_line;
664
665 /* Check backend name against params if <px> is defined */
666 if (px) {
667 int check_id = (atoi(st_line->params[0]) == px->uuid);
668 int check_name = (strcmp(px->id, st_line->params[1]) == 0);
669 int bk_f_forced_id = (atoi(st_line->params[15]) & PR_O_FORCED_ID);
670
671
672 if (!check_id && !check_name) {
673 /* backend does not match at all: skip the line */
674 goto skip_line;
675 }
676 else if (!check_id) {
677 /* Id mismatch: warn but continue */
678 ha_warning("Proxy '%s': backend ID mismatch: from server state file: '%s', from running config '%d'\n",
679 px->id, st_line->params[0], px->uuid);
680 send_log(px, LOG_NOTICE, "backend ID mismatch: from server state file: '%s', from running config '%d'\n",
681 st_line->params[0], px->uuid);
682 }
683 else if (!check_name) {
684 /* Name mismatch: warn and skip the line, except if the backend id was forced
685 * in the previous configuration */
686 ha_warning("Proxy '%s': backend name mismatch: from server state file: '%s', from running config '%s'\n",
687 px->id, st_line->params[1], px->id);
688 send_log(px, LOG_NOTICE, "backend name mismatch: from server state file: '%s', from running config '%s'\n",
689 st_line->params[1], px->id);
690 if (!bk_f_forced_id)
691 goto skip_line;
692 }
693 }
694
695 /*
696 * The key: "be_name srv_name"
697 * if <px> is defined: be_name == px->id
698 * otherwise: be_name == params[1]
699 */
700 chunk_printf(&trash, "%s %s", (px ? px->id : st_line->params[1]), st_line->params[3]);
701 st_line->node.key = XXH3(trash.area, trash.data, 0);
702 if (eb64_insert(st_tree, &st_line->node) != &st_line->node) {
703 /* this is a duplicate key, probably a hand-crafted file, drop it! */
704 goto skip_line;
705 }
706
707 return ret;
708
709 skip_line:
710 /* free up memory in case of error during the processing of the line */
711 if (st_line) {
712 free(st_line->line);
713 free(st_line);
714 }
715 return ret;
716}
717
718/* Helper function to get the server-state file path.
719 * If <filename> starts with a '/', it is considered as an absolute path. In
720 * this case or if <global.server_state_base> is not set, <filename> only is
721 * considered. Otherwise, the <global.server_state_base> is concatenated to
722 * <filename> to produce the file path and copied to <dst_path>. in both cases,
723 * the result must not exceeds <maxpathlen>.
724 *
725 * The len is returned on success or -1 if the path is too long. On error, the
726 * caller must not rely on <dst_path>.
727 */
728static inline int srv_state_get_filepath(char *dst_path, int maxpathlen, const char *filename)
729{
730 char *sep = (global.server_state_base[strlen(global.server_state_base)-1] != '/' ? "/": "");
731 int len = 0;
732
733 /* create the globalfilepath variable */
734 if (*filename == '/' || !global.server_state_base) {
735 /* absolute path or no base directory provided */
736 len = strlen(filename);
737 if (len < maxpathlen)
738 strcpy(dst_path, global.server_state_file);
739 }
740 else {
741 /* concat base directory and global server-state file */
742 len = snprintf(dst_path, maxpathlen, "%s%s%s", global.server_state_base, sep, filename);
743 }
744 return (len < maxpathlen ? len: -1);
745}
746
747
748/* This function parses all the proxies and only take care of the backends (since we're looking for server)
749 * For each proxy, it does the following:
750 * - opens its server state file (either one or local one)
751 * - read whole file, line by line
752 * - analyse each line to check if it matches our current backend:
753 * - backend name matches
754 * - backend id matches if id is forced and name doesn't match
755 * - if the server pointed by the line is found, then state is applied
756 *
757 * If the running backend uuid or id differs from the state file, then HAProxy reports
758 * a warning.
759 *
760 * Grabs the server's lock via srv_state_srv_update().
761 */
762void apply_server_state(void)
763{
764 /* tree where global state_file is loaded */
765 struct eb_root global_state_tree = EB_ROOT_UNIQUE;
766 struct proxy *curproxy;
767 struct server_state_line *st_line;
768 struct eb64_node *node, *next_node;
769 FILE *f;
770 char mybuf[SRV_STATE_LINE_MAXLEN];
771 char file[MAXPATHLEN];
772 int local_vsn, global_vsn, len, linenum;
773
774 global_vsn = 0; /* no global file */
775 if (!global.server_state_file)
776 goto no_globalfile;
777 len = srv_state_get_filepath(file, MAXPATHLEN, global.server_state_file);
778 if (len == -1) {
779 ha_warning("config: Can't load global server state file: file too long.\n");
780 goto no_globalfile;
781 }
782
783 /* Load global server state in a tree */
784 errno = 0;
785 f = fopen(file, "r");
786 if (!f) {
787 ha_warning("config: Can't open global server state file '%s': %s\n", file, strerror(errno));
788 goto no_globalfile;
789 }
790
791 global_vsn = srv_state_get_version(f);
792 if (global_vsn == 0) {
793 ha_warning("config: Can't get version of the global server state file '%s'.\n",
794 file);
795 goto close_globalfile;
796 }
797
798 for (linenum = 1; fgets(mybuf, SRV_STATE_LINE_MAXLEN, f); linenum++) {
799 int ret;
800
801 ret = srv_state_parse_and_store_line(mybuf, global_vsn, &global_state_tree, NULL);
802 if (ret == -1) {
803 ha_warning("config: corrupted global server state file '%s' at line %d.\n",
804 file, linenum);
805 global_vsn = 0;
806 break;
807 }
808 }
809
810 close_globalfile:
811 fclose(f);
812
813 no_globalfile:
814 /* parse all proxies and load states form tree (global file) or from local file */
815 for (curproxy = proxies_list; curproxy != NULL; curproxy = curproxy->next) {
816 struct eb_root local_state_tree = EB_ROOT_UNIQUE;
817
Christopher Faulet6f691102021-03-04 16:35:26 +0100818 /* Must be an enabled backend with at least a server */
819 if (!(curproxy->cap & PR_CAP_BE) || curproxy->disabled || !curproxy->srv)
Christopher Faulet3e3d3be2021-02-16 13:31:30 +0100820 continue; /* next proxy */
821
Christopher Faulet6f691102021-03-04 16:35:26 +0100822 /* Mode must be specified */
823 BUG_ON(curproxy->load_server_state_from_file == PR_SRV_STATE_FILE_UNSPEC);
824
Christopher Faulet3e3d3be2021-02-16 13:31:30 +0100825 /* No server-state file for this proxy */
826 if (curproxy->load_server_state_from_file == PR_SRV_STATE_FILE_NONE)
827 continue; /* next proxy */
828
829 if (curproxy->load_server_state_from_file == PR_SRV_STATE_FILE_GLOBAL) {
830 /* when global file is used, we get data from the tree
831 * Note that in such case we don't check backend name neither uuid.
832 * Backend name can't be wrong since it's used as a key to retrieve the server state
833 * line from the tree.
834 */
835 if (global_vsn)
836 srv_state_px_update(curproxy, global_vsn, &global_state_tree);
837 continue; /* next proxy */
838 }
839
840 /*
841 * Here we load a local server state-file
842 */
843
844 /* create file variable */
845 len = srv_state_get_filepath(file, MAXPATHLEN, curproxy->server_state_file_name);
846 if (len == -1) {
847 ha_warning("Proxy '%s': Can't load local server state file: file too long.\n", curproxy->id);
848 continue; /* next proxy */
849 }
850
851 /* Load local server state in a tree */
852 errno = 0;
853 f = fopen(file, "r");
854 if (!f) {
855 ha_warning("Proxy '%s': Can't open server state file '%s': %s.\n",
856 curproxy->id, file, strerror(errno));
857 continue; /* next proxy */
858 }
859
860 /* first character of first line of the file must contain the version of the export */
861 local_vsn = srv_state_get_version(f);
862 if (local_vsn == 0) {
863 ha_warning("Proxy '%s': Can't get version of the server state file '%s'.\n",
864 curproxy->id, file);
865 goto close_localfile;
866 }
867
868 /* First, parse lines of the local server-state file and store them in a eb-tree */
869 for (linenum = 1; fgets(mybuf, SRV_STATE_LINE_MAXLEN, f); linenum++) {
870 int ret;
871
872 ret = srv_state_parse_and_store_line(mybuf, local_vsn, &local_state_tree, curproxy);
873 if (ret == -1) {
874 ha_warning("Proxy '%s': corrupted server state file '%s' at line %d.\n",
875 curproxy->id, file, linenum);
876 local_vsn = 0;
877 break;
878 }
879 }
880
881 if (local_vsn)
882 srv_state_px_update(curproxy, local_vsn, &local_state_tree);
883
Ilya Shipitsind7a988c2021-03-04 23:26:15 +0500884 /* Remove unused server-state lines */
Christopher Faulet3e3d3be2021-02-16 13:31:30 +0100885 node = eb64_first(&local_state_tree);
886 while (node) {
887 st_line = eb64_entry(node, typeof(*st_line), node);
888 next_node = eb64_next(node);
889 eb64_delete(node);
890
891 if (local_vsn) {
892 /* if no server found, then warn */
893 ha_warning("Proxy '%s': can't find server '%s' in backend '%s'\n",
894 curproxy->id, st_line->params[3], curproxy->id);
895 send_log(curproxy, LOG_NOTICE, "can't find server '%s' in backend '%s'\n",
896 st_line->params[3], curproxy->id);
897 }
898
899 free(st_line->line);
900 free(st_line);
901 node = next_node;
902 }
903
904 close_localfile:
905 fclose(f);
906 }
907
908 node = eb64_first(&global_state_tree);
909 while (node) {
910 st_line = eb64_entry(node, typeof(*st_line), node);
911 next_node = eb64_next(node);
912 eb64_delete(node);
913 free(st_line->line);
914 free(st_line);
915 node = next_node;
916 }
917}