Coverage Report

Created: 2026-01-09 06:23

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/haproxy/src/event_hdl.c
Line
Count
Source
1
/*
2
 * general purpose event handlers management
3
 *
4
 * Copyright 2022 HAProxy Technologies
5
 *
6
 * This program is free software; you can redistribute it and/or modify
7
 * it under the terms of the GNU General Public License as published by
8
 * the Free Software Foundation; either version 2 of the License, or
9
 * (at your option) any later version.
10
 *
11
 * This program is distributed in the hope that it will be useful,
12
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14
 * GNU General Public License for more details.
15
 *
16
 * You should have received a copy of the GNU General Public License
17
 * along with this program; if not, write to the Free Software
18
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
19
 */
20
21
#include <string.h>
22
#include <haproxy/event_hdl.h>
23
#include <haproxy/compiler.h>
24
#include <haproxy/task.h>
25
#include <haproxy/tools.h>
26
#include <haproxy/errors.h>
27
#include <haproxy/signal.h>
28
#include <haproxy/xxhash.h>
29
#include <haproxy/cfgparse.h>
30
31
/* event types changes in event_hdl-t.h file should be reflected in the
32
 * map below to allow string to type and type to string conversions
33
 */
34
static struct event_hdl_sub_type_map event_hdl_sub_type_map[] = {
35
  {"NONE",                EVENT_HDL_SUB_NONE},
36
  {"SERVER",              EVENT_HDL_SUB_SERVER},
37
  {"SERVER_ADD",          EVENT_HDL_SUB_SERVER_ADD},
38
  {"SERVER_DEL",          EVENT_HDL_SUB_SERVER_DEL},
39
  {"SERVER_UP",           EVENT_HDL_SUB_SERVER_UP},
40
  {"SERVER_DOWN",         EVENT_HDL_SUB_SERVER_DOWN},
41
  {"SERVER_STATE",        EVENT_HDL_SUB_SERVER_STATE},
42
  {"SERVER_ADMIN",        EVENT_HDL_SUB_SERVER_ADMIN},
43
  {"SERVER_CHECK",        EVENT_HDL_SUB_SERVER_CHECK},
44
  {"SERVER_INETADDR",     EVENT_HDL_SUB_SERVER_INETADDR},
45
  {"PAT_REF",             EVENT_HDL_SUB_PAT_REF},
46
  {"PAT_REF_ADD",         EVENT_HDL_SUB_PAT_REF_ADD},
47
  {"PAT_REF_DEL",         EVENT_HDL_SUB_PAT_REF_DEL},
48
  {"PAT_REF_SET",         EVENT_HDL_SUB_PAT_REF_SET},
49
  {"PAT_REF_COMMIT",      EVENT_HDL_SUB_PAT_REF_COMMIT},
50
  {"PAT_REF_CLEAR",       EVENT_HDL_SUB_PAT_REF_CLEAR},
51
};
52
53
/* internal types (only used in this file) */
54
struct event_hdl_async_task_default_ctx
55
{
56
  event_hdl_async_equeue e_queue; /* event queue list */
57
  event_hdl_cb_async func; /* event handling func */
58
};
59
60
/* memory pools declarations */
61
DECLARE_STATIC_TYPED_POOL(pool_head_sub, "ehdl_sub", struct event_hdl_sub);
62
DECLARE_STATIC_TYPED_POOL(pool_head_sub_event, "ehdl_sub_e", struct event_hdl_async_event);
63
DECLARE_STATIC_TYPED_POOL(pool_head_sub_event_data, "ehdl_sub_ed", struct event_hdl_async_event_data);
64
DECLARE_STATIC_TYPED_POOL(pool_head_sub_taskctx, "ehdl_sub_tctx", struct event_hdl_async_task_default_ctx);
65
66
/* global event_hdl tunables (public variable) */
67
struct event_hdl_tune event_hdl_tune;
68
69
/* global subscription list (implicit where NULL is used as sublist argument) */
70
static event_hdl_sub_list global_event_hdl_sub_list;
71
72
/* every known subscription lists are tracked in this list (including the global one) */
73
static struct mt_list known_event_hdl_sub_list = MT_LIST_HEAD_INIT(known_event_hdl_sub_list);
74
75
static void _event_hdl_sub_list_destroy(event_hdl_sub_list *sub_list);
76
77
static void event_hdl_deinit(struct sig_handler *sh)
78
0
{
79
0
  event_hdl_sub_list *cur_list;
80
0
  struct mt_list back;
81
82
  /* destroy all known subscription lists */
83
0
  MT_LIST_FOR_EACH_ENTRY_UNLOCKED(cur_list, &known_event_hdl_sub_list, known, back) {
84
    /* remove cur elem from list and free it */
85
0
    _event_hdl_sub_list_destroy(cur_list);
86
0
    cur_list = NULL;
87
0
  }
88
0
}
89
90
static void event_hdl_init(void)
91
0
{
92
  /* initialize global subscription list */
93
0
  event_hdl_sub_list_init(&global_event_hdl_sub_list);
94
  /* register the deinit function, will be called on soft-stop */
95
0
  signal_register_fct(0, event_hdl_deinit, 0);
96
97
  /* set some default values */
98
0
  event_hdl_tune.max_events_at_once = EVENT_HDL_MAX_AT_ONCE;
99
0
}
100
101
/* general purpose hashing function when you want to compute
102
 * an ID based on <scope> x <name>
103
 * It is your responsibility to make sure <scope> is not used
104
 * elsewhere in the code (or that you are fine with sharing
105
 * the scope).
106
 */
107
inline uint64_t event_hdl_id(const char *scope, const char *name)
108
0
{
109
0
  XXH64_state_t state;
110
111
0
  XXH64_reset(&state, 0);
112
0
  XXH64_update(&state, scope, strlen(scope));
113
0
  XXH64_update(&state, name, strlen(name));
114
0
  return XXH64_digest(&state);
115
0
}
116
117
/* takes a sub_type as input, returns corresponding sub_type
118
 * printable string or "N/A" if not found.
119
 * If not found, an error will be reported to stderr so the developers
120
 * know that a sub_type is missing its associated string in event_hdl-t.h
121
 */
122
const char *event_hdl_sub_type_to_string(struct event_hdl_sub_type sub_type)
123
0
{
124
0
  int it;
125
126
0
  for (it = 0; it < (int)(sizeof(event_hdl_sub_type_map) / sizeof(event_hdl_sub_type_map[0])); it++) {
127
0
    if (sub_type.family == event_hdl_sub_type_map[it].type.family &&
128
0
        sub_type.subtype == event_hdl_sub_type_map[it].type.subtype)
129
0
      return event_hdl_sub_type_map[it].name;
130
0
  }
131
0
  ha_alert("event_hdl-t.h: missing sub_type string representation.\n"
132
0
     "Please reflect any changes in event_hdl_sub_type_map.\n");
133
0
  return "N/A";
134
0
}
135
136
/* returns the internal sub_type corresponding
137
 * to the printable representation <name>
138
 * or EVENT_HDL_SUB_NONE if no such event exists
139
 * (see event_hdl-t.h for the complete list of supported types)
140
 */
141
struct event_hdl_sub_type event_hdl_string_to_sub_type(const char *name)
142
0
{
143
0
  int it;
144
145
0
  for (it = 0; it < (int)(sizeof(event_hdl_sub_type_map) / sizeof(event_hdl_sub_type_map[0])); it++) {
146
0
    if (strcmp(name, event_hdl_sub_type_map[it].name) == 0)
147
0
      return event_hdl_sub_type_map[it].type;
148
0
  }
149
0
  return EVENT_HDL_SUB_NONE;
150
0
}
151
152
/* Takes <subscriptions> sub list as input, returns a printable string
153
 * containing every sub_types contained in <subscriptions>
154
 * separated by '|' char.
155
 * Returns NULL if no sub_types are found in <subscriptions>
156
 * This functions leverages memprintf, thus it is up to the
157
 * caller to free the returned value (if != NULL) when he no longer
158
 * uses it.
159
 */
160
char *event_hdl_sub_type_print(struct event_hdl_sub_type subscriptions)
161
0
{
162
0
  char *out = NULL;
163
0
  int it;
164
0
  uint8_t first = 1;
165
166
0
  for (it = 0; it < (int)(sizeof(event_hdl_sub_type_map) / sizeof(event_hdl_sub_type_map[0])); it++) {
167
0
    if (subscriptions.family == event_hdl_sub_type_map[it].type.family &&
168
0
        ((subscriptions.subtype & event_hdl_sub_type_map[it].type.subtype) ==
169
0
         event_hdl_sub_type_map[it].type.subtype)) {
170
0
      if (first) {
171
0
        memprintf(&out, "%s", event_hdl_sub_type_map[it].name);
172
0
        first--;
173
0
      }
174
0
      else
175
0
        memprintf(&out, "%s%s%s", out, "|", event_hdl_sub_type_map[it].name);
176
0
    }
177
0
  }
178
179
0
  return out;
180
0
}
181
182
/* event_hdl debug/reporting function */
183
typedef void (*event_hdl_report_hdl_state_func)(const char *fmt, ...);
184
static void event_hdl_report_hdl_state(event_hdl_report_hdl_state_func report_func,
185
                                       const struct event_hdl *hdl, const char *what, const char *state)
186
0
{
187
0
  report_func("[event_hdl]:%s (%s)'#%llu@%s': %s\n",
188
0
        what,
189
0
        (hdl->async) ? "ASYNC" : "SYNC",
190
0
        (long long unsigned int)hdl->id,
191
0
        hdl->dorigin,
192
0
        state);
193
0
}
194
195
static inline void _event_hdl_async_data_drop(struct event_hdl_async_event_data *data)
196
0
{
197
0
  if (HA_ATOMIC_SUB_FETCH(&data->refcount, 1) == 0) {
198
    /* we were the last one holding a reference to event data - free required */
199
0
    if (data->mfree) {
200
      /* Some event data members are dynamically allocated and thus
201
       * require specific cleanup using user-provided function.
202
       * We directly pass a pointer to internal data storage but
203
       * we only expect the cleanup function to typecast it in the
204
       * relevant data type to give enough context to the function to
205
       * perform the cleanup on data members, and not actually freeing
206
       * data pointer since it is our internal buffer :)
207
       */
208
0
      data->mfree(&data->data);
209
0
    }
210
0
    pool_free(pool_head_sub_event_data, data);
211
0
  }
212
0
}
213
214
void event_hdl_async_free_event(struct event_hdl_async_event *e)
215
0
{
216
0
  if (unlikely(event_hdl_sub_type_equal(e->type, EVENT_HDL_SUB_END))) {
217
    /* last event for hdl, special case */
218
    /* free subscription entry as we're the last one still using it
219
     * (it is already removed from mt_list, no race can occur)
220
     */
221
0
    event_hdl_drop(e->sub_mgmt.this);
222
0
    HA_ATOMIC_DEC(&jobs);
223
0
  }
224
0
  else if (e->_data)
225
0
    _event_hdl_async_data_drop(e->_data); /* data wrapper */
226
0
  pool_free(pool_head_sub_event, e);
227
0
}
228
229
/* wakeup the task depending on its type:
230
 * normal async mode internally uses tasklets but advanced async mode
231
 * allows both tasks and tasklets.
232
 * While tasks and tasklets may be easily casted, we need to use the proper
233
 * API to wake them up (the waiting queues are exclusive).
234
 */
235
static void event_hdl_task_wakeup(struct tasklet *task)
236
0
{
237
0
  if (TASK_IS_TASKLET(task))
238
0
    tasklet_wakeup(task);
239
0
  else
240
0
    task_wakeup((struct task *)task, TASK_WOKEN_OTHER); /* TODO: switch to TASK_WOKEN_EVENT? */
241
0
}
242
243
/* task handler used for normal async subscription mode
244
 * if you use advanced async subscription mode, you can use this
245
 * as an example to implement your own task wrapper
246
 */
247
static struct task *event_hdl_async_task_default(struct task *task, void *ctx, unsigned int state)
248
0
{
249
0
  struct tasklet *tl = (struct tasklet *)task;
250
0
  struct event_hdl_async_task_default_ctx *task_ctx = ctx;
251
0
  struct event_hdl_async_event *event;
252
0
  int max_notif_at_once_it = 0;
253
0
  uint8_t done = 0;
254
255
  /* run through e_queue, and call func() for each event
256
   * if we read END event, it indicates we must stop:
257
   * no more events to come (handler is unregistered)
258
   * so we must free task_ctx and stop task
259
   */
260
0
  while (max_notif_at_once_it < event_hdl_tune.max_events_at_once &&
261
0
         (event = event_hdl_async_equeue_pop(&task_ctx->e_queue)))
262
0
  {
263
0
    if (event_hdl_sub_type_equal(event->type, EVENT_HDL_SUB_END)) {
264
0
      done = 1;
265
0
      event_hdl_async_free_event(event);
266
      /* break is normally not even required, EVENT_HDL_SUB_END
267
       * is guaranteed to be last event of e_queue
268
       * (because in normal mode one sub == one e_queue)
269
       */
270
0
      break;
271
0
    }
272
0
    else {
273
0
      struct event_hdl_cb cb;
274
275
0
      cb.e_type = event->type;
276
0
      cb.e_data = event->data;
277
0
      cb.sub_mgmt = &event->sub_mgmt;
278
0
      cb._sync = 0;
279
280
      /* call user function */
281
0
      task_ctx->func(&cb, event->private);
282
0
      max_notif_at_once_it++;
283
0
    }
284
0
    event_hdl_async_free_event(event);
285
0
  }
286
287
0
  if (done) {
288
    /* our job is done, subscription is over: no more events to come */
289
0
    pool_free(pool_head_sub_taskctx, task_ctx);
290
0
    tasklet_free(tl);
291
0
    return NULL;
292
0
  }
293
0
  return task;
294
0
}
295
296
/* internal subscription mgmt functions */
297
static inline struct event_hdl_sub_type _event_hdl_getsub(struct event_hdl_sub *cur_sub)
298
0
{
299
0
  return cur_sub->sub;
300
0
}
301
302
static inline struct event_hdl_sub_type _event_hdl_getsub_async(struct event_hdl_sub *cur_sub)
303
0
{
304
0
  struct mt_list lock;
305
0
  struct event_hdl_sub_type type = EVENT_HDL_SUB_NONE;
306
307
0
  lock = mt_list_lock_full(&cur_sub->mt_list);
308
0
  if (lock.next != &cur_sub->mt_list)
309
0
    type = _event_hdl_getsub(cur_sub);
310
  // else already removed
311
0
  mt_list_unlock_full(&cur_sub->mt_list, lock);
312
0
  return type;
313
0
}
314
315
static inline int _event_hdl_resub(struct event_hdl_sub *cur_sub, struct event_hdl_sub_type type)
316
0
{
317
0
  if (!event_hdl_sub_family_equal(cur_sub->sub, type))
318
0
    return 0; /* family types differ, do nothing */
319
0
  cur_sub->sub.subtype = type.subtype; /* new subtype assignment */
320
0
  return 1;
321
0
}
322
323
static inline int _event_hdl_resub_async(struct event_hdl_sub *cur_sub, struct event_hdl_sub_type type)
324
0
{
325
0
  int status = 0;
326
0
  struct mt_list lock;
327
328
0
  lock = mt_list_lock_full(&cur_sub->mt_list);
329
0
  if (lock.next != &cur_sub->mt_list)
330
0
    status = _event_hdl_resub(cur_sub, type);
331
  // else already removed
332
0
  mt_list_unlock_full(&cur_sub->mt_list, lock);
333
0
  return status;
334
0
}
335
336
static inline void _event_hdl_unsubscribe(struct event_hdl_sub *del_sub)
337
0
{
338
0
  struct mt_list lock;
339
340
0
  if (del_sub->hdl.async) {
341
    /* ASYNC SUB MODE */
342
    /* push EVENT_HDL_SUB_END (to notify the task that the subscription is dead) */
343
344
    /* push END EVENT in busy state so we can safely wakeup
345
     * the task before releasing it.
346
     * Not doing that would expose us to a race where the task could've already
347
     * consumed the END event before the wakeup, and some tasks
348
     * kill themselves (ie: normal async mode) when they receive such event
349
     */
350
0
    HA_ATOMIC_INC(&del_sub->hdl.async_equeue->size);
351
0
    mt_list_lock_elem(&del_sub->async_end->mt_list);
352
0
    lock = mt_list_lock_prev(&del_sub->hdl.async_equeue->head);
353
354
    /* wake up the task */
355
0
    event_hdl_task_wakeup(del_sub->hdl.async_task);
356
357
    /* unlock END EVENT (we're done, the task is now free to consume it) */
358
0
    mt_list_unlock_full(&del_sub->async_end->mt_list, lock);
359
360
    /* we don't free sub here
361
    * freeing will be performed by async task so it can safely rely
362
    * on the pointer until it notices it
363
    */
364
0
  } else {
365
    /* SYNC SUB MODE */
366
367
    /* we can directly free the subscription:
368
     * no other thread can access it since we successfully
369
     * removed it from the list
370
     */
371
0
    event_hdl_drop(del_sub);
372
0
  }
373
0
}
374
375
static inline void _event_hdl_unsubscribe_async(struct event_hdl_sub *del_sub)
376
0
{
377
0
  if (!MT_LIST_DELETE(&del_sub->mt_list))
378
0
    return; /* already removed (but may be pending in e_queues) */
379
0
  _event_hdl_unsubscribe(del_sub);
380
0
}
381
382
/* sub_mgmt function pointers (for handlers) */
383
static struct event_hdl_sub_type event_hdl_getsub_sync(const struct event_hdl_sub_mgmt *mgmt)
384
0
{
385
0
  if (!mgmt)
386
0
    return EVENT_HDL_SUB_NONE;
387
388
0
  if (!mgmt->this)
389
0
    return EVENT_HDL_SUB_NONE; /* already removed from sync ctx */
390
0
  return _event_hdl_getsub(mgmt->this);
391
0
}
392
393
static struct event_hdl_sub_type event_hdl_getsub_async(const struct event_hdl_sub_mgmt *mgmt)
394
0
{
395
0
  if (!mgmt)
396
0
    return EVENT_HDL_SUB_NONE;
397
398
0
  return _event_hdl_getsub_async(mgmt->this);
399
0
}
400
401
static int event_hdl_resub_sync(const struct event_hdl_sub_mgmt *mgmt, struct event_hdl_sub_type type)
402
0
{
403
0
  if (!mgmt)
404
0
    return 0;
405
406
0
  if (!mgmt->this)
407
0
    return 0; /* already removed from sync ctx */
408
0
  return _event_hdl_resub(mgmt->this, type);
409
0
}
410
411
static int event_hdl_resub_async(const struct event_hdl_sub_mgmt *mgmt, struct event_hdl_sub_type type)
412
0
{
413
0
  if (!mgmt)
414
0
    return 0;
415
416
0
  return _event_hdl_resub_async(mgmt->this, type);
417
0
}
418
419
static void event_hdl_unsubscribe_sync(const struct event_hdl_sub_mgmt *mgmt)
420
0
{
421
0
  if (!mgmt)
422
0
    return;
423
424
0
  if (!mgmt->this)
425
0
    return; /* already removed from sync ctx */
426
427
  /* assuming that publish sync code will notice that mgmt->this is NULL
428
   * and will perform the list removal and _event_hdl_unsubscribe()
429
   * while still owning the lock
430
   */
431
0
  ((struct event_hdl_sub_mgmt *)mgmt)->this = NULL;
432
0
}
433
434
static void event_hdl_unsubscribe_async(const struct event_hdl_sub_mgmt *mgmt)
435
0
{
436
0
  if (!mgmt)
437
0
    return;
438
439
0
  _event_hdl_unsubscribe_async(mgmt->this);
440
0
}
441
442
0
#define EVENT_HDL_SUB_MGMT_ASYNC(_sub)  (struct event_hdl_sub_mgmt){ .this = _sub,        \
443
0
                                                                     .getsub = event_hdl_getsub_async,    \
444
0
                                                                     .resub = event_hdl_resub_async,    \
445
0
                                                                     .unsub = event_hdl_unsubscribe_async}
446
0
#define EVENT_HDL_SUB_MGMT_SYNC(_sub)   (struct event_hdl_sub_mgmt){ .this = _sub,        \
447
0
                                                                     .getsub = event_hdl_getsub_sync,   \
448
0
                                                                     .resub = event_hdl_resub_sync,   \
449
0
                                                                     .unsub = event_hdl_unsubscribe_sync}
450
451
struct event_hdl_sub *event_hdl_subscribe_ptr(event_hdl_sub_list *sub_list,
452
                                              struct event_hdl_sub_type e_type, struct event_hdl hdl)
453
0
{
454
0
  struct event_hdl_sub *new_sub = NULL;
455
0
  struct mt_list back;
456
0
  struct event_hdl_async_task_default_ctx *task_ctx = NULL;
457
0
  struct mt_list lock;
458
459
0
  if (!sub_list)
460
0
    sub_list = &global_event_hdl_sub_list; /* fall back to global list */
461
462
  /* hdl API consistency check */
463
  /*FIXME: do we need to ensure that if private is set, private_free should be set as well? */
464
0
  BUG_ON((!hdl.async && !hdl.sync_ptr) ||
465
0
         (hdl.async == EVENT_HDL_ASYNC_MODE_NORMAL && !hdl.async_ptr) ||
466
0
         (hdl.async == EVENT_HDL_ASYNC_MODE_ADVANCED &&
467
0
    (!hdl.async_equeue || !hdl.async_task)));
468
469
0
  new_sub = pool_alloc(pool_head_sub);
470
0
  if (new_sub == NULL) {
471
0
    goto memory_error;
472
0
  }
473
474
  /* assignments */
475
0
  new_sub->sub.family = e_type.family;
476
0
  new_sub->sub.subtype = e_type.subtype;
477
0
  new_sub->flags = 0;
478
0
  new_sub->hdl = hdl;
479
480
0
  if (hdl.async) {
481
    /* async END event pre-allocation */
482
0
    new_sub->async_end = pool_alloc(pool_head_sub_event);
483
0
    if (!new_sub->async_end) {
484
      /* memory error */
485
0
      goto memory_error;
486
0
    }
487
0
    if (hdl.async == EVENT_HDL_ASYNC_MODE_NORMAL) {
488
      /* normal mode: no task provided, we must initialize it */
489
490
      /* initialize task context */
491
0
      task_ctx = pool_alloc(pool_head_sub_taskctx);
492
493
0
      if (!task_ctx) {
494
        /* memory error */
495
0
        goto memory_error;
496
0
      }
497
0
      event_hdl_async_equeue_init(&task_ctx->e_queue);
498
0
      task_ctx->func = new_sub->hdl.async_ptr;
499
500
0
      new_sub->hdl.async_equeue = &task_ctx->e_queue;
501
0
      new_sub->hdl.async_task = tasklet_new();
502
503
0
      if (!new_sub->hdl.async_task) {
504
        /* memory error */
505
0
        goto memory_error;
506
0
      }
507
0
      new_sub->hdl.async_task->context = task_ctx;
508
0
      new_sub->hdl.async_task->process = event_hdl_async_task_default;
509
0
    }
510
    /* initialize END event (used to notify about subscription ending)
511
     * used by both normal and advanced mode:
512
     *  - to safely terminate the task in normal mode
513
     *  - to safely free subscription and
514
     *    keep track of active subscriptions in advanced mode
515
     */
516
0
    new_sub->async_end->type = EVENT_HDL_SUB_END;
517
0
    new_sub->async_end->sub_mgmt = EVENT_HDL_SUB_MGMT_ASYNC(new_sub);
518
0
    new_sub->async_end->private = new_sub->hdl.private;
519
0
    new_sub->async_end->_data = NULL;
520
0
    MT_LIST_INIT(&new_sub->async_end->mt_list);
521
0
  }
522
  /* set refcount to 2:
523
   * 1 for handler (because handler can manage the subscription itself)
524
   * 1 for caller (will be dropped automatically if caller use the non-ptr version)
525
   */
526
0
  new_sub->refcount = 2;
527
528
  /* ready for registration */
529
0
  MT_LIST_INIT(&new_sub->mt_list);
530
531
0
  lock = mt_list_lock_full(&sub_list->known);
532
533
  /* check if such identified hdl is not already registered */
534
0
  if (hdl.id) {
535
0
    struct event_hdl_sub *cur_sub;
536
0
    uint8_t found = 0;
537
538
0
    MT_LIST_FOR_EACH_ENTRY_LOCKED(cur_sub, &sub_list->head, mt_list, back) {
539
0
      if (hdl.id == cur_sub->hdl.id) {
540
        /* we found matching registered hdl */
541
0
        found = 1;
542
0
        break;
543
0
      }
544
0
    }
545
0
    if (found) {
546
      /* error already registered */
547
0
      mt_list_unlock_full(&sub_list->known, lock);
548
0
      event_hdl_report_hdl_state(ha_alert, &hdl, "SUB", "could not subscribe: subscription with this id already exists");
549
0
      goto cleanup;
550
0
    }
551
0
  }
552
553
0
  if (lock.next == &sub_list->known) {
554
    /* this is an expected corner case on de-init path, a subscribe attempt
555
     * was made but the subscription list is already destroyed, we pretend
556
     * it is a memory/IO error since it should not be long before haproxy
557
     * enters the deinit() function anyway
558
     */
559
0
    mt_list_unlock_full(&sub_list->known, lock);
560
0
    goto cleanup;
561
0
  }
562
563
  /* Append in list (global or user specified list).
564
   * For now, append when sync mode, and insert when async mode
565
   * so that async handlers are executed first
566
   */
567
0
  if (hdl.async) {
568
    /* Prevent the task from being aborted on soft-stop: let's wait
569
     * until the END event is acknowledged by the task.
570
     * (decrease is performed in event_hdl_async_free_event())
571
     *
572
     * If we don't do this, event_hdl API will leak and we won't give
573
     * a chance to the event-handling task to perform cleanup
574
     */
575
0
    HA_ATOMIC_INC(&jobs);
576
    /* async mode, insert at the beginning of the list */
577
0
    MT_LIST_INSERT(&sub_list->head, &new_sub->mt_list);
578
0
  } else {
579
    /* sync mode, append at the end of the list */
580
0
    MT_LIST_APPEND(&sub_list->head, &new_sub->mt_list);
581
0
  }
582
583
0
  mt_list_unlock_full(&sub_list->known, lock);
584
585
0
  return new_sub;
586
587
0
 cleanup:
588
0
  if (new_sub) {
589
0
    if (hdl.async == EVENT_HDL_ASYNC_MODE_NORMAL) {
590
0
      tasklet_free(new_sub->hdl.async_task);
591
0
      pool_free(pool_head_sub_taskctx, task_ctx);
592
0
    }
593
0
    if (hdl.async)
594
0
      pool_free(pool_head_sub_event, new_sub->async_end);
595
0
    pool_free(pool_head_sub, new_sub);
596
0
  }
597
598
0
  return NULL;
599
600
0
 memory_error:
601
0
  event_hdl_report_hdl_state(ha_warning, &hdl, "SUB", "could not register subscription due to memory error");
602
0
  goto cleanup;
603
0
}
604
605
void event_hdl_take(struct event_hdl_sub *sub)
606
0
{
607
0
  HA_ATOMIC_INC(&sub->refcount);
608
0
}
609
610
void event_hdl_drop(struct event_hdl_sub *sub)
611
0
{
612
0
  if (HA_ATOMIC_SUB_FETCH(&sub->refcount, 1) != 0)
613
0
    return;
614
615
  /* we were the last one holding a reference to event sub - free required */
616
0
  if (sub->hdl.private_free) {
617
    /* free private data if specified upon registration */
618
0
    sub->hdl.private_free(sub->hdl.private);
619
0
  }
620
0
  pool_free(pool_head_sub, sub);
621
0
}
622
623
int event_hdl_resubscribe(struct event_hdl_sub *cur_sub, struct event_hdl_sub_type type)
624
0
{
625
0
  return _event_hdl_resub_async(cur_sub, type);
626
0
}
627
628
void _event_hdl_pause(struct event_hdl_sub *cur_sub)
629
0
{
630
0
  cur_sub->flags |= EHDL_SUB_F_PAUSED;
631
0
}
632
633
void event_hdl_pause(struct event_hdl_sub *cur_sub)
634
0
{
635
0
  struct mt_list lock;
636
637
0
  lock = mt_list_lock_full(&cur_sub->mt_list);
638
0
  if (lock.next != &cur_sub->mt_list)
639
0
    _event_hdl_pause(cur_sub);
640
  // else already removed
641
0
  mt_list_unlock_full(&cur_sub->mt_list, lock);
642
0
}
643
644
void _event_hdl_resume(struct event_hdl_sub *cur_sub)
645
0
{
646
0
  cur_sub->flags &= ~EHDL_SUB_F_PAUSED;
647
0
}
648
649
void event_hdl_resume(struct event_hdl_sub *cur_sub)
650
0
{
651
0
  struct mt_list lock;
652
653
0
  lock = mt_list_lock_full(&cur_sub->mt_list);
654
0
  if (lock.next != &cur_sub->mt_list)
655
0
    _event_hdl_resume(cur_sub);
656
  // else already removed
657
0
  mt_list_unlock_full(&cur_sub->mt_list, lock);
658
0
}
659
660
void event_hdl_unsubscribe(struct event_hdl_sub *del_sub)
661
0
{
662
0
  _event_hdl_unsubscribe_async(del_sub);
663
  /* drop refcount, assuming caller no longer use ptr */
664
0
  event_hdl_drop(del_sub);
665
0
}
666
667
int event_hdl_subscribe(event_hdl_sub_list *sub_list, struct event_hdl_sub_type e_type, struct event_hdl hdl)
668
0
{
669
0
  struct event_hdl_sub *sub;
670
671
0
  sub = event_hdl_subscribe_ptr(sub_list, e_type, hdl);
672
0
  if (sub) {
673
    /* drop refcount because the user is not willing to hold a reference */
674
0
    event_hdl_drop(sub);
675
0
    return 1;
676
0
  }
677
0
  return 0;
678
0
}
679
680
/* Subscription external lookup functions
681
 */
682
int event_hdl_lookup_unsubscribe(event_hdl_sub_list *sub_list,
683
                                 uint64_t lookup_id)
684
0
{
685
0
  struct event_hdl_sub *del_sub = NULL;
686
0
  struct mt_list back;
687
0
  int found = 0;
688
689
0
  if (!sub_list)
690
0
    sub_list = &global_event_hdl_sub_list; /* fall back to global list */
691
692
0
  MT_LIST_FOR_EACH_ENTRY_LOCKED(del_sub, &sub_list->head, mt_list, back) {
693
0
    if (lookup_id == del_sub->hdl.id) {
694
      /* we found matching registered hdl */
695
0
      mt_list_unlock_self(&del_sub->mt_list);
696
0
      _event_hdl_unsubscribe(del_sub);
697
0
      del_sub = NULL;
698
0
      found = 1;
699
0
      break; /* id is unique, stop searching */
700
0
    }
701
0
  }
702
0
  return found;
703
0
}
704
705
int event_hdl_lookup_resubscribe(event_hdl_sub_list *sub_list,
706
                                 uint64_t lookup_id, struct event_hdl_sub_type type)
707
0
{
708
0
  struct event_hdl_sub *cur_sub = NULL;
709
0
  struct mt_list back;
710
0
  int status = 0;
711
712
0
  if (!sub_list)
713
0
    sub_list = &global_event_hdl_sub_list; /* fall back to global list */
714
715
0
  MT_LIST_FOR_EACH_ENTRY_LOCKED(cur_sub, &sub_list->head, mt_list, back) {
716
0
    if (lookup_id == cur_sub->hdl.id) {
717
      /* we found matching registered hdl */
718
0
      status = _event_hdl_resub(cur_sub, type);
719
0
      break; /* id is unique, stop searching */
720
0
    }
721
0
  }
722
0
  return status;
723
0
}
724
725
int event_hdl_lookup_pause(event_hdl_sub_list *sub_list,
726
                           uint64_t lookup_id)
727
0
{
728
0
  struct event_hdl_sub *cur_sub = NULL;
729
0
  struct mt_list back;
730
0
  int found = 0;
731
732
0
  if (!sub_list)
733
0
    sub_list = &global_event_hdl_sub_list; /* fall back to global list */
734
735
0
  MT_LIST_FOR_EACH_ENTRY_LOCKED(cur_sub, &sub_list->head, mt_list, back) {
736
0
    if (lookup_id == cur_sub->hdl.id) {
737
      /* we found matching registered hdl */
738
0
      _event_hdl_pause(cur_sub);
739
0
      found = 1;
740
0
      break; /* id is unique, stop searching */
741
0
    }
742
0
  }
743
0
  return found;
744
0
}
745
746
int event_hdl_lookup_resume(event_hdl_sub_list *sub_list,
747
                            uint64_t lookup_id)
748
0
{
749
0
  struct event_hdl_sub *cur_sub = NULL;
750
0
  struct mt_list back;
751
0
  int found = 0;
752
753
0
  if (!sub_list)
754
0
    sub_list = &global_event_hdl_sub_list; /* fall back to global list */
755
756
0
  MT_LIST_FOR_EACH_ENTRY_LOCKED(cur_sub, &sub_list->head, mt_list, back) {
757
0
    if (lookup_id == cur_sub->hdl.id) {
758
      /* we found matching registered hdl */
759
0
      _event_hdl_resume(cur_sub);
760
0
      found = 1;
761
0
      break; /* id is unique, stop searching */
762
0
    }
763
0
  }
764
0
  return found;
765
0
}
766
767
struct event_hdl_sub *event_hdl_lookup_take(event_hdl_sub_list *sub_list,
768
                                            uint64_t lookup_id)
769
0
{
770
0
  struct event_hdl_sub *cur_sub = NULL;
771
0
  struct mt_list back;
772
0
  uint8_t found = 0;
773
774
0
  if (!sub_list)
775
0
    sub_list = &global_event_hdl_sub_list; /* fall back to global list */
776
777
0
  MT_LIST_FOR_EACH_ENTRY_LOCKED(cur_sub, &sub_list->head, mt_list, back) {
778
0
    if (lookup_id == cur_sub->hdl.id) {
779
      /* we found matching registered hdl */
780
0
      event_hdl_take(cur_sub);
781
0
      found = 1;
782
0
      break; /* id is unique, stop searching */
783
0
    }
784
0
  }
785
0
  if (found)
786
0
    return cur_sub;
787
0
  return NULL;
788
0
}
789
790
/* event publishing functions
791
 */
792
static int _event_hdl_publish(event_hdl_sub_list *sub_list, struct event_hdl_sub_type e_type,
793
                              const struct event_hdl_cb_data *data)
794
0
{
795
0
  struct event_hdl_sub *cur_sub;
796
0
  struct mt_list back;
797
0
  struct event_hdl_async_event_data *async_data = NULL; /* reuse async data for multiple async hdls */
798
0
  int error = 0;
799
800
0
  MT_LIST_FOR_EACH_ENTRY_LOCKED(cur_sub, &sub_list->head, mt_list, back) {
801
    /* notify each function that has subscribed to sub_family.type, unless paused */
802
0
    if ((cur_sub->sub.family == e_type.family) &&
803
0
        ((cur_sub->sub.subtype & e_type.subtype) == e_type.subtype) &&
804
0
        !(cur_sub->flags & EHDL_SUB_F_PAUSED)) {
805
      /* hdl should be notified */
806
0
      if (!cur_sub->hdl.async) {
807
        /* sync mode: simply call cb pointer
808
        * it is up to the callee to schedule a task if needed or
809
        * take specific precautions in order to return as fast as possible
810
        * and not use locks that are already held by the caller
811
        */
812
0
        struct event_hdl_cb cb;
813
0
        struct event_hdl_sub_mgmt sub_mgmt;
814
815
0
        sub_mgmt = EVENT_HDL_SUB_MGMT_SYNC(cur_sub);
816
0
        cb.e_type = e_type;
817
0
        if (data)
818
0
          cb.e_data = data->_ptr;
819
0
        else
820
0
          cb.e_data = NULL;
821
0
        cb.sub_mgmt = &sub_mgmt;
822
0
        cb._sync = 1;
823
824
        /* call user function */
825
0
        cur_sub->hdl.sync_ptr(&cb, cur_sub->hdl.private);
826
827
0
        if (!sub_mgmt.this) {
828
          /* user has performed hdl unsub
829
           * we must remove it from the list
830
           * then free it.
831
           */
832
0
          mt_list_unlock_self(&cur_sub->mt_list);
833
0
          _event_hdl_unsubscribe(cur_sub);
834
0
          cur_sub = NULL;
835
0
        }
836
0
      } else {
837
        /* async mode: here we need to prepare event data
838
         * and push it to the event_queue of the task(s)
839
         * responsible for consuming the events of current
840
         * subscription.
841
         * Once the event is pushed, we wake up the associated task.
842
         * This feature depends on <haproxy/task> that also
843
         * depends on <haproxy/pool>:
844
         * If STG_PREPARE+STG_POOL is not performed prior to publishing to
845
         * async handler, program may crash.
846
         * Hopefully, STG_PREPARE+STG_POOL should be done early in
847
         * HAProxy startup sequence.
848
         */
849
0
        struct event_hdl_async_event *new_event;
850
851
0
        new_event = pool_alloc(pool_head_sub_event);
852
0
        if (!new_event) {
853
0
          error = 1;
854
0
          break; /* stop on error */
855
0
        }
856
0
        new_event->type = e_type;
857
0
        new_event->private = cur_sub->hdl.private;
858
0
        new_event->when = date;
859
0
        new_event->sub_mgmt = EVENT_HDL_SUB_MGMT_ASYNC(cur_sub);
860
0
        if (data) {
861
          /* if this fails, please adjust EVENT_HDL_ASYNC_EVENT_DATA in
862
           * event_hdl-t.h file or consider providing dynamic struct members
863
           * to reduce overall struct size
864
           */
865
0
          BUG_ON(data->_size > sizeof(async_data->data));
866
0
          if (!async_data) {
867
            /* first async hdl reached - preparing async_data cache */
868
0
            async_data = pool_alloc(pool_head_sub_event_data);
869
0
            if (!async_data) {
870
0
              error = 1;
871
0
              pool_free(pool_head_sub_event, new_event);
872
0
              break; /* stop on error */
873
0
            }
874
875
            /* async data assignment */
876
0
            memcpy(async_data->data, data->_ptr, data->_size);
877
0
            async_data->mfree = data->_mfree;
878
            /* Initialize refcount, we start at 1 to prevent async
879
             * data from being freed by an async handler while we
880
             * still use it. We will drop the reference when the
881
             * publish is over.
882
             *
883
             * (first use, atomic operation not required)
884
             */
885
0
            async_data->refcount = 1;
886
0
          }
887
0
          new_event->_data = async_data;
888
0
          new_event->data = async_data->data;
889
          /* increment refcount because multiple hdls could
890
           * use the same async_data
891
           */
892
0
          HA_ATOMIC_INC(&async_data->refcount);
893
0
        } else {
894
0
          new_event->_data = NULL;
895
0
          new_event->data = NULL;
896
0
        }
897
898
        /* appending new event to event hdl queue */
899
0
        MT_LIST_INIT(&new_event->mt_list);
900
0
        HA_ATOMIC_INC(&cur_sub->hdl.async_equeue->size);
901
0
        MT_LIST_APPEND(&cur_sub->hdl.async_equeue->head, &new_event->mt_list);
902
903
        /* wake up the task */
904
0
        event_hdl_task_wakeup(cur_sub->hdl.async_task);
905
0
      } /* end async mode */
906
0
    } /* end hdl should be notified */
907
0
  } /* end mt_list */
908
0
  if (async_data) {
909
    /* we finished publishing, drop the reference on async data */
910
0
    _event_hdl_async_data_drop(async_data);
911
0
  } else {
912
    /* no async subscribers, we are responsible for calling the data
913
     * member freeing function if it was provided
914
     */
915
0
    if (data && data->_mfree)
916
0
      data->_mfree(data->_ptr);
917
0
  }
918
0
  if (error) {
919
0
    event_hdl_report_hdl_state(ha_warning, &cur_sub->hdl, "PUBLISH", "memory error");
920
0
    return 0;
921
0
  }
922
0
  return 1;
923
0
}
924
925
/* Publish function should not be used from high calling rate or time sensitive
926
 * places for now, because list lookup based on e_type is not optimized at
927
 * all!
928
 * Returns 1 in case of SUCCESS:
929
 *  Subscribed handlers were notified successfully
930
 * Returns 0 in case of FAILURE:
931
 *  FAILURE means memory error while handling the very first async handler from
932
 *  the subscription list.
933
 *  As async handlers are executed first within the list, when such failure occurs
934
 *  you can safely assume that no events were published for the current call
935
 */
936
int event_hdl_publish(event_hdl_sub_list *sub_list,
937
                      struct event_hdl_sub_type e_type, const struct event_hdl_cb_data *data)
938
0
{
939
0
  if (!e_type.family) {
940
    /* do nothing, these types are reserved for internal use only
941
     * (ie: unregistering) */
942
0
    return 0;
943
0
  }
944
0
  if (sub_list) {
945
    /* if sublist is provided, first publish event to list subscribers */
946
0
    return _event_hdl_publish(sub_list, e_type, data);
947
0
  } else {
948
    /* publish to global list */
949
0
    return _event_hdl_publish(&global_event_hdl_sub_list, e_type, data);
950
0
  }
951
0
}
952
953
void event_hdl_sub_list_init(event_hdl_sub_list *sub_list)
954
0
{
955
0
  BUG_ON(!sub_list); /* unexpected, global sublist is managed internally */
956
0
  MT_LIST_INIT(&sub_list->head);
957
0
  MT_LIST_APPEND(&known_event_hdl_sub_list, &sub_list->known);
958
0
}
959
960
/* internal function, assumes that sub_list ptr is always valid */
961
static void _event_hdl_sub_list_destroy(event_hdl_sub_list *sub_list)
962
0
{
963
0
  struct event_hdl_sub *cur_sub;
964
0
  struct mt_list back;
965
966
0
  MT_LIST_FOR_EACH_ENTRY_UNLOCKED(cur_sub, &sub_list->head, mt_list, back) {
967
    /* remove cur elem from list and free it */
968
0
    _event_hdl_unsubscribe(cur_sub);
969
0
    cur_sub = NULL;
970
0
  }
971
0
}
972
973
/* when a subscription list is no longer used, call this
974
 * to do the cleanup and make sure all related subscriptions are
975
 * safely ended according to their types
976
 */
977
void event_hdl_sub_list_destroy(event_hdl_sub_list *sub_list)
978
0
{
979
0
  BUG_ON(!sub_list); /* unexpected, global sublist is managed internally */
980
0
  if (!MT_LIST_DELETE(&sub_list->known))
981
0
    return; /* already destroyed */
982
0
  _event_hdl_sub_list_destroy(sub_list);
983
0
}
984
985
/* config parser for global "tune.events.max-events-at-once" */
986
static int event_hdl_parse_max_events_at_once(char **args, int section_type, struct proxy *curpx,
987
                                              const struct proxy *defpx, const char *file, int line,
988
                                              char **err)
989
0
{
990
0
  int arg = -1;
991
992
0
  if (too_many_args(1, args, err, NULL))
993
0
    return -1;
994
995
0
  if (*(args[1]) != 0)
996
0
    arg = atoi(args[1]);
997
998
0
  if (arg < 1 || arg > 10000) {
999
0
    memprintf(err, "'%s' expects an integer argument between 1 and 10000.", args[0]);
1000
0
    return -1;
1001
0
  }
1002
1003
0
  event_hdl_tune.max_events_at_once = arg;
1004
0
  return 0;
1005
0
}
1006
1007
/* config keyword parsers */
1008
static struct cfg_kw_list cfg_kws = {ILH, {
1009
  { CFG_GLOBAL, "tune.events.max-events-at-once", event_hdl_parse_max_events_at_once },
1010
  { 0, NULL, NULL }
1011
}};
1012
1013
INITCALL1(STG_REGISTER, cfg_register_keywords, &cfg_kws);
1014
1015
INITCALL0(STG_INIT, event_hdl_init);