File: http-loadbalancer.c

package info (click to toggle)
syslog-ng 4.8.1-6
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 20,456 kB
  • sloc: ansic: 177,631; python: 13,035; cpp: 11,611; makefile: 7,012; sh: 5,147; java: 3,651; xml: 3,344; yacc: 1,377; lex: 599; perl: 193; awk: 190; objc: 162
file content (431 lines) | stat: -rw-r--r-- 12,022 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
/*
 * Copyright (c) 2018 Balazs Scheidler
 * Copyright (c) 2018 Balabit
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 as published
 * by the Free Software Foundation, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 * As an additional exemption you are allowed to compile & link against the
 * OpenSSL libraries as published by the OpenSSL project. See the file
 * COPYING for details.
 *
 */

#include "http-loadbalancer.h"
#include "messages.h"
#include "str-utils.h"
#include <string.h>
#include "compat/curl.h"

#define HTTP_URL_FORMAT_ERROR http_url_format_error_quark()

static GQuark http_url_format_error_quark(void)
{
  return g_quark_from_static_string("http_url_format_error_quark");
}

enum HttpUrlFormatError
{
  HTTP_URL_FORMAT_ERROR_UNSAFE_TEMPLATE,
};

/* HTTPLoadBalancerTarget */

static gboolean
_is_url_safely_templated(const gchar *url, GError **error)
{
#if !SYSLOG_NG_CURL_FULLY_SUPPORTS_URL_PARSING
  if (strchr(url, '$'))
    msg_warning_once("http(): Cannot validate whether the url() option is safely templated or not with the libcurl "
                     "version your syslog-ng was compiled with. Using templates in the scheme, host, port, user "
                     "or password part of the URL is considered unsafe and not recommended. Please make sure that only "
                     "the path or query parameters parts are templated in your http() destinations");
  return TRUE;
#else
  if (!strchr(url, '$'))
    return TRUE;

  static const gchar *unsafe_part_names[CURLUE_LAST] =
  {
    [CURLUE_BAD_SCHEME] = "Scheme",
    [CURLUE_BAD_HOSTNAME] = "Host",
    [CURLUE_BAD_PORT_NUMBER] = "Port",
    [CURLUE_BAD_USER] = "User",
    [CURLUE_BAD_PASSWORD] = "Password",

    [CURLUE_MALFORMED_INPUT] = "Failed to parse URL. Scheme, host, port, user or password",
  };

  static const struct
  {
    CURLUPart part;
    CURLUcode error;
  } unsafe_parts[] =
  {
    { .part = CURLUPART_SCHEME, .error = CURLUE_BAD_SCHEME },
    { .part = CURLUPART_HOST, .error = CURLUE_BAD_HOSTNAME },
    { .part = CURLUPART_PORT, .error = CURLUE_BAD_PORT_NUMBER },
    { .part = CURLUPART_USER, .error = CURLUE_BAD_USER },
    { .part = CURLUPART_PASSWORD, .error = CURLUE_BAD_PASSWORD },
  };

  CURLU *h = curl_url();
  CURLUcode rc = curl_url_set(h, CURLUPART_URL, url, CURLU_ALLOW_SPACE);

  const gchar *unsafe_part_name = unsafe_part_names[rc];
  if (unsafe_part_name)
    goto exit;

  for (size_t i = 0; i < G_N_ELEMENTS(unsafe_parts) && !unsafe_part_name; i++)
    {
      gchar *part = NULL;
      curl_url_get(h, unsafe_parts[i].part, &part, 0);

      if (part && strchr(part, '$'))
        unsafe_part_name = unsafe_part_names[unsafe_parts[i].error];

      curl_free(part);
    }

exit:
  curl_url_cleanup(h);

  if (unsafe_part_name)
    {
      g_set_error(error, HTTP_URL_FORMAT_ERROR, HTTP_URL_FORMAT_ERROR_UNSAFE_TEMPLATE,
                  "%s part of URL cannot contain templates: %s", unsafe_part_name, url);
      return FALSE;
    }

  return TRUE;
#endif
}

gboolean
http_lb_target_init(HTTPLoadBalancerTarget *self, const gchar *url, gint index_, GError **error)
{
  memset(self, 0, sizeof(*self));

  if (!_is_url_safely_templated(url, error))
    return FALSE;

  LogTemplate *url_template = log_template_new(configuration, NULL);
  log_template_set_escape(url_template, TRUE);
  if (!log_template_compile(url_template, url, error))
    {
      log_template_unref(url_template);
      return FALSE;
    }

  log_template_unref(self->url_template);
  self->url_template = url_template;
  self->state = HTTP_TARGET_OPERATIONAL;
  self->index = index_;
  g_snprintf(self->formatted_index, sizeof(self->formatted_index), "%d", index_);

  return TRUE;
}

void
http_lb_target_deinit(HTTPLoadBalancerTarget *self)
{
  log_template_unref(self->url_template);
}

gboolean
http_lb_target_is_url_templated(HTTPLoadBalancerTarget *self)
{
  return !log_template_is_literal_string(self->url_template);
}

const gchar *
http_lb_target_get_literal_url(HTTPLoadBalancerTarget *self)
{
  return log_template_get_literal_value(self->url_template, NULL);
}

static void
_escape_urlencoded(GString *result, const gchar *value, gsize value_len)
{
  APPEND_ZERO(value, value, value_len);
  g_string_append_uri_escaped(result, value, NULL, FALSE);
}

void
http_lb_target_format_templated_url(HTTPLoadBalancerTarget *self, LogMessage *msg,
                                    const LogTemplateOptions *template_options, GString *result)
{
  LogTemplateEvalOptions template_eval_options =
  {
    .opts = template_options,
    .tz = LTZ_LOCAL,
    .seq_num = -1,
    .context_id = self->formatted_index,
    .context_id_type = LM_VT_INTEGER,
    .escape = _escape_urlencoded,
  };
  log_template_format(self->url_template, msg, &template_eval_options, result);
}

/* HTTPLoadBalancerClient */

void
http_lb_client_init(HTTPLoadBalancerClient *self, HTTPLoadBalancer *lb)
{
  memset(self, 0, sizeof(*self));
  http_load_balancer_track_client(lb, self);
}

void
http_lb_client_deinit(HTTPLoadBalancerClient *self)
{
}

/* HTTPLoadBalancer */

static void
_recalculate_clients_per_target_goals(HTTPLoadBalancer *self)
{
  gint num_operational_targets = self->num_targets - self->num_failed_targets;

  if (num_operational_targets == 0)
    return;

  /* spread clients evenly */
  gint clients_per_target = self->num_clients / num_operational_targets;
  gint remainder = self->num_clients % num_operational_targets;

  /* assign the new targets */
  for (gint i = 0; i < self->num_targets; i++)
    {
      HTTPLoadBalancerTarget *target = &self->targets[i];

      if (target->state != HTTP_TARGET_OPERATIONAL)
        continue;

      target->max_clients = clients_per_target;
      if (remainder > 0)
        {
          target->max_clients++;
          remainder--;
        }
      msg_trace("Setting maximum number of workers for HTTP destination",
                evt_tag_str("url", target->url_template->template_str),
                evt_tag_int("max_clients", target->max_clients));
    }
}

static void
_switch_target(HTTPLoadBalancer *self, HTTPLoadBalancerClient *lbc, HTTPLoadBalancerTarget *new_target)
{
  /* self->lock must be held */
  if (lbc->target != new_target)
    {
      if (lbc->target)
        lbc->target->number_of_clients--;

      new_target->number_of_clients++;
      lbc->target = new_target;
    }
}

static HTTPLoadBalancerTarget *
_get_least_recently_tried_failing_target(HTTPLoadBalancer *self)
{
  time_t lru = 0;
  gint lru_index = -1;

  for (gint i = 0; i < self->num_targets; i++)
    {
      HTTPLoadBalancerTarget *target = &self->targets[i];

      if (target->state != HTTP_TARGET_FAILED)
        continue;

      if (lru_index < 0 || lru > target->last_failure_time)
        {
          lru = target->last_failure_time;
          lru_index = i;
        }
    }
  return &self->targets[lru_index >= 0 ? lru_index : 0];
}

static HTTPLoadBalancerTarget *
_recover_a_failed_target(HTTPLoadBalancer *self)
{
  self->last_recovery_attempt = time(NULL);
  /* allocation failed, try the target that failed the least recently. */
  return _get_least_recently_tried_failing_target(self);
}

static gboolean
_check_recovery(HTTPLoadBalancer *self, HTTPLoadBalancerClient *lbc, HTTPLoadBalancerTarget **new_target)
{
  if (self->num_failed_targets > 0)
    {
      time_t now = time(NULL);

      if (self->last_recovery_attempt == 0)
        self->last_recovery_attempt = now;

      if (now - self->last_recovery_attempt >= self->recovery_timeout)
        {
          *new_target = _recover_a_failed_target(self);
          return TRUE;
        }
    }
  return FALSE;
}

static HTTPLoadBalancerTarget *
_locate_target(HTTPLoadBalancer *self, HTTPLoadBalancerClient *lbc)
{
  gint start_index = lbc->target
                     ? (lbc->target->index + 1) % self->num_targets
                     : 0;
  for (gint i = 0; i < self->num_targets; i++)
    {
      HTTPLoadBalancerTarget *target = &self->targets[(i + start_index) % self->num_targets];

      if (target->state == HTTP_TARGET_OPERATIONAL &&
          target->number_of_clients < target->max_clients)
        return target;
    }

  return _recover_a_failed_target(self);
}

static gboolean
_check_rebalance(HTTPLoadBalancer *self, HTTPLoadBalancerClient *lbc, HTTPLoadBalancerTarget **new_target)
{
  /* Are we misbalanced? */
  if (lbc->target == NULL ||
      lbc->target->state != HTTP_TARGET_OPERATIONAL ||
      lbc->target->number_of_clients > lbc->target->max_clients)
    {
      *new_target = _locate_target(self, lbc);
      return TRUE;
    }
  return FALSE;
}

HTTPLoadBalancerTarget *
http_load_balancer_choose_target(HTTPLoadBalancer *self, HTTPLoadBalancerClient *lbc)
{
  HTTPLoadBalancerTarget *new_target;

  g_mutex_lock(&self->lock);

  new_target = lbc->target;
  if (_check_recovery(self, lbc, &new_target) ||
      _check_rebalance(self, lbc, &new_target))
    _switch_target(self, lbc, new_target);

  g_mutex_unlock(&self->lock);
  return lbc->target;
}

gboolean
http_load_balancer_add_target(HTTPLoadBalancer *self, const gchar *url, GError **error)
{
  gint n = self->num_targets++;

  self->targets = g_renew(HTTPLoadBalancerTarget, self->targets, self->num_targets);
  return http_lb_target_init(&self->targets[n], url, n, error);
}

void
http_load_balancer_drop_all_targets(HTTPLoadBalancer *self)
{
  for (int i = 0; i < self->num_targets; i++)
    http_lb_target_deinit(&self->targets[i]);
  self->num_targets = 0;
}

void
http_load_balancer_track_client(HTTPLoadBalancer *self, HTTPLoadBalancerClient *lbc)
{
  g_mutex_lock(&self->lock);
  self->num_clients++;
  _recalculate_clients_per_target_goals(self);
  g_mutex_unlock(&self->lock);
}

void
http_load_balancer_set_target_failed(HTTPLoadBalancer *self, HTTPLoadBalancerTarget *target)
{
  g_mutex_lock(&self->lock);
  if (target->state != HTTP_TARGET_FAILED)
    {
      msg_debug("Load balancer target failed, removing from rotation",
                evt_tag_str("url", target->url_template->template_str));
      self->num_failed_targets++;
      target->state = HTTP_TARGET_FAILED;
      _recalculate_clients_per_target_goals(self);
    }
  target->last_failure_time = time(NULL);
  g_mutex_unlock(&self->lock);
}

void
http_load_balancer_set_target_successful(HTTPLoadBalancer *self, HTTPLoadBalancerTarget *target)
{
  g_mutex_lock(&self->lock);
  if (target->state != HTTP_TARGET_OPERATIONAL)
    {
      msg_debug("Load balancer target recovered, adding back to rotation",
                evt_tag_str("url", target->url_template->template_str));
      self->num_failed_targets--;
      target->state = HTTP_TARGET_OPERATIONAL;
      _recalculate_clients_per_target_goals(self);
    }
  g_mutex_unlock(&self->lock);
}

gboolean
http_load_balancer_is_url_templated(HTTPLoadBalancer *self)
{
  for (gint i = 0; i < self->num_targets; i++)
    {
      if (http_lb_target_is_url_templated(&self->targets[i]))
        return TRUE;
    }

  return FALSE;
}

void
http_load_balancer_set_recovery_timeout(HTTPLoadBalancer *self, gint recovery_timeout)
{
  self->recovery_timeout = recovery_timeout;
}

HTTPLoadBalancer *
http_load_balancer_new(void)
{
  HTTPLoadBalancer *self = g_new0(HTTPLoadBalancer, 1);

  g_mutex_init(&self->lock);
  self->recovery_timeout = 60;
  return self;
}

void
http_load_balancer_free(HTTPLoadBalancer *self)
{
  http_load_balancer_drop_all_targets(self);
  g_free(self->targets);
  g_mutex_clear(&self->lock);
  g_free(self);
}