forked from timescale/timescaledb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
data_node.c
2126 lines (1823 loc) · 65.1 KB
/
data_node.c
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
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* This file and its contents are licensed under the Timescale License.
* Please see the included NOTICE for copyright information and
* LICENSE-TIMESCALE for a copy of the license.
*/
#include <postgres.h>
#include <access/htup_details.h>
#include <access/xact.h>
#include <catalog/namespace.h>
#include <catalog/pg_database.h>
#include <catalog/pg_foreign_server.h>
#include <catalog/pg_inherits.h>
#include <catalog/pg_namespace.h>
#include <commands/dbcommands.h>
#include <commands/defrem.h>
#include <commands/event_trigger.h>
#include <compat/compat.h>
#include <executor/tuptable.h>
#include <extension.h>
#include <fmgr.h>
#include <funcapi.h>
#include <libpq/crypt.h>
#include <miscadmin.h>
#include <nodes/makefuncs.h>
#include <nodes/parsenodes.h>
#include <nodes/nodes.h>
#include <nodes/value.h>
#include <utils/acl.h>
#include <utils/builtins.h>
#include <utils/array.h>
#include <utils/builtins.h>
#include <utils/guc.h>
#include <utils/inval.h>
#include <utils/palloc.h>
#include <utils/syscache.h>
#include "compat/compat.h"
#include "config.h"
#include "extension.h"
#include "cache.h"
#include "chunk.h"
#include "fdw/fdw.h"
#include "remote/async.h"
#include "remote/connection.h"
#include "remote/connection_cache.h"
#include "remote/dist_commands.h"
#include "data_node.h"
#include "remote/utils.h"
#include "hypertable_cache.h"
#include "errors.h"
#include "dist_util.h"
#include "utils/uuid.h"
#include "mb/pg_wchar.h"
#include "scan_iterator.h"
#include "ts_catalog/catalog.h"
#include "ts_catalog/chunk_data_node.h"
#include "ts_catalog/dimension_partition.h"
#include "ts_catalog/hypertable_data_node.h"
#define TS_DEFAULT_POSTGRES_PORT 5432
#define TS_DEFAULT_POSTGRES_HOST "localhost"
#define ERRCODE_DUPLICATE_DATABASE_STR "42P04"
#define ERRCODE_DUPLICATE_SCHEMA_STR "42P06"
typedef struct DbInfo
{
NameData name;
int32 encoding;
const char *chartype;
const char *collation;
} DbInfo;
/* A list of databases we try to connect to when bootstrapping a data node */
static const char *bootstrap_databases[] = { "postgres", "template1", "defaultdb" };
static bool data_node_validate_database(TSConnection *conn, const DbInfo *database);
/*
* get_database_info - given a database OID, look up info about the database
*
* Returns:
* True if a record for the OID was found, false otherwise.
*/
static bool
get_database_info(Oid dbid, DbInfo *database)
{
HeapTuple dbtuple;
Form_pg_database dbrecord;
dbtuple = SearchSysCache1(DATABASEOID, ObjectIdGetDatum(dbid));
if (!HeapTupleIsValid(dbtuple))
return false;
dbrecord = (Form_pg_database) GETSTRUCT(dbtuple);
database->encoding = dbrecord->encoding;
#if PG15_LT
database->collation = NameStr(dbrecord->datcollate);
database->chartype = NameStr(dbrecord->datctype);
#else
/*
* Since datcollate and datctype are varlen fields in PG15+ we cannot rely
* on GETSTRUCT filling them in as GETSTRUCT only works for fixed-length
* non-NULLABLE columns.
*/
Datum datum;
bool isnull;
datum = SysCacheGetAttr(DATABASEOID, dbtuple, Anum_pg_database_datcollate, &isnull);
Assert(!isnull);
database->collation = TextDatumGetCString(datum);
datum = SysCacheGetAttr(DATABASEOID, dbtuple, Anum_pg_database_datctype, &isnull);
Assert(!isnull);
database->chartype = TextDatumGetCString(datum);
#endif
database->collation = pstrdup(database->collation);
database->chartype = pstrdup(database->chartype);
ReleaseSysCache(dbtuple);
return true;
}
/*
* Verify that server is TimescaleDB data node and perform optional ACL check.
*
* The function returns true if the server is valid TimescaleDB data node and
* the ACL check succeeds. Otherwise, false is returned, or, an error is thrown
* if fail_on_aclcheck is set to true.
*/
static bool
validate_foreign_server(const ForeignServer *server, AclMode const mode, bool fail_on_aclcheck)
{
Oid const fdwid = get_foreign_data_wrapper_oid(EXTENSION_FDW_NAME, false);
Oid curuserid = GetUserId();
AclResult aclresult;
bool valid;
Assert(NULL != server);
if (server->fdwid != fdwid)
ereport(ERROR,
(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
errmsg("data node \"%s\" is not a TimescaleDB server", server->servername)));
if (mode == ACL_NO_CHECK)
return true;
/* Must have permissions on the server object */
aclresult = pg_foreign_server_aclcheck(server->serverid, curuserid, mode);
valid = (aclresult == ACLCHECK_OK);
if (!valid && fail_on_aclcheck)
aclcheck_error(aclresult, OBJECT_FOREIGN_SERVER, server->servername);
return valid;
}
/*
* Lookup the foreign server by name
*/
ForeignServer *
data_node_get_foreign_server(const char *node_name, AclMode mode, bool fail_on_aclcheck,
bool missing_ok)
{
ForeignServer *server;
bool valid;
if (node_name == NULL)
ereport(ERROR,
(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
errmsg("data node name cannot be NULL")));
server = GetForeignServerByName(node_name, missing_ok);
if (NULL == server)
return NULL;
valid = validate_foreign_server(server, mode, fail_on_aclcheck);
if (mode != ACL_NO_CHECK && !valid)
return NULL;
return server;
}
ForeignServer *
data_node_get_foreign_server_by_oid(Oid server_oid, AclMode mode)
{
ForeignServer *server = GetForeignServer(server_oid);
bool PG_USED_FOR_ASSERTS_ONLY valid = validate_foreign_server(server, mode, true);
Assert(valid); /* Should always be valid since we should see error otherwise */
return server;
}
/*
* Create a foreign server.
*
* Returns true if the server was created and set the `oid` to the server oid.
*/
static bool
create_foreign_server(const char *const node_name, const char *const host, int32 port,
const char *const dbname, bool if_not_exists)
{
ForeignServer *server = NULL;
ObjectAddress objaddr;
CreateForeignServerStmt stmt = {
.type = T_CreateForeignServerStmt,
.servername = (char *) node_name,
.fdwname = EXTENSION_FDW_NAME,
.options = list_make3(makeDefElem("host", (Node *) makeString(pstrdup(host)), -1),
makeDefElem("port", (Node *) makeInteger(port), -1),
makeDefElem("dbname", (Node *) makeString(pstrdup(dbname)), -1)),
.if_not_exists = if_not_exists,
};
if (NULL == host)
ereport(ERROR,
(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
(errmsg("invalid host"),
(errhint("A hostname or IP address must be specified when "
"a data node does not already exist.")))));
if (if_not_exists)
{
server = data_node_get_foreign_server(node_name, ACL_NO_CHECK, false, true);
if (NULL != server)
{
ereport(NOTICE,
(errcode(ERRCODE_DUPLICATE_OBJECT),
errmsg("data node \"%s\" already exists, skipping", node_name)));
return false;
}
}
/* Permissions checks done in CreateForeignServer() */
objaddr = CreateForeignServer(&stmt);
/* CreateForeignServer returns InvalidOid if server already exists */
if (!OidIsValid(objaddr.objectId))
{
Assert(if_not_exists);
return false;
}
return true;
}
TSConnection *
data_node_get_connection(const char *const data_node, RemoteTxnPrepStmtOption const ps_opt,
bool transactional)
{
const ForeignServer *server;
TSConnectionId id;
server = data_node_get_foreign_server(data_node, ACL_NO_CHECK, false, false);
id = remote_connection_id(server->serverid, GetUserId());
if (transactional)
return remote_dist_txn_get_connection(id, ps_opt);
return remote_connection_cache_get_connection(id);
}
/* Attribute numbers for datum returned by create_data_node() */
enum Anum_create_data_node
{
Anum_create_data_node_name = 1,
Anum_create_data_node_host,
Anum_create_data_node_port,
Anum_create_data_node_dbname,
Anum_create_data_node_node_created,
Anum_create_data_node_database_created,
Anum_create_data_node_extension_created,
_Anum_create_data_node_max,
};
#define Natts_create_data_node (_Anum_create_data_node_max - 1)
static Datum
create_data_node_datum(FunctionCallInfo fcinfo, const char *node_name, const char *host, int32 port,
const char *dbname, bool node_created, bool database_created,
bool extension_created)
{
TupleDesc tupdesc;
Datum values[_Anum_create_data_node_max];
bool nulls[_Anum_create_data_node_max] = { false };
HeapTuple tuple;
if (get_call_result_type(fcinfo, NULL, &tupdesc) != TYPEFUNC_COMPOSITE)
ereport(ERROR,
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("function returning record called in "
"context that cannot accept type record")));
tupdesc = BlessTupleDesc(tupdesc);
values[AttrNumberGetAttrOffset(Anum_create_data_node_name)] = CStringGetDatum(node_name);
values[AttrNumberGetAttrOffset(Anum_create_data_node_host)] = CStringGetTextDatum(host);
values[AttrNumberGetAttrOffset(Anum_create_data_node_port)] = Int32GetDatum(port);
values[AttrNumberGetAttrOffset(Anum_create_data_node_dbname)] = CStringGetDatum(dbname);
values[AttrNumberGetAttrOffset(Anum_create_data_node_node_created)] =
BoolGetDatum(node_created);
values[AttrNumberGetAttrOffset(Anum_create_data_node_database_created)] =
BoolGetDatum(database_created);
values[AttrNumberGetAttrOffset(Anum_create_data_node_extension_created)] =
BoolGetDatum(extension_created);
tuple = heap_form_tuple(tupdesc, values, nulls);
return HeapTupleGetDatum(tuple);
}
static Datum
create_hypertable_data_node_datum(FunctionCallInfo fcinfo, HypertableDataNode *node)
{
TupleDesc tupdesc;
Datum values[Natts_hypertable_data_node];
bool nulls[Natts_hypertable_data_node] = { false };
HeapTuple tuple;
if (get_call_result_type(fcinfo, NULL, &tupdesc) != TYPEFUNC_COMPOSITE)
ereport(ERROR,
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("function returning record called in "
"context that cannot accept type record")));
tupdesc = BlessTupleDesc(tupdesc);
values[AttrNumberGetAttrOffset(Anum_hypertable_data_node_hypertable_id)] =
Int32GetDatum(node->fd.hypertable_id);
values[AttrNumberGetAttrOffset(Anum_hypertable_data_node_node_hypertable_id)] =
Int32GetDatum(node->fd.node_hypertable_id);
values[AttrNumberGetAttrOffset(Anum_hypertable_data_node_node_name)] =
NameGetDatum(&node->fd.node_name);
tuple = heap_form_tuple(tupdesc, values, nulls);
return HeapTupleGetDatum(tuple);
}
static List *
create_data_node_options(const char *host, int32 port, const char *dbname, const char *user,
const char *password)
{
DefElem *host_elm = makeDefElem("host", (Node *) makeString(pstrdup(host)), -1);
DefElem *port_elm = makeDefElem("port", (Node *) makeInteger(port), -1);
DefElem *dbname_elm = makeDefElem("dbname", (Node *) makeString(pstrdup(dbname)), -1);
DefElem *user_elm = makeDefElem("user", (Node *) makeString(pstrdup(user)), -1);
if (NULL != password)
{
DefElem *password_elm = makeDefElem("password", (Node *) makeString(pstrdup(password)), -1);
return list_make5(host_elm, port_elm, dbname_elm, user_elm, password_elm);
}
return list_make4(host_elm, port_elm, dbname_elm, user_elm);
}
/* Returns 'true' if the database was created. */
static bool
data_node_bootstrap_database(TSConnection *conn, const DbInfo *database)
{
const char *const username = PQuser(remote_connection_get_pg_conn(conn));
Assert(database);
if (data_node_validate_database(conn, database))
{
/* If the database already existed on the remote node, we will log a
* notice and proceed since it is not an error if the database already
* existed on the remote node. */
elog(NOTICE,
"database \"%s\" already exists on data node, skipping",
NameStr(database->name));
return false;
}
/* Create the database with the user as owner. There is no need to
* validate the database after this command since it should be created
* correctly. */
PGresult *res =
remote_connection_execf(conn,
"CREATE DATABASE %s ENCODING %s LC_COLLATE %s LC_CTYPE %s "
"TEMPLATE template0 OWNER %s",
quote_identifier(NameStr(database->name)),
quote_identifier(pg_encoding_to_char(database->encoding)),
quote_literal_cstr(database->collation),
quote_literal_cstr(database->chartype),
quote_identifier(username));
if (PQresultStatus(res) != PGRES_COMMAND_OK)
remote_result_elog(res, ERROR);
return true;
}
/* Validate the database.
*
* Errors:
* Will abort with errors if the database exists but is not correctly set
* up.
* Returns:
* true if the database exists and is valid
* false if it does not exist.
*/
static bool
data_node_validate_database(TSConnection *conn, const DbInfo *database)
{
PGresult *res;
int32 actual_encoding;
const char *actual_chartype;
const char *actual_collation;
res = remote_connection_execf(conn,
"SELECT encoding, datcollate, datctype "
"FROM pg_database WHERE datname = %s",
quote_literal_cstr(NameStr(database->name)));
if (PQresultStatus(res) != PGRES_TUPLES_OK)
ereport(ERROR,
(errcode(ERRCODE_CONNECTION_EXCEPTION), errmsg("%s", PQresultErrorMessage(res))));
if (PQntuples(res) == 0)
return false;
Assert(PQnfields(res) > 2);
actual_encoding = atoi(PQgetvalue(res, 0, 0));
if (actual_encoding != database->encoding)
ereport(ERROR,
(errcode(ERRCODE_TS_DATA_NODE_INVALID_CONFIG),
errmsg("database exists but has wrong encoding"),
errdetail("Expected database encoding to be \"%s\" (%u) but it was \"%s\" (%u).",
pg_encoding_to_char(database->encoding),
database->encoding,
pg_encoding_to_char(actual_encoding),
actual_encoding)));
actual_collation = PQgetvalue(res, 0, 1);
Assert(actual_collation != NULL);
if (strcmp(actual_collation, database->collation) != 0)
ereport(ERROR,
(errcode(ERRCODE_TS_DATA_NODE_INVALID_CONFIG),
errmsg("database exists but has wrong collation"),
errdetail("Expected collation \"%s\" but it was \"%s\".",
database->collation,
actual_collation)));
actual_chartype = PQgetvalue(res, 0, 2);
Assert(actual_chartype != NULL);
if (strcmp(actual_chartype, database->chartype) != 0)
ereport(ERROR,
(errcode(ERRCODE_TS_DATA_NODE_INVALID_CONFIG),
errmsg("database exists but has wrong LC_CTYPE"),
errdetail("Expected LC_CTYPE \"%s\" but it was \"%s\".",
database->chartype,
actual_chartype)));
return true;
}
static void
data_node_validate_extension(TSConnection *conn)
{
const char *const dbname = PQdb(remote_connection_get_pg_conn(conn));
const char *const host = PQhost(remote_connection_get_pg_conn(conn));
const char *const port = PQport(remote_connection_get_pg_conn(conn));
if (!remote_connection_check_extension(conn))
ereport(ERROR,
(errcode(ERRCODE_TS_DATA_NODE_INVALID_CONFIG),
errmsg("database does not have TimescaleDB extension loaded"),
errdetail("The TimescaleDB extension is not loaded in database %s on node at "
"%s:%s.",
dbname,
host,
port)));
}
static void
data_node_validate_as_data_node(TSConnection *conn)
{
PGresult *res =
remote_connection_exec(conn, "SELECT _timescaledb_internal.validate_as_data_node()");
if (PQresultStatus(res) != PGRES_TUPLES_OK)
ereport(ERROR,
(errcode(ERRCODE_TS_DATA_NODE_INVALID_CONFIG),
(errmsg("cannot add \"%s\" as a data node", remote_connection_node_name(conn)),
errdetail("%s", PQresultErrorMessage(res)))));
remote_result_close(res);
}
/*
* Bootstrap the extension and associated objects.
*/
static bool
data_node_bootstrap_extension(TSConnection *conn)
{
const char *const username = PQuser(remote_connection_get_pg_conn(conn));
const char *schema_name = ts_extension_schema_name();
const char *schema_name_quoted = quote_identifier(schema_name);
Oid schema_oid = get_namespace_oid(schema_name, true);
/* We only count the number of tuples in the code below, but having the
* name and version are useful for debugging purposes. */
PGresult *res =
remote_connection_execf(conn,
"SELECT extname, extversion FROM pg_extension WHERE extname = %s",
quote_literal_cstr(EXTENSION_NAME));
if (PQresultStatus(res) != PGRES_TUPLES_OK)
remote_result_elog(res, ERROR);
if (PQntuples(res) == 0)
{
remote_result_close(res);
if (schema_oid != PG_PUBLIC_NAMESPACE)
{
res = remote_connection_execf(conn,
"CREATE SCHEMA %s AUTHORIZATION %s",
schema_name_quoted,
quote_identifier(username));
if (PQresultStatus(res) != PGRES_COMMAND_OK)
{
const char *const sqlstate = PQresultErrorField(res, PG_DIAG_SQLSTATE);
bool schema_exists =
(sqlstate && strcmp(sqlstate, ERRCODE_DUPLICATE_SCHEMA_STR) == 0);
if (!schema_exists)
remote_result_elog(res, ERROR);
remote_result_close(res);
/* If the schema already existed on the remote node, we got a
* duplicate schema error and the schema was not created. In
* that case, we log an error with a hint on how to fix the
* issue. */
ereport(ERROR,
(errcode(ERRCODE_DUPLICATE_SCHEMA),
errmsg("schema \"%s\" already exists in database, aborting", schema_name),
errhint("Make sure that the data node does not contain any "
"existing objects prior to adding it.")));
}
remote_result_close(res);
}
remote_connection_cmdf_ok(conn,
"CREATE EXTENSION " EXTENSION_NAME
" WITH SCHEMA %s VERSION %s CASCADE",
schema_name_quoted,
quote_literal_cstr(ts_extension_get_version()));
return true;
}
else
{
ereport(NOTICE,
(errmsg("extension \"%s\" already exists on data node, skipping",
PQgetvalue(res, 0, 0)),
errdetail("TimescaleDB extension version on %s:%s was %s.",
PQhost(remote_connection_get_pg_conn(conn)),
PQport(remote_connection_get_pg_conn(conn)),
PQgetvalue(res, 0, 1))));
remote_result_close(res);
data_node_validate_extension(conn);
return false;
}
}
/* Add dist_uuid on the remote node.
*
* If the remote node is set to use the current database, `set_dist_id` will report an error and not
* set it. */
static void
add_distributed_id_to_data_node(TSConnection *conn)
{
Datum id_string = DirectFunctionCall1(uuid_out, dist_util_get_id());
PGresult *res = remote_connection_queryf_ok(conn,
"SELECT _timescaledb_internal.set_dist_id('%s')",
DatumGetCString(id_string));
remote_result_close(res);
}
/*
* Connect to do bootstrapping.
*
* We iterate through the list of databases and try to connect to so we can
* bootstrap the data node.
*/
static TSConnection *
connect_for_bootstrapping(const char *node_name, const char *const host, int32 port,
const char *username, const char *password)
{
TSConnection *conn = NULL;
char *err = NULL;
for (size_t i = 0; i < lengthof(bootstrap_databases); i++)
{
List *node_options =
create_data_node_options(host, port, bootstrap_databases[i], username, password);
conn = remote_connection_open(node_name, node_options, TS_NO_TIMEOUT, &err);
if (conn)
return conn;
}
ereport(ERROR,
(errcode(ERRCODE_SQLCLIENT_UNABLE_TO_ESTABLISH_SQLCONNECTION),
errmsg("could not connect to \"%s\"", node_name),
err == NULL ? 0 : errdetail("%s", err)));
pg_unreachable();
return NULL;
}
/*
* Validate that compatible extension is available on the data node.
*
* We check all available extension versions. Since we are connected to
* template DB when performing this check, it means we can't
* really tell if a compatible extension is installed in the database we
* are trying to add to the cluster. However we can make sure that a user
* will be able to manually upgrade the extension on the data node if needed.
*
* Will abort with error if there is no compatible version available, otherwise do nothing.
*/
static void
data_node_validate_extension_availability(TSConnection *conn)
{
StringInfo concat_versions = makeStringInfo();
bool compatible = false;
PGresult *res;
int i;
res =
remote_connection_execf(conn,
"SELECT version FROM pg_available_extension_versions WHERE name = "
"%s AND version ~ '\\d+.\\d+.\\d+.*' ORDER BY version DESC",
quote_literal_cstr(EXTENSION_NAME));
if (PQresultStatus(res) != PGRES_TUPLES_OK)
ereport(ERROR,
(errcode(ERRCODE_CONNECTION_EXCEPTION),
errmsg("failed to validate remote extension: %s", PQresultErrorMessage(res))));
if (PQntuples(res) == 0)
ereport(ERROR,
(errcode(ERRCODE_TS_DATA_NODE_INVALID_CONFIG),
errmsg("TimescaleDB extension not available on remote PostgreSQL instance"),
errhint("Install the TimescaleDB extension on the remote PostgresSQL instance.")));
Assert(PQnfields(res) == 1);
for (i = 0; i < PQntuples(res); i++)
{
appendStringInfo(concat_versions, "%s, ", PQgetvalue(res, i, 0));
compatible = dist_util_is_compatible_version(PQgetvalue(res, i, 0), TIMESCALEDB_VERSION);
if (compatible)
break;
}
if (!compatible)
ereport(ERROR,
(errcode(ERRCODE_TS_DATA_NODE_INVALID_CONFIG),
errmsg("remote PostgreSQL instance has an incompatible timescaledb extension "
"version"),
errdetail_internal("Access node version: %s, available remote versions: %s.",
TIMESCALEDB_VERSION_MOD,
concat_versions->data)));
}
/**
* Get the configured server port for the server as an integer.
*
* Returns:
* Port number if a port is configured, -1 if it is not able to get
* the port number.
*
* Note:
* We cannot use `inet_server_port()` since that will return NULL if
* connecting to a server on localhost since a UNIX socket will be
* used. This is the case even if explicitly using a port when
* connecting. Regardless of how the user connected, we want to use the same
* port as the one that the server listens on.
*/
static int32
get_server_port()
{
const char *const portstr =
GetConfigOption("port", /* missing_ok= */ false, /* restrict_privileged= */ false);
return pg_strtoint32(portstr);
}
static void
validate_data_node_port(int port)
{
if (port < 1 || port > PG_UINT16_MAX)
ereport(ERROR,
(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
(errmsg("invalid port number %d", port),
errhint("The port number must be between 1 and %u.", PG_UINT16_MAX))));
}
/* set_distid may need to be false for some otherwise invalid configurations
* that are useful for testing */
static Datum
data_node_add_internal(PG_FUNCTION_ARGS, bool set_distid)
{
Oid userid = GetUserId();
const char *username = GetUserNameFromId(userid, false);
const char *node_name = PG_ARGISNULL(0) ? NULL : PG_GETARG_CSTRING(0);
const char *host = PG_ARGISNULL(1) ? NULL : TextDatumGetCString(PG_GETARG_DATUM(1));
const char *dbname = PG_ARGISNULL(2) ? get_database_name(MyDatabaseId) : PG_GETARG_CSTRING(2);
int32 port = PG_ARGISNULL(3) ? get_server_port() : PG_GETARG_INT32(3);
bool if_not_exists = PG_ARGISNULL(4) ? false : PG_GETARG_BOOL(4);
bool bootstrap = PG_ARGISNULL(5) ? true : PG_GETARG_BOOL(5);
const char *password = PG_ARGISNULL(6) ? NULL : TextDatumGetCString(PG_GETARG_DATUM(6));
bool server_created = false;
bool database_created = false;
bool extension_created = false;
bool PG_USED_FOR_ASSERTS_ONLY result;
DbInfo database;
TS_PREVENT_FUNC_IF_READ_ONLY();
namestrcpy(&database.name, dbname);
if (host == NULL)
ereport(ERROR,
(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
(errmsg("a host needs to be specified"),
errhint("Provide a host name or IP address of a data node to add."))));
if (set_distid && dist_util_membership() == DIST_MEMBER_DATA_NODE)
ereport(ERROR,
(errcode(ERRCODE_TS_DATA_NODE_ASSIGNMENT_ALREADY_EXISTS),
(errmsg("unable to assign data nodes from an existing distributed database"))));
if (NULL == node_name)
ereport(ERROR,
(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
(errmsg("data node name cannot be NULL"))));
validate_data_node_port(port);
result = get_database_info(MyDatabaseId, &database);
Assert(result);
/*
* Since this function creates databases on remote nodes, and CREATE DATABASE
* cannot run in a transaction block, we cannot run the function in a
* transaction block either.
*/
TS_PREVENT_IN_TRANSACTION_BLOCK(true);
/* Try to create the foreign server, or get the existing one in case of
* if_not_exists true. */
if (create_foreign_server(node_name, host, port, dbname, if_not_exists))
{
List *node_options;
TSConnection *conn;
server_created = true;
/* Make the foreign server visible in current transaction. */
CommandCounterIncrement();
/* If bootstrapping, we check the extension availability here and
* abort if the extension is not available. We should not start
* creating databases and other cruft on the datanode unless we know
* that the extension is installed.
*
* We ensure that there is a database if we are bootstrapping. This is
* done using a separate connection since the database that is going
* to be used for the data node does not exist yet, so we cannot
* connect to it. */
if (bootstrap)
{
TSConnection *conn =
connect_for_bootstrapping(node_name, host, port, username, password);
Assert(NULL != conn);
data_node_validate_extension_availability(conn);
database_created = data_node_bootstrap_database(conn, &database);
remote_connection_close(conn);
}
/* Connect to the database we are bootstrapping and either install the
* extension or validate that the extension is installed. The
* following statements are executed inside a transaction so that they
* can be rolled back in the event of a failure.
*
* We could use `remote_dist_txn_get_connection` here, but it is
* comparably heavy and make the code more complicated than
* necessary. Instead using a more straightforward approach here since
* we do not need 2PC support. */
node_options = create_data_node_options(host, port, dbname, username, password);
conn = remote_connection_open_session(node_name, node_options, false);
Assert(NULL != conn);
remote_connection_cmd_ok(conn, "BEGIN");
if (bootstrap)
extension_created = data_node_bootstrap_extension(conn);
if (!database_created)
{
data_node_validate_database(conn, &database);
data_node_validate_as_data_node(conn);
}
if (!extension_created)
data_node_validate_extension(conn);
/* After the node is verified or bootstrapped, we set the `dist_uuid`
* using the same connection. We skip this if clustering checks are
* disabled, which means that the `dist_uuid` is neither set nor
* checked.
*
* This is done inside a transaction so that we can roll it back if
* there are any failures. Note that any failure at this point will
* not rollback the creates above. */
if (set_distid)
{
if (dist_util_membership() != DIST_MEMBER_ACCESS_NODE)
dist_util_set_as_access_node();
add_distributed_id_to_data_node(conn);
}
/* If there were an error before, we will not reach this point to the
* transaction will be aborted when the connection is closed. */
remote_connection_cmd_ok(conn, "COMMIT");
remote_connection_close(conn);
}
PG_RETURN_DATUM(create_data_node_datum(fcinfo,
node_name,
host,
port,
dbname,
server_created,
database_created,
extension_created));
}
Datum
data_node_add(PG_FUNCTION_ARGS)
{
return data_node_add_internal(fcinfo, true);
}
Datum
data_node_add_without_dist_id(PG_FUNCTION_ARGS)
{
return data_node_add_internal(fcinfo, false);
}
Datum
data_node_attach(PG_FUNCTION_ARGS)
{
const char *node_name = PG_ARGISNULL(0) ? NULL : PG_GETARG_CSTRING(0);
Oid table_id = PG_GETARG_OID(1);
bool if_not_attached = PG_ARGISNULL(2) ? false : PG_GETARG_BOOL(2);
bool repartition = PG_ARGISNULL(3) ? false : PG_GETARG_BOOL(3);
ForeignServer *fserver;
HypertableDataNode *node;
Cache *hcache;
Hypertable *ht;
Dimension *space_dim;
List *result;
int num_nodes;
ListCell *lc;
Oid uid, saved_uid;
int sec_ctx;
Relation rel;
TS_PREVENT_FUNC_IF_READ_ONLY();
if (PG_ARGISNULL(1))
ereport(ERROR,
(errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("hypertable cannot be NULL")));
Assert(get_rel_name(table_id));
ht = ts_hypertable_cache_get_cache_and_entry(table_id, CACHE_FLAG_NONE, &hcache);
Assert(ht != NULL);
if (!hypertable_is_distributed(ht))
ereport(ERROR,
(errcode(ERRCODE_TS_HYPERTABLE_NOT_DISTRIBUTED),
errmsg("hypertable \"%s\" is not distributed", get_rel_name(table_id))));
/* Must have owner permissions on the hypertable to attach a new data
node. Must also have USAGE on the foreign server. */
ts_hypertable_permissions_check(table_id, GetUserId());
fserver = data_node_get_foreign_server(node_name, ACL_USAGE, true, false);
Assert(NULL != fserver);
foreach (lc, ht->data_nodes)
{
node = lfirst(lc);
if (node->foreign_server_oid == fserver->serverid)
{
ts_cache_release(hcache);
if (if_not_attached)
{
ereport(NOTICE,
(errcode(ERRCODE_TS_DATA_NODE_ALREADY_ATTACHED),
errmsg("data node \"%s\" is already attached to hypertable \"%s\", "
"skipping",
node_name,
get_rel_name(table_id))));
PG_RETURN_DATUM(create_hypertable_data_node_datum(fcinfo, node));
}
else
ereport(ERROR,
(errcode(ERRCODE_TS_DATA_NODE_ALREADY_ATTACHED),
errmsg("data node \"%s\" is already attached to hypertable \"%s\"",
node_name,
get_rel_name(table_id))));
}
}
/*
* Change to the hypertable owner so that the same permissions will be set up on the
* datanode being attached to as well. We need to do this explicitly because the
* caller of this function could be a superuser and we definitely don't want to create
* this hypertable with superuser ownership on the datanode being attached to!
*
* We retain the lock on the hypertable till the end of the traction to avoid any
* possibility of a concurrent "ALTER TABLE OWNER TO" changing the owner underneath
* us.
*/
rel = table_open(ht->main_table_relid, AccessShareLock);
uid = rel->rd_rel->relowner;
table_close(rel, NoLock);
GetUserIdAndSecContext(&saved_uid, &sec_ctx);
if (uid != saved_uid)
SetUserIdAndSecContext(uid, sec_ctx | SECURITY_LOCAL_USERID_CHANGE);
result = hypertable_assign_data_nodes(ht->fd.id, list_make1((char *) node_name));
Assert(result->length == 1);
/* Refresh the cached hypertable entry to get the attached node */
ts_cache_release(hcache);
hcache = ts_hypertable_cache_pin();
ht = ts_hypertable_cache_get_entry(hcache, table_id, CACHE_FLAG_NONE);
/* Get the first closed (space) dimension, which is the one along which we
* partition across data nodes. */
space_dim = ts_hyperspace_get_mutable_dimension(ht->space, DIMENSION_TYPE_CLOSED, 0);
num_nodes = list_length(ht->data_nodes);
if (num_nodes > MAX_NUM_HYPERTABLE_DATA_NODES)
ereport(ERROR,
(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
errmsg("max number of data nodes already attached"),
errdetail("The number of data nodes in a hypertable cannot exceed %d.",
MAX_NUM_HYPERTABLE_DATA_NODES)));
/* If there are less slices (partitions) in the space dimension than there
* are data nodes, we'd like to expand the number of slices to be able to
* make use of the new data node. */
if (NULL != space_dim)
{
List *data_node_names = NIL;
int num_partitions = space_dim->fd.num_slices;
if (num_nodes > space_dim->fd.num_slices)
{
if (repartition)
{
ts_dimension_set_number_of_slices(space_dim, num_nodes & 0xFFFF);
num_partitions = num_nodes;
ereport(NOTICE,
(errmsg("the number of partitions in dimension \"%s\" was increased to %u",
NameStr(space_dim->fd.column_name),
num_nodes),
errdetail("To make use of all attached data nodes, a distributed "
"hypertable needs at least as many partitions in the first "
"closed (space) dimension as there are attached data nodes.")));
}
else
{
/* Raise a warning if the number of partitions are too few to make
* use of all data nodes. Need to refresh cache first to get the
* updated data node list. */
int dimension_id = space_dim->fd.id;
ts_hypertable_check_partitioning(ht, dimension_id);
}
}
data_node_names = ts_hypertable_get_available_data_node_names(ht, true);
ts_dimension_partition_info_recreate(space_dim->fd.id,
num_partitions,
data_node_names,
ht->fd.replication_factor);