aboutsummaryrefslogtreecommitdiff
path: root/src/lib/pq/pq_event.c
blob: 7506ff2f0b610c6e2348ad62e07d2ee8f2be2ee1 (plain) (blame)
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
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
/*
   This file is part of GNUnet
   Copyright (C) 2021, 2023 GNUnet e.V.

   GNUnet is free software: you can redistribute it and/or modify it
   under the terms of the GNU Affero General Public License as published
   by the Free Software Foundation, either version 3 of the License,
   or (at your option) any later version.

   GNUnet 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
   Affero General Public License for more details.

   You should have received a copy of the GNU Affero General Public License
   along with this program.  If not, see <http://www.gnu.org/licenses/>.

     SPDX-License-Identifier: AGPL3.0-or-later
 */
/**
 * @file pq/pq_event.c
 * @brief event notifications via Postgres
 * @author Christian Grothoff
 */
#include "platform.h"
#include "pq.h"
#include <pthread.h>


/**
 * Handle for an active LISTENer to the database.
 */
struct GNUNET_DB_EventHandler
{
  /**
   * Channel name.
   */
  struct GNUNET_ShortHashCode sh;

  /**
   * Function to call on events.
   */
  GNUNET_DB_EventCallback cb;

  /**
   * Closure for @e cb.
   */
  void *cb_cls;

  /**
   * Database context this event handler is with.
   */
  struct GNUNET_PQ_Context *db;

  /**
   * Task to run on timeout.
   */
  struct GNUNET_SCHEDULER_Task *timeout_task;
};


/**
 * Convert @a es to a short hash.
 *
 * @param es spec to hash to an identifier
 * @param[out] sh short hash to set
 */
static void
es_to_sh (const struct GNUNET_DB_EventHeaderP *es,
          struct GNUNET_ShortHashCode *sh)
{
  struct GNUNET_HashCode h_channel;

  GNUNET_CRYPTO_hash (es,
                      ntohs (es->size),
                      &h_channel);
  GNUNET_static_assert (sizeof (*sh) <= sizeof (h_channel));
  memcpy (sh,
          &h_channel,
          sizeof (*sh));
}


/**
 * Convert @a sh to a Postgres identifier.
 *
 * @param sh short hash to convert to an identifier
 * @param[out] identifier by default, Postgres supports
 *     NAMEDATALEN=64 character identifiers
 * @return end position of the identifier
 */
static char *
sh_to_channel (struct GNUNET_ShortHashCode *sh,
               char identifier[64])
{
  char *end;

  end = GNUNET_STRINGS_data_to_string (sh,
                                       sizeof (*sh),
                                       identifier,
                                       63);
  GNUNET_assert (NULL != end);
  *end = '\0';
  return end;
}


/**
 * Convert @a sh to a Postgres identifier.
 *
 * @param identifier to convert
 * @param[out] sh set to short hash
 * @return #GNUNET_OK on success
 */
static enum GNUNET_GenericReturnValue
channel_to_sh (const char *identifier,
               struct GNUNET_ShortHashCode *sh)
{
  return GNUNET_STRINGS_string_to_data (identifier,
                                        strlen (identifier),
                                        sh,
                                        sizeof (*sh));
}


/**
 * Convert @a es to a Postgres identifier.
 *
 * @param es spec to hash to an identifier
 * @param[out] identifier by default, Postgres supports
 *     NAMEDATALEN=64 character identifiers
 * @return end position of the identifier
 */
static char *
es_to_channel (const struct GNUNET_DB_EventHeaderP *es,
               char identifier[64])
{
  struct GNUNET_ShortHashCode sh;

  es_to_sh (es,
            &sh);
  return sh_to_channel (&sh,
                        identifier);
}


/**
 * Closure for #do_notify().
 */
struct NotifyContext
{
  /**
   * Extra argument of the notification, or NULL.
   */
  void *extra;

  /**
   * Number of bytes in @e extra.
   */
  size_t extra_size;
};


/**
 * Function called on every event handler that
 * needs to be triggered.
 *
 * @param cls a `struct NotifyContext`
 * @param sh channel name
 * @param value a `struct GNUNET_DB_EventHandler`
 * @return #GNUNET_OK continue to iterate
 */
static enum GNUNET_GenericReturnValue
do_notify (void *cls,
           const struct GNUNET_ShortHashCode *sh,
           void *value)
{
  struct NotifyContext *ctx = cls;
  struct GNUNET_DB_EventHandler *eh = value;

  eh->cb (eh->cb_cls,
          ctx->extra,
          ctx->extra_size);
  return GNUNET_OK;
}


void
GNUNET_PQ_event_do_poll (struct GNUNET_PQ_Context *db)
{
  PGnotify *n;
  unsigned int cnt = 0;

  GNUNET_log (GNUNET_ERROR_TYPE_INFO,
              "PG poll job active\n");
  if (1 !=
      PQconsumeInput (db->conn))
  {
    GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
                "Failed to read from Postgres: %s\n",
                PQerrorMessage (db->conn));
    if (CONNECTION_BAD != PQstatus (db->conn))
      return;
    GNUNET_PQ_reconnect (db);
    return;
  }
  while (NULL != (n = PQnotifies (db->conn)))
  {
    struct GNUNET_ShortHashCode sh;
    struct NotifyContext ctx = {
      .extra = NULL
    };

    cnt++;
    if ('X' != toupper ((int) n->relname[0]))
    {
      GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
                  "Ignoring notification for unsupported channel identifier `%s'\n",
                  n->relname);
      PQfreemem (n);
      continue;
    }
    if (GNUNET_OK !=
        channel_to_sh (&n->relname[1],
                       &sh))
    {
      GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
                  "Ignoring notification for unsupported channel identifier `%s'\n",
                  n->relname);
      PQfreemem (n);
      continue;
    }
    if ( (NULL != n->extra) &&
         (GNUNET_OK !=
          GNUNET_STRINGS_string_to_data_alloc (n->extra,
                                               strlen (n->extra),
                                               &ctx.extra,
                                               &ctx.extra_size)))
    {
      GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
                  "Ignoring notification for unsupported extra data `%s' on channel `%s'\n",
                  n->extra,
                  n->relname);
      PQfreemem (n);
      continue;
    }
    GNUNET_log (GNUNET_ERROR_TYPE_INFO,
                "Received notification %s with extra data `%.*s'\n",
                n->relname,
                (int) ctx.extra_size,
                (const char *) ctx.extra);
    GNUNET_CONTAINER_multishortmap_get_multiple (db->channel_map,
                                                 &sh,
                                                 &do_notify,
                                                 &ctx);
    GNUNET_free (ctx.extra);
    PQfreemem (n);
  }
  GNUNET_log (GNUNET_ERROR_TYPE_INFO,
              "PG poll job finishes after %u events\n",
              cnt);
}


/**
 * The GNUnet scheduler notifies us that we need to
 * trigger the DB event poller.
 *
 * @param cls a `struct GNUNET_PQ_Context *`
 */
static void
do_scheduler_notify (void *cls)
{
  struct GNUNET_PQ_Context *db = cls;

  db->event_task = NULL;
  if (NULL == db->rfd)
    GNUNET_PQ_reconnect (db);
  GNUNET_PQ_event_do_poll (db);
  if (NULL != db->event_task)
    return;
  GNUNET_log (GNUNET_ERROR_TYPE_INFO,
              "Resubscribing\n");
  if (NULL == db->rfd)
  {
    db->resubscribe_backoff
      = GNUNET_TIME_relative_max (db->resubscribe_backoff,
                                  GNUNET_TIME_UNIT_SECONDS);
    db->resubscribe_backoff
      = GNUNET_TIME_STD_BACKOFF (db->resubscribe_backoff);
    db->event_task = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_SECONDS,
                                                   &do_scheduler_notify,
                                                   db);
    return;
  }
  db->resubscribe_backoff = GNUNET_TIME_UNIT_SECONDS;
  db->event_task
    = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
                                     db->rfd,
                                     &do_scheduler_notify,
                                     db);
}


/**
 * Function called when the Postgres FD changes and we need
 * to update the scheduler event loop task.
 *
 * @param cls a `struct GNUNET_PQ_Context *`
 * @param fd the file descriptor, possibly -1
 */
static void
scheduler_fd_cb (void *cls,
                 int fd)
{
  struct GNUNET_PQ_Context *db = cls;

  GNUNET_log (GNUNET_ERROR_TYPE_INFO,
              "New poll FD is %d\n",
              fd);
  if (NULL != db->event_task)
  {
    GNUNET_SCHEDULER_cancel (db->event_task);
    db->event_task = NULL;
  }
  GNUNET_free (db->rfd);
  if (-1 == fd)
    return;
  if (0 == GNUNET_CONTAINER_multishortmap_size (db->channel_map))
    return;
  GNUNET_log (GNUNET_ERROR_TYPE_INFO,
              "Activating poll job on %d\n",
              fd);
  db->rfd = GNUNET_NETWORK_socket_box_native (fd);
  db->event_task
    = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_ZERO,
                                     db->rfd,
                                     &do_scheduler_notify,
                                     db);
}


/**
 * Helper function to trigger an SQL @a cmd on @a db
 *
 * @param db database to send command to
 * @param cmd prefix of the command to send
 * @param eh details about the event
 */
static void
manage_subscribe (struct GNUNET_PQ_Context *db,
                  const char *cmd,
                  struct GNUNET_DB_EventHandler *eh)
{
  char sql[16 + 64];
  char *end;
  PGresult *result;

  if (NULL == db->conn)
    return;
  end = stpcpy (sql,
                cmd);
  end = sh_to_channel (&eh->sh,
                       end);
  GNUNET_log (GNUNET_ERROR_TYPE_INFO,
              "Executing PQ command `%s'\n",
              sql);
  result = PQexec (db->conn,
                   sql);
  if (PGRES_COMMAND_OK != PQresultStatus (result))
  {
    GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR,
                     "pq",
                     "Failed to execute `%s': %s/%s/%s/%s/%s",
                     sql,
                     PQresultErrorField (result,
                                         PG_DIAG_MESSAGE_PRIMARY),
                     PQresultErrorField (result,
                                         PG_DIAG_MESSAGE_DETAIL),
                     PQresultErrorMessage (result),
                     PQresStatus (PQresultStatus (result)),
                     PQerrorMessage (db->conn));
  }
  PQclear (result);
}


/**
 * Re-subscribe to notifications after disconnect.
 *
 * @param cls the DB context
 * @param sh the short hash of the channel
 * @param value the event handler
 * @return #GNUNET_OK to continue to iterate
 */
static enum GNUNET_GenericReturnValue
register_notify (void *cls,
                 const struct GNUNET_ShortHashCode *sh,
                 void *value)
{
  struct GNUNET_PQ_Context *db = cls;
  struct GNUNET_DB_EventHandler *eh = value;

  manage_subscribe (db,
                    "LISTEN X",
                    eh);
  return GNUNET_OK;
}


void
GNUNET_PQ_event_reconnect_ (struct GNUNET_PQ_Context *db,
                            int fd)
{
  GNUNET_log (GNUNET_ERROR_TYPE_INFO,
              "Change in PQ event FD to %d\n",
              fd);
  scheduler_fd_cb (db,
                   fd);
  GNUNET_CONTAINER_multishortmap_iterate (db->channel_map,
                                          &register_notify,
                                          db);
}


/**
 * Function run on timeout for an event. Triggers
 * the notification, but does NOT clear the handler.
 *
 * @param cls a `struct GNUNET_DB_EventHandler *`
 */
static void
event_timeout (void *cls)
{
  struct GNUNET_DB_EventHandler *eh = cls;

  eh->timeout_task = NULL;
  eh->cb (eh->cb_cls,
          NULL,
          0);
}


struct GNUNET_DB_EventHandler *
GNUNET_PQ_event_listen (struct GNUNET_PQ_Context *db,
                        const struct GNUNET_DB_EventHeaderP *es,
                        struct GNUNET_TIME_Relative timeout,
                        GNUNET_DB_EventCallback cb,
                        void *cb_cls)
{
  struct GNUNET_DB_EventHandler *eh;
  bool sub;

  eh = GNUNET_new (struct GNUNET_DB_EventHandler);
  eh->db = db;
  es_to_sh (es,
            &eh->sh);
  eh->cb = cb;
  eh->cb_cls = cb_cls;
  sub = (NULL ==
         GNUNET_CONTAINER_multishortmap_get (db->channel_map,
                                             &eh->sh));
  GNUNET_assert (GNUNET_OK ==
                 GNUNET_CONTAINER_multishortmap_put (db->channel_map,
                                                     &eh->sh,
                                                     eh,
                                                     GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE));
  if (NULL == db->event_task)
  {
    GNUNET_log (GNUNET_ERROR_TYPE_INFO,
                "Starting event scheduler\n");
    scheduler_fd_cb (db,
                     PQsocket (db->conn));
  }
  if (sub)
    manage_subscribe (db,
                      "LISTEN X",
                      eh);
  eh->timeout_task = GNUNET_SCHEDULER_add_delayed (timeout,
                                                   &event_timeout,
                                                   eh);
  return eh;
}


void
GNUNET_PQ_event_listen_cancel (struct GNUNET_DB_EventHandler *eh)
{
  struct GNUNET_PQ_Context *db = eh->db;

  GNUNET_assert (GNUNET_OK ==
                 GNUNET_CONTAINER_multishortmap_remove (db->channel_map,
                                                        &eh->sh,
                                                        eh));
  if (NULL ==
      GNUNET_CONTAINER_multishortmap_get (db->channel_map,
                                          &eh->sh))
    manage_subscribe (db,
                      "UNLISTEN X",
                      eh);
  if (0 == GNUNET_CONTAINER_multishortmap_size (db->channel_map))
  {
    GNUNET_log (GNUNET_ERROR_TYPE_INFO,
                "Stopping PQ event scheduler job\n");
    GNUNET_free (db->rfd);
    if (NULL != db->event_task)
    {
      GNUNET_SCHEDULER_cancel (db->event_task);
      db->event_task = NULL;
    }
  }
  if (NULL != eh->timeout_task)
  {
    GNUNET_SCHEDULER_cancel (eh->timeout_task);
    eh->timeout_task = NULL;
  }
  GNUNET_free (eh);
}


char *
GNUNET_PQ_get_event_notify_channel (const struct GNUNET_DB_EventHeaderP *es)
{
  char sql[16 + 64 + 8];
  char *end;

  end = stpcpy (sql,
                "X");
  end = es_to_channel (es,
                       end);
  GNUNET_assert (NULL != end);
  return GNUNET_strdup (sql);
}


void
GNUNET_PQ_event_notify (struct GNUNET_PQ_Context *db,
                        const struct GNUNET_DB_EventHeaderP *es,
                        const void *extra,
                        size_t extra_size)
{
  char sql[16 + 64 + extra_size * 8 / 5 + 8];
  char *end;
  PGresult *result;

  end = stpcpy (sql,
                "NOTIFY X");
  end = es_to_channel (es,
                       end);
  end = stpcpy (end,
                ", '");
  end = GNUNET_STRINGS_data_to_string (extra,
                                       extra_size,
                                       end,
                                       sizeof (sql) - (end - sql) - 1);
  GNUNET_assert (NULL != end);
  *end = '\0';
  end = stpcpy (end,
                "'");
  GNUNET_log (GNUNET_ERROR_TYPE_INFO,
              "Executing command `%s'\n",
              sql);
  result = PQexec (db->conn,
                   sql);
  if (PGRES_COMMAND_OK != PQresultStatus (result))
  {
    GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR,
                     "pq",
                     "Failed to execute `%s': %s/%s/%s/%s/%s",
                     sql,
                     PQresultErrorField (result,
                                         PG_DIAG_MESSAGE_PRIMARY),
                     PQresultErrorField (result,
                                         PG_DIAG_MESSAGE_DETAIL),
                     PQresultErrorMessage (result),
                     PQresStatus (PQresultStatus (result)),
                     PQerrorMessage (db->conn));
  }
  PQclear (result);
  GNUNET_PQ_event_do_poll (db);
}


/* end of pq_event.c */