aboutsummaryrefslogtreecommitdiff
path: root/src/pq/pq_connect.c
blob: a2dce3fb0129844edbdb152251fecf34a3f38001 (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
/*
   This file is part of GNUnet
   Copyright (C) 2017, 2019, 2020 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_connect.c
 * @brief functions to connect to libpq (PostGres)
 * @author Christian Grothoff
 */
#include "platform.h"
#include "pq.h"
#include <pthread.h>


/**
 * Function called by libpq whenever it wants to log something.
 * We already log whenever we care, so this function does nothing
 * and merely exists to silence the libpq logging.
 *
 * @param arg the SQL connection that was used
 * @param res information about some libpq event
 */
static void
pq_notice_receiver_cb (void *arg,
                       const PGresult *res)
{
  /* do nothing, intentionally */
  (void) arg;
  (void) res;
}


/**
 * Function called by libpq whenever it wants to log something.
 * We log those using the GNUnet logger.
 *
 * @param arg the SQL connection that was used
 * @param message information about some libpq event
 */
static void
pq_notice_processor_cb (void *arg,
                        const char *message)
{
  (void) arg;
  GNUNET_log_from (GNUNET_ERROR_TYPE_INFO,
                   "pq",
                   "%s",
                   message);
}


struct GNUNET_PQ_Context *
GNUNET_PQ_connect (const char *config_str,
                   const char *load_path,
                   const struct GNUNET_PQ_ExecuteStatement *es,
                   const struct GNUNET_PQ_PreparedStatement *ps)
{
  struct GNUNET_PQ_Context *db;
  unsigned int elen = 0;
  unsigned int plen = 0;

  if (NULL != es)
    while (NULL != es[elen].sql)
      elen++;
  if (NULL != ps)
    while (NULL != ps[plen].name)
      plen++;

  db = GNUNET_new (struct GNUNET_PQ_Context);
  db->config_str = GNUNET_strdup (config_str);
  if (NULL != load_path)
    db->load_path = GNUNET_strdup (load_path);
  if (0 != elen)
  {
    db->es = GNUNET_new_array (elen + 1,
                               struct GNUNET_PQ_ExecuteStatement);
    memcpy (db->es,
            es,
            elen * sizeof (struct GNUNET_PQ_ExecuteStatement));
  }
  if (0 != plen)
  {
    db->ps = GNUNET_new_array (plen + 1,
                               struct GNUNET_PQ_PreparedStatement);
    memcpy (db->ps,
            ps,
            plen * sizeof (struct GNUNET_PQ_PreparedStatement));
  }
  db->channel_map = GNUNET_CONTAINER_multishortmap_create (16,
                                                           GNUNET_YES);
  GNUNET_PQ_reconnect (db);
  if (NULL == db->conn)
  {
    GNUNET_free (db->load_path);
    GNUNET_free (db->config_str);
    GNUNET_free (db);
    return NULL;
  }
  return db;
}


/**
 * Apply patch number @a from path @a load_path.
 *
 * @param db database context to use
 * @param load_path where to find the SQL code to run
 * @param i patch number to append to the @a load_path
 * @return #GNUNET_OK on success, #GNUNET_NO if patch @a i does not exist, #GNUNET_SYSERR on error
 */
static enum GNUNET_GenericReturnValue
apply_patch (struct GNUNET_PQ_Context *db,
             const char *load_path,
             unsigned int i)
{
  struct GNUNET_OS_Process *psql;
  enum GNUNET_OS_ProcessStatusType type;
  unsigned long code;
  size_t slen = strlen (load_path) + 10;
  char buf[slen];

  GNUNET_snprintf (buf,
                   sizeof (buf),
                   "%s%04u.sql",
                   load_path,
                   i);
  GNUNET_log (GNUNET_ERROR_TYPE_INFO,
              "Applying SQL file `%s' on database %s\n",
              buf,
              db->config_str);
  psql = GNUNET_OS_start_process (GNUNET_OS_INHERIT_STD_ERR,
                                  NULL,
                                  NULL,
                                  NULL,
                                  "psql",
                                  "psql",
                                  db->config_str,
                                  "-f",
                                  buf,
                                  "-q",
                                  "--set",
                                  "ON_ERROR_STOP=1",
                                  NULL);
  if (NULL == psql)
  {
    GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR,
                              "exec",
                              "psql");
    return GNUNET_SYSERR;
  }
  GNUNET_assert (GNUNET_OK ==
                 GNUNET_OS_process_wait_status (psql,
                                                &type,
                                                &code));
  GNUNET_OS_process_destroy (psql);
  if ( (GNUNET_OS_PROCESS_EXITED != type) ||
       (0 != code) )
  {
    GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
                "Could not run PSQL on file %s: psql exit code was %d\n",
                buf,
                (int) code);
    return GNUNET_SYSERR;
  }
  return GNUNET_OK;
}


enum GNUNET_GenericReturnValue
GNUNET_PQ_run_sql (struct GNUNET_PQ_Context *db,
                   const char *load_path)
{
  const char *load_path_suffix;
  size_t slen = strlen (load_path) + 10;

  load_path_suffix = strrchr (load_path, '/');
  if (NULL == load_path_suffix)
  {
    GNUNET_break (0);
    return GNUNET_SYSERR;
  }
  load_path_suffix++; /* skip '/' */
  GNUNET_log (GNUNET_ERROR_TYPE_INFO,
              "Loading SQL resources from `%s'\n",
              load_path);
  for (unsigned int i = 1; i<10000; i++)
  {
    enum GNUNET_DB_QueryStatus qs;
    {
      char buf[slen];

      /* First, check patch actually exists */
      GNUNET_snprintf (buf,
                       sizeof (buf),
                       "%s%04u.sql",
                       load_path,
                       i);
      if (GNUNET_YES !=
          GNUNET_DISK_file_test (buf))
        return GNUNET_OK;   /* We are done */
    }

    /* Second, check with DB versioning schema if this patch was already applied,
       if so, skip it. */
    {
      char patch_name[slen];

      GNUNET_snprintf (patch_name,
                       sizeof (patch_name),
                       "%s%04u",
                       load_path_suffix,
                       i);
      {
        char *applied_by;
        struct GNUNET_PQ_QueryParam params[] = {
          GNUNET_PQ_query_param_string (patch_name),
          GNUNET_PQ_query_param_end
        };
        struct GNUNET_PQ_ResultSpec rs[] = {
          GNUNET_PQ_result_spec_string ("applied_by",
                                        &applied_by),
          GNUNET_PQ_result_spec_end
        };

        qs = GNUNET_PQ_eval_prepared_singleton_select (db,
                                                       "gnunet_pq_check_patch",
                                                       params,
                                                       rs);
        if (GNUNET_DB_STATUS_SUCCESS_ONE_RESULT == qs)
        {
          GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
                      "Database version %s already applied by %s, skipping\n",
                      patch_name,
                      applied_by);
          GNUNET_PQ_cleanup_result (rs);
        }
        if (GNUNET_DB_STATUS_HARD_ERROR == qs)
        {
          GNUNET_break (0);
          return GNUNET_SYSERR;
        }
      }
    }
    if (GNUNET_DB_STATUS_SUCCESS_ONE_RESULT == qs)
      continue; /* patch already applied, skip it */

    /* patch not yet applied, run it! */
    {
      int ret;

      ret = apply_patch (db,
                         load_path,
                         i);
      if (GNUNET_NO == ret)
        break;
      if (GNUNET_SYSERR == ret)
        return GNUNET_SYSERR;
    }
  }
  return GNUNET_OK;
}


void
GNUNET_PQ_reconnect_if_down (struct GNUNET_PQ_Context *db)
{
  if (1 ==
      PQconsumeInput (db->conn))
    return;
  if (CONNECTION_BAD != PQstatus (db->conn))
    return;
  GNUNET_PQ_reconnect (db);
}


void
GNUNET_PQ_reconnect (struct GNUNET_PQ_Context *db)
{
  GNUNET_PQ_event_reconnect_ (db,
                              -1);
  if (NULL != db->conn)
    PQfinish (db->conn);
  db->conn = PQconnectdb (db->config_str);
  if ( (NULL == db->conn) ||
       (CONNECTION_OK != PQstatus (db->conn)) )
  {
    GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR,
                     "pq",
                     "Database connection to '%s' failed: %s\n",
                     db->config_str,
                     (NULL != db->conn) ?
                     PQerrorMessage (db->conn)
                     : "PQconnectdb returned NULL");
    if (NULL != db->conn)
    {
      PQfinish (db->conn);
      db->conn = NULL;
    }
    return;
  }
  PQsetNoticeReceiver (db->conn,
                       &pq_notice_receiver_cb,
                       db);
  PQsetNoticeProcessor (db->conn,
                        &pq_notice_processor_cb,
                        db);
  if (NULL != db->load_path)
  {
    PGresult *res;

    res = PQprepare (db->conn,
                     "gnunet_pq_check_patch",
                     "SELECT"
                     " applied_by"
                     " FROM _v.patches"
                     " WHERE patch_name = $1"
                     " LIMIT 1",
                     1,
                     NULL);
    if (PGRES_COMMAND_OK != PQresultStatus (res))
    {
      int ret;

      PQclear (res);
      GNUNET_log (GNUNET_ERROR_TYPE_INFO,
                  "Failed to prepare statement to check patch level. Likely versioning schema does not exist yet, loading patch level 0000!\n");
      ret = apply_patch (db,
                         db->load_path,
                         0);
      if (GNUNET_NO == ret)
      {
        GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
                    "Failed to find SQL file to load database versioning logic\n");
        PQfinish (db->conn);
        db->conn = NULL;
        return;
      }
      if (GNUNET_SYSERR == ret)
      {
        GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
                    "Failed to run SQL logic to setup database versioning logic\n");
        PQfinish (db->conn);
        db->conn = NULL;
        return;
      }
      /* try again to prepare our statement! */
      res = PQprepare (db->conn,
                       "gnunet_pq_check_patch",
                       "SELECT"
                       " applied_by"
                       " FROM _v.patches"
                       " WHERE patch_name = $1"
                       " LIMIT 1",
                       1,
                       NULL);
      if (PGRES_COMMAND_OK != PQresultStatus (res))
      {
        GNUNET_log (GNUNET_ERROR_TYPE_INFO,
                    "Failed to run SQL logic to setup database versioning logic: %s/%s\n",
                    PQresultErrorMessage (res),
                    PQerrorMessage (db->conn));
        PQclear (res);
        PQfinish (db->conn);
        db->conn = NULL;
        return;
      }
    }
    PQclear (res);

    if (GNUNET_SYSERR ==
        GNUNET_PQ_run_sql (db,
                           db->load_path))
    {
      GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
                  "Failed to load SQL statements from `%s*'\n",
                  db->load_path);
      PQfinish (db->conn);
      db->conn = NULL;
      return;
    }
  }
  if ( (NULL != db->es) &&
       (GNUNET_OK !=
        GNUNET_PQ_exec_statements (db,
                                   db->es)) )
  {
    PQfinish (db->conn);
    db->conn = NULL;
    return;
  }
  if ( (NULL != db->ps) &&
       (GNUNET_OK !=
        GNUNET_PQ_prepare_statements (db,
                                      db->ps)) )
  {
    PQfinish (db->conn);
    db->conn = NULL;
    return;
  }
  GNUNET_PQ_event_reconnect_ (db,
                              PQsocket (db->conn));
}


struct GNUNET_PQ_Context *
GNUNET_PQ_connect_with_cfg (const struct GNUNET_CONFIGURATION_Handle *cfg,
                            const char *section,
                            const char *load_path_suffix,
                            const struct GNUNET_PQ_ExecuteStatement *es,
                            const struct GNUNET_PQ_PreparedStatement *ps)
{
  struct GNUNET_PQ_Context *db;
  char *conninfo;
  char *load_path;
  char *sp;

  if (GNUNET_OK !=
      GNUNET_CONFIGURATION_get_value_string (cfg,
                                             section,
                                             "CONFIG",
                                             &conninfo))
    conninfo = NULL;
  load_path = NULL;
  sp = NULL;
  if ( (NULL != load_path_suffix) &&
       (GNUNET_OK ==
        GNUNET_CONFIGURATION_get_value_filename (cfg,
                                                 section,
                                                 "SQL_DIR",
                                                 &sp)) )
    GNUNET_asprintf (&load_path,
                     "%s%s",
                     sp,
                     load_path_suffix);
  db = GNUNET_PQ_connect (conninfo == NULL ? "" : conninfo,
                          load_path,
                          es,
                          ps);
  GNUNET_free (load_path);
  GNUNET_free (sp);
  GNUNET_free (conninfo);
  return db;
}


void
GNUNET_PQ_disconnect (struct GNUNET_PQ_Context *db)
{
  if (NULL == db)
    return;
  GNUNET_assert (0 ==
                 GNUNET_CONTAINER_multishortmap_size (db->channel_map));
  GNUNET_CONTAINER_multishortmap_destroy (db->channel_map);
  GNUNET_free (db->es);
  GNUNET_free (db->ps);
  GNUNET_free (db->load_path);
  GNUNET_free (db->config_str);
  PQfinish (db->conn);
  GNUNET_free (db);
}


/* end of pq/pq_connect.c */