-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathsynchdb.c
3655 lines (3218 loc) · 107 KB
/
synchdb.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
/*
* synchdb.c
*
* Implementation of SynchDB functionality for PostgreSQL
*
* This file contains the core functionality for the SynchDB extension,
* including background worker management, JNI interactions with the
* Debezium engine, and shared memory state management.
*
* Key components:
* - JNI setup and interaction with Debezium
* - Background worker management
* - Shared memory state management
* - User-facing functions for controlling SynchDB
*
* Copyright (c) 2024 Hornetlabs Technology, Inc.
*
*/
#include "postgres.h"
#include "fmgr.h"
#include "utils/builtins.h"
#include <jni.h>
#include <unistd.h>
#include "format_converter.h"
#include "postmaster/bgworker.h"
#include "postmaster/interrupt.h"
#include "storage/procsignal.h"
#include "storage/latch.h"
#include "storage/lwlock.h"
#include "storage/proc.h"
#include "storage/ipc.h"
#include "storage/fd.h"
#include "miscadmin.h"
#include "utils/wait_event.h"
#include "utils/guc.h"
#include "varatt.h"
#include "funcapi.h"
#include "synchdb.h"
#include "replication_agent.h"
#include "access/xact.h"
#include "utils/snapmgr.h"
PG_MODULE_MAGIC;
/* Function declarations for user-facing functions */
PG_FUNCTION_INFO_V1(synchdb_stop_engine_bgw);
PG_FUNCTION_INFO_V1(synchdb_start_engine_bgw);
PG_FUNCTION_INFO_V1(synchdb_start_engine_bgw_snapshot_mode);
PG_FUNCTION_INFO_V1(synchdb_get_state);
PG_FUNCTION_INFO_V1(synchdb_pause_engine);
PG_FUNCTION_INFO_V1(synchdb_resume_engine);
PG_FUNCTION_INFO_V1(synchdb_set_offset);
PG_FUNCTION_INFO_V1(synchdb_add_conninfo);
PG_FUNCTION_INFO_V1(synchdb_restart_connector);
PG_FUNCTION_INFO_V1(synchdb_log_jvm_meminfo);
PG_FUNCTION_INFO_V1(synchdb_get_stats);
PG_FUNCTION_INFO_V1(synchdb_reset_stats);
/* Constants */
#define SYNCHDB_METADATA_DIR "pg_synchdb"
#define DBZ_ENGINE_JAR_FILE "dbz-engine-1.0.0.jar"
#define MAX_PATH_LENGTH 1024
#define MAX_JAVA_OPTION_LENGTH 256
/* Global variables */
SynchdbSharedState *sdb_state = NULL; /* Pointer to shared-memory state. */
int myConnectorId = -1; /* Global index number to SynchdbSharedState in shared memory - global per worker */
ExtraConnectionInfo extraConnInfo = {0}; /* global extra connector parameters read from rule file */
/* GUC variables */
int synchdb_worker_naptime = 500;
bool synchdb_dml_use_spi = false;
bool synchdb_auto_launcher = true;
int dbz_batch_size = 2048;
int dbz_queue_size = 8192;
char * dbz_skipped_operations = "t";
int dbz_connect_timeout_ms = 30000;
int dbz_query_timeout_ms = 600000;
int jvm_max_heap_size = 0;
int dbz_snapshot_thread_num = 2;
int dbz_snapshot_fetch_size = 0; /* 0: auto */
int dbz_snapshot_min_row_to_stream_results = 0; /* 0: always stream */
int dbz_incremental_snapshot_chunk_size = 2048;
char * dbz_incremental_snapshot_watermarking_strategy = "insert_insert";
int dbz_offset_flush_interval_ms = 60000;
bool dbz_capture_only_selected_table_ddl = true;
int synchdb_max_connector_workers = 30;
/* JNI-related variables */
static JavaVM *jvm = NULL; /* represents java vm instance */
static JNIEnv *env = NULL; /* represents JNI run-time environment */
static jclass cls; /* represents debezium runner java class */
static jobject obj; /* represents debezium runner java class object */
/* Function declarations */
PGDLLEXPORT void synchdb_engine_main(Datum main_arg);
PGDLLEXPORT void synchdb_auto_launcher_main(Datum main_arg);
/* Static function prototypes */
static int dbz_engine_stop(void);
static int dbz_engine_init(JNIEnv *env, jclass *cls, jobject *obj);
static int dbz_engine_get_change(JavaVM *jvm, JNIEnv *env, jclass *cls, jobject *obj, int myConnectorId, bool * dbzExitSignal,
BatchInfo * batchinfo, SynchdbStatistics * myBatchStats);
static int dbz_engine_start(const ConnectionInfo *connInfo, ConnectorType connectorType, const char * snapshotMode);
static char *dbz_engine_get_offset(int connectorId);
static int dbz_mark_batch_complete(int batchid);
static TupleDesc synchdb_state_tupdesc(void);
static TupleDesc synchdb_stats_tupdesc(void);
static void synchdb_init_shmem(void);
static void synchdb_detach_shmem(int code, Datum arg);
static void prepare_bgw(BackgroundWorker *worker, const ConnectionInfo *connInfo, const char *connector, int connectorid, const char * snapshotMode);
static const char *connectorStateAsString(ConnectorState state);
static void reset_shm_request_state(int connectorId);
static int dbz_engine_set_offset(ConnectorType connectorType, char *db, char *offset, char *file);
static void processRequestInterrupt(const ConnectionInfo *connInfo, ConnectorType type, int connectorId, const char * snapshotMode);
static void setup_environment(ConnectorType * connectorType, ConnectionInfo *conninfo, char ** snapshotMode);
static void initialize_jvm(void);
static void start_debezium_engine(ConnectorType connectorType, const ConnectionInfo *connInfo, const char * snapshotMode);
static void main_loop(ConnectorType connectorType, const ConnectionInfo *connInfo, const char * snapshotMode);
static void cleanup(ConnectorType connectorType);
static void set_extra_dbz_parameters(jobject myParametersObj, jclass myParametersClass);
static void set_shm_connector_statistics(int connectorId, SynchdbStatistics * stats);
/*
* count_active_connectors
*
* helper function to count number of active connectors
*
* @return: number of active connectors
*/
static int
count_active_connectors(void)
{
int i = 0;
for (i = 0; i < synchdb_max_connector_workers; i++)
{
/* if an empty name is found, there is no need to continue counting */
if (strlen(sdb_state->connectors[i].conninfo.name) == 0)
break;
}
return i;
}
/*
* set_extra_dbz_parameters - configures extra paramters for Debezium runner
*
* This function builds myParametersObj with extra parameters to be passed
* to the Debezium Java side.
*
* @return: void
*/
static void set_extra_dbz_parameters(jobject myParametersObj, jclass myParametersClass)
{
jmethodID setBatchSize, setQueueSize, setSkippedOperations, setConnectTimeout, setQueryTimeout;
jmethodID setSnapshotThreadNum, setSnapshotFetchSize, setSnapshotMinRowToStreamResults;
jmethodID setIncrementalSnapshotChunkSize, setIncrementalSnapshotWatermarkingStrategy;
jmethodID setOffsetFlushIntervalMs, setCaptureOnlySelectedTableDDL;
jmethodID setSslmode, setSslKeystore, setSslKeystorePass, setSslTruststore, setSslTruststorePass;
jstring jdbz_skipped_operations, jdbz_watermarking_strategy;
jstring jdbz_sslmode, jdbz_sslkeystore, jdbz_sslkeystorepass, jdbz_ssltruststore, jdbz_ssltruststorepass;
setBatchSize = (*env)->GetMethodID(env, myParametersClass, "setBatchSize",
"(I)Lcom/example/DebeziumRunner$MyParameters;");
if (setBatchSize)
{
myParametersObj = (*env)->CallObjectMethod(env, myParametersObj, setBatchSize, dbz_batch_size);
if (!myParametersObj)
{
elog(WARNING, "failed to call setBatchSize method");
}
}
else
elog(WARNING, "failed to find setBatchSize method");
setQueueSize = (*env)->GetMethodID(env, myParametersClass, "setQueueSize",
"(I)Lcom/example/DebeziumRunner$MyParameters;");
if (setQueueSize)
{
myParametersObj = (*env)->CallObjectMethod(env, myParametersObj, setQueueSize, dbz_queue_size);
if (!myParametersObj)
{
elog(WARNING, "failed to call setQueueSize method");
}
}
else
elog(WARNING, "failed to find setQueueSize method");
setConnectTimeout = (*env)->GetMethodID(env, myParametersClass, "setConnectTimeout",
"(I)Lcom/example/DebeziumRunner$MyParameters;");
if (setConnectTimeout)
{
myParametersObj = (*env)->CallObjectMethod(env, myParametersObj, setConnectTimeout, dbz_connect_timeout_ms);
if (!myParametersObj)
{
elog(WARNING, "failed to call setConnectTimeout method");
}
}
else
elog(WARNING, "failed to find setConnectTimeout method");
setQueryTimeout = (*env)->GetMethodID(env, myParametersClass, "setQueryTimeout",
"(I)Lcom/example/DebeziumRunner$MyParameters;");
if (setQueryTimeout)
{
myParametersObj = (*env)->CallObjectMethod(env, myParametersObj, setQueryTimeout, dbz_query_timeout_ms);
if (!myParametersObj)
{
elog(WARNING, "failed to call setQueryTimeout method");
}
}
else
elog(WARNING, "failed to find setQueryTimeout method");
jdbz_skipped_operations = (*env)->NewStringUTF(env, dbz_skipped_operations);
setSkippedOperations = (*env)->GetMethodID(env, myParametersClass, "setSkippedOperations",
"(Ljava/lang/String;)Lcom/example/DebeziumRunner$MyParameters;");
if (setSkippedOperations)
{
myParametersObj = (*env)->CallObjectMethod(env, myParametersObj, setSkippedOperations, jdbz_skipped_operations);
if (!myParametersObj)
{
elog(WARNING, "failed to call setSkippedOperations method");
}
}
else
elog(WARNING, "failed to find setSkippedOperations method");
if (jdbz_skipped_operations)
(*env)->DeleteLocalRef(env, jdbz_skipped_operations);
setSnapshotThreadNum = (*env)->GetMethodID(env, myParametersClass, "setSnapshotThreadNum",
"(I)Lcom/example/DebeziumRunner$MyParameters;");
if (setSnapshotThreadNum)
{
myParametersObj = (*env)->CallObjectMethod(env, myParametersObj, setSnapshotThreadNum, dbz_snapshot_thread_num);
if (!myParametersObj)
{
elog(WARNING, "failed to call setSnapshotThreadNum method");
}
}
else
elog(WARNING, "failed to find setSnapshotThreadNum method");
setSnapshotFetchSize = (*env)->GetMethodID(env, myParametersClass, "setSnapshotFetchSize",
"(I)Lcom/example/DebeziumRunner$MyParameters;");
if (setSnapshotFetchSize)
{
myParametersObj = (*env)->CallObjectMethod(env, myParametersObj, setSnapshotFetchSize, dbz_snapshot_fetch_size);
if (!myParametersObj)
{
elog(WARNING, "failed to call setSnapshotFetchSize method");
}
}
else
elog(WARNING, "failed to find setSnapshotFetchSize method");
setSnapshotMinRowToStreamResults = (*env)->GetMethodID(env, myParametersClass, "setSnapshotMinRowToStreamResults",
"(I)Lcom/example/DebeziumRunner$MyParameters;");
if (setSnapshotMinRowToStreamResults)
{
myParametersObj = (*env)->CallObjectMethod(env, myParametersObj, setSnapshotMinRowToStreamResults, dbz_snapshot_min_row_to_stream_results);
if (!myParametersObj)
{
elog(WARNING, "failed to call setSnapshotMinRowToStreamResults method");
}
}
else
elog(WARNING, "failed to find setSnapshotMinRowToStreamResults method");
setIncrementalSnapshotChunkSize = (*env)->GetMethodID(env, myParametersClass, "setIncrementalSnapshotChunkSize",
"(I)Lcom/example/DebeziumRunner$MyParameters;");
if (setIncrementalSnapshotChunkSize)
{
myParametersObj = (*env)->CallObjectMethod(env, myParametersObj, setIncrementalSnapshotChunkSize, dbz_incremental_snapshot_chunk_size);
if (!myParametersObj)
{
elog(WARNING, "failed to call setIncrementalSnapshotChunkSize method");
}
}
else
elog(WARNING, "failed to find setIncrementalSnapshotChunkSize method");
jdbz_watermarking_strategy = (*env)->NewStringUTF(env, dbz_incremental_snapshot_watermarking_strategy);
setIncrementalSnapshotWatermarkingStrategy = (*env)->GetMethodID(env, myParametersClass, "setIncrementalSnapshotWatermarkingStrategy",
"(Ljava/lang/String;)Lcom/example/DebeziumRunner$MyParameters;");
if (setIncrementalSnapshotWatermarkingStrategy)
{
myParametersObj = (*env)->CallObjectMethod(env, myParametersObj, setIncrementalSnapshotWatermarkingStrategy, jdbz_watermarking_strategy);
if (!myParametersObj)
{
elog(WARNING, "failed to call setIncrementalSnapshotWatermarkingStrategy method");
}
}
else
elog(WARNING, "failed to find setIncrementalSnapshotWatermarkingStrategy method");
if (jdbz_watermarking_strategy)
(*env)->DeleteLocalRef(env, jdbz_watermarking_strategy);
setOffsetFlushIntervalMs = (*env)->GetMethodID(env, myParametersClass, "setOffsetFlushIntervalMs",
"(I)Lcom/example/DebeziumRunner$MyParameters;");
if (setOffsetFlushIntervalMs)
{
myParametersObj = (*env)->CallObjectMethod(env, myParametersObj, setOffsetFlushIntervalMs, dbz_offset_flush_interval_ms);
if (!myParametersObj)
{
elog(WARNING, "failed to call setOffsetFlushIntervalMs method");
}
}
else
elog(WARNING, "failed to find setOffsetFlushIntervalMs method");
setCaptureOnlySelectedTableDDL = (*env)->GetMethodID(env, myParametersClass, "setCaptureOnlySelectedTableDDL",
"(Z)Lcom/example/DebeziumRunner$MyParameters;");
if (setCaptureOnlySelectedTableDDL)
{
jboolean bval = dbz_capture_only_selected_table_ddl ? JNI_TRUE : JNI_FALSE;
myParametersObj = (*env)->CallObjectMethod(env, myParametersObj, setCaptureOnlySelectedTableDDL, bval);
if (!myParametersObj)
{
elog(WARNING, "failed to call setCaptureOnlySelectedTableDDL method");
}
}
else
elog(WARNING, "failed to find setCaptureOnlySelectedTableDDL method");
jdbz_watermarking_strategy = (*env)->NewStringUTF(env, dbz_incremental_snapshot_watermarking_strategy);
setIncrementalSnapshotWatermarkingStrategy = (*env)->GetMethodID(env, myParametersClass, "setIncrementalSnapshotWatermarkingStrategy",
"(Ljava/lang/String;)Lcom/example/DebeziumRunner$MyParameters;");
if (setIncrementalSnapshotWatermarkingStrategy)
{
myParametersObj = (*env)->CallObjectMethod(env, myParametersObj, setIncrementalSnapshotWatermarkingStrategy, jdbz_watermarking_strategy);
if (!myParametersObj)
{
elog(WARNING, "failed to call setIncrementalSnapshotWatermarkingStrategy method");
}
}
else
elog(WARNING, "failed to find setIncrementalSnapshotWatermarkingStrategy method");
if (jdbz_watermarking_strategy)
(*env)->DeleteLocalRef(env, jdbz_watermarking_strategy);
if (extraConnInfo.ssl_mode != NULL)
{
jdbz_sslmode = (*env)->NewStringUTF(env, extraConnInfo.ssl_mode);
setSslmode = (*env)->GetMethodID(env, myParametersClass, "setSslmode",
"(Ljava/lang/String;)Lcom/example/DebeziumRunner$MyParameters;");
if (setSslmode)
{
myParametersObj = (*env)->CallObjectMethod(env, myParametersObj, setSslmode, jdbz_sslmode);
if (!myParametersObj)
{
elog(WARNING, "failed to call setSslmode method");
}
}
else
elog(WARNING, "failed to find setSslmode method");
if (jdbz_sslmode)
(*env)->DeleteLocalRef(env, jdbz_sslmode);
}
if (extraConnInfo.ssl_keystore != NULL)
{
jdbz_sslkeystore = (*env)->NewStringUTF(env, extraConnInfo.ssl_keystore);
setSslKeystore = (*env)->GetMethodID(env, myParametersClass, "setSslKeystore",
"(Ljava/lang/String;)Lcom/example/DebeziumRunner$MyParameters;");
if (setSslKeystore)
{
myParametersObj = (*env)->CallObjectMethod(env, myParametersObj, setSslKeystore, jdbz_sslkeystore);
if (!myParametersObj)
{
elog(WARNING, "failed to call setSslKeystore method");
}
}
else
elog(WARNING, "failed to find setSslKeystore method");
if (jdbz_sslkeystore)
(*env)->DeleteLocalRef(env, jdbz_sslkeystore);
}
if (extraConnInfo.ssl_keystore_pass != NULL)
{
jdbz_sslkeystorepass = (*env)->NewStringUTF(env, extraConnInfo.ssl_keystore_pass);
setSslKeystorePass = (*env)->GetMethodID(env, myParametersClass, "setSslKeystorePass",
"(Ljava/lang/String;)Lcom/example/DebeziumRunner$MyParameters;");
if (setSslKeystorePass)
{
myParametersObj = (*env)->CallObjectMethod(env, myParametersObj, setSslKeystorePass, jdbz_sslkeystorepass);
if (!myParametersObj)
{
elog(WARNING, "failed to call setSslKeystorePass method");
}
}
else
elog(WARNING, "failed to find setSslKeystorePass method");
if (jdbz_sslkeystorepass)
(*env)->DeleteLocalRef(env, jdbz_sslkeystorepass);
}
if (extraConnInfo.ssl_truststore != NULL)
{
jdbz_ssltruststore = (*env)->NewStringUTF(env, extraConnInfo.ssl_truststore);
setSslTruststore = (*env)->GetMethodID(env, myParametersClass, "setSslTruststore",
"(Ljava/lang/String;)Lcom/example/DebeziumRunner$MyParameters;");
if (setSslTruststore)
{
myParametersObj = (*env)->CallObjectMethod(env, myParametersObj, setSslTruststore, jdbz_ssltruststore);
if (!myParametersObj)
{
elog(WARNING, "failed to call setSslTruststore method");
}
}
else
elog(WARNING, "failed to find setSslTruststore method");
if (jdbz_ssltruststore)
(*env)->DeleteLocalRef(env, jdbz_ssltruststore);
}
if (extraConnInfo.ssl_truststore_pass != NULL)
{
jdbz_ssltruststorepass = (*env)->NewStringUTF(env, extraConnInfo.ssl_truststore_pass);
setSslTruststorePass = (*env)->GetMethodID(env, myParametersClass, "setSslTruststorePass",
"(Ljava/lang/String;)Lcom/example/DebeziumRunner$MyParameters;");
if (setSslTruststorePass)
{
myParametersObj = (*env)->CallObjectMethod(env, myParametersObj, setSslTruststorePass, jdbz_ssltruststorepass);
if (!myParametersObj)
{
elog(WARNING, "failed to call setSslTruststorePass method");
}
}
else
elog(WARNING, "failed to find setSslTruststorePass method");
if (jdbz_ssltruststorepass)
(*env)->DeleteLocalRef(env, jdbz_ssltruststorepass);
}
/*
* additional parameters that we want to pass to Debezium on the java side
* will be added here, Make sure to add the matching methods in the MyParameters
* inner class inside DebeziumRunner class.
*/
}
/*
* dbz_engine_stop - Stop the Debezium engine
*
* This function stops the Debezium engine by calling the stopEngine method
* on the DebeziumRunner object.
*
* @return: 0 on success, -1 on failure
*/
static int
dbz_engine_stop(void)
{
jmethodID stopEngine;
jthrowable exception;
if (!jvm)
{
elog(WARNING, "jvm not initialized");
return -1;
}
if (!env)
{
elog(WARNING, "jvm env not initialized");
return -1;
}
/* Find the stopEngine method */
stopEngine = (*env)->GetMethodID(env, cls, "stopEngine", "()V");
if (stopEngine == NULL)
{
elog(WARNING, "Failed to find stopEngine method");
return -1;
}
(*env)->CallVoidMethod(env, obj, stopEngine);
/* Check for exceptions */
exception = (*env)->ExceptionOccurred(env);
if (exception)
{
(*env)->ExceptionDescribe(env);
(*env)->ExceptionClear(env);
elog(WARNING, "Exception occurred while stopping Debezium engine");
return -1;
}
return 0;
}
/*
* dbz_engine_init - Initialize the Debezium engine
*
* This function initializes the Debezium engine by finding the DebeziumRunner
* class and allocating an instance of it. It handles JNI interactions and
* exception checking.
*
* @param env: JNI environment pointer
* @param cls: Pointer to store the found Java class
* @param obj: Pointer to store the allocated Java object
*
* @return: 0 on success, -1 on failure
*/
static int
dbz_engine_init(JNIEnv *env, jclass *cls, jobject *obj)
{
elog(DEBUG1, "dbz_engine_init - Starting initialization");
/* Find the DebeziumRunner class */
*cls = (*env)->FindClass(env, "com/example/DebeziumRunner");
if (*cls == NULL)
{
if ((*env)->ExceptionCheck(env))
{
(*env)->ExceptionDescribe(env);
(*env)->ExceptionClear(env);
}
elog(WARNING, "Failed to find com.example.DebeziumRunner class");
return -1;
}
elog(DEBUG1, "dbz_engine_init - Class found, allocating object");
/* Allocate an instance of the DebeziumRunner class */
*obj = (*env)->AllocObject(env, *cls);
if (*obj == NULL)
{
if ((*env)->ExceptionCheck(env))
{
(*env)->ExceptionDescribe(env);
(*env)->ExceptionClear(env);
}
elog(WARNING, "Failed to allocate DBZ Runner object");
return -1;
}
elog(DEBUG1, "dbz_engine_init - Object allocated successfully");
return 0;
}
/*
* processCompletionMessage - completion message processor
*
* This function processes the completion message sent from the Debezium runner
* in the event of an connector exit
*
* @param eventStr: the completion message string
* @param myConnectorId: Connector ID of interest
* @param dbzExitSignal: Set by the function to indicate connector has exited
*
* @return: void
*/
static void
processCompletionMessage(const char * eventStr, int myConnectorId, bool * dbzExitSignal)
{
char * msgcopy = pstrdup(eventStr + 2); /* skip K- */
char * successflag = NULL;
char * message = NULL;
elog(DEBUG1, "completion message: %s", msgcopy);
/*
* success flag indicates if worker exits successfully or due to an error.
* Currently not used
*/
successflag = strtok(msgcopy, ";");
/* remove compiler warning */
if (successflag && strlen(successflag) > 0)
{
/* presence of successflag indicates that the DBZ connector in java has exited */
elog(DEBUG1, "successflag = %s", successflag);
*dbzExitSignal = true;
}
/*
* message is the last error or exit message the connector produced before
* it exited
*/
message = strtok(NULL, ";");
if (message)
{
/* save it to shm for display to use */
set_shm_connector_errmsg(myConnectorId, message);
}
}
/*
* dbz_engine_get_change - Retrieve and process change events from the Debezium engine
*
* This function retrieves change events from the Debezium engine and processes them.
*
* @param jvm: Pointer to the Java VM
* @param env: Pointer to the JNI environment
* @param cls: Pointer to the DebeziumRunner class
* @param obj: Pointer to the DebeziumRunner object
* @param myConnectorId: The connector ID of interest
* @param dbzExitSignal: Set by this function to indicate the connector has exited
* @param batchinfo: Set by this function to indicate a valid batch is in progress
* @param myBatchStats: update connector statistics to this struct
*
* @return: 0 on success, -1 on failure
*/
static int
dbz_engine_get_change(JavaVM *jvm, JNIEnv *env, jclass *cls, jobject *obj, int myConnectorId,
bool * dbzExitSignal, BatchInfo * batchinfo, SynchdbStatistics * myBatchStats)
{
jmethodID getChangeEvents, sizeMethod, getMethod;
jobject changeEventsList;
jint size;
jclass listClass;
jobject event;
const char *eventStr;
/* Validate input parameters */
if (!jvm || !env || !cls || !obj)
{
elog(WARNING, "dbz_engine_get_change: Invalid input parameters");
return -1;
}
/* Get the getChangeEvents method */
getChangeEvents = (*env)->GetMethodID(env, *cls, "getChangeEvents", "()Ljava/util/List;");
if (getChangeEvents == NULL)
{
elog(WARNING, "Failed to find getChangeEvents method");
return -1;
}
/* Call getChangeEvents method */
changeEventsList = (*env)->CallObjectMethod(env, *obj, getChangeEvents);
if ((*env)->ExceptionCheck(env))
{
(*env)->ExceptionDescribe(env);
(*env)->ExceptionClear(env);
elog(WARNING, "Exception occurred while calling getChangeEvents");
return -1;
}
if (changeEventsList == NULL)
{
elog(WARNING, "dbz_engine_get_change: getChangeEvents returned null");
return -1;
}
/* Get List class and methods */
listClass = (*env)->FindClass(env, "java/util/List");
if (listClass == NULL)
{
elog(WARNING, "Failed to find java list class");
(*env)->DeleteLocalRef(env, changeEventsList);
return -1;
}
sizeMethod = (*env)->GetMethodID(env, listClass, "size", "()I");
if (sizeMethod == NULL)
{
elog(WARNING, "Failed to find java list.size method");
(*env)->DeleteLocalRef(env, changeEventsList);
(*env)->DeleteLocalRef(env, listClass);
return -1;
}
getMethod = (*env)->GetMethodID(env, listClass, "get", "(I)Ljava/lang/Object;");
if (getMethod == NULL)
{
elog(WARNING, "Failed to find java list.get method");
return -1;
}
/* Process change events */
size = (*env)->CallIntMethod(env, changeEventsList, sizeMethod);
elog(DEBUG1, "dbz_engine_get_change: Retrieved %d change events", size);
if (size == 0 || size < 0)
{
/* nothing to process, set current stage to CDC and return */
if (get_shm_connector_stage_enum(myConnectorId) != STAGE_CHANGE_DATA_CAPTURE)
{
set_shm_connector_stage(myConnectorId, STAGE_CHANGE_DATA_CAPTURE);
}
(*env)->DeleteLocalRef(env, changeEventsList);
(*env)->DeleteLocalRef(env, listClass);
return -1;
}
batchinfo->batchSize = size - 1; /* minus the metadata record */
/* fetch special metadata element at index 0 and convert it to string */
event = (*env)->CallObjectMethod(env, changeEventsList, getMethod, 0);
if (event == NULL)
{
elog(WARNING, "dbz_engine_get_change: missing metadata element at index 0");
(*env)->DeleteLocalRef(env, changeEventsList);
(*env)->DeleteLocalRef(env, listClass);
return -1;
}
eventStr = (*env)->GetStringUTFChars(env, (jstring)event, 0);
if (eventStr == NULL)
{
elog(WARNING, "dbz_engine_get_change: Failed to convert metadata element to string");
(*env)->DeleteLocalRef(env, event);
(*env)->DeleteLocalRef(env, changeEventsList);
(*env)->DeleteLocalRef(env, listClass);
return -1;
}
/* check if it is a completion message */
if (eventStr[0] == 'K' && eventStr[1] == '-')
{
/*
* connector completion/error message, consume it right here
* This may also indicates that the dbz connector on java side
* has exited and we may need to exit later as well.
*/
processCompletionMessage(eventStr, myConnectorId, dbzExitSignal);
(*env)->ReleaseStringUTFChars(env, (jstring)event, eventStr);
(*env)->DeleteLocalRef(env, event);
(*env)->DeleteLocalRef(env, changeEventsList);
(*env)->DeleteLocalRef(env, listClass);
return 0;
}
/* check if it is a batch change request */
else if (eventStr[0] == 'B' && eventStr[1] == '-')
{
/*
* obtain the batch id as we will need it to commit debezium offsets
* as we process the batch
*/
batchinfo->batchId = atoi(&eventStr[2]);
elog(DEBUG1, "Synchdb received batchid(%d) with size(%d)", batchinfo->batchId, size-1);
/* free reference to metadata element at index 0 */
(*env)->ReleaseStringUTFChars(env, (jstring)event, eventStr);
(*env)->DeleteLocalRef(env, event);
StartTransactionCommand();
PushActiveSnapshot(GetTransactionSnapshot());
/* now process the rest of the changes in the batch */
for (int i = 1; i < size; i++)
{
event = (*env)->CallObjectMethod(env, changeEventsList, getMethod, i);
if (event == NULL)
{
elog(DEBUG1, "dbz_engine_get_change: Received NULL event at index %d", i);
increment_connector_statistics(myBatchStats, STATS_BAD_CHANGE_EVENT, 1);
continue;
}
eventStr = (*env)->GetStringUTFChars(env, (jstring)event, 0);
if (eventStr == NULL)
{
elog(WARNING, "dbz_engine_get_change: Failed to get string for event at index %d", i);
(*env)->DeleteLocalRef(env, event);
increment_connector_statistics(myBatchStats, STATS_BAD_CHANGE_EVENT, 1);
continue;
}
elog(DEBUG1, "Processing DBZ Event: %s", eventStr);
/* change event message, send to format converter */
if (fc_processDBZChangeEvent(eventStr, myBatchStats) != 0)
{
elog(DEBUG1, "dbz_engine_get_change: Failed to process event at index %d", i);
}
(*env)->ReleaseStringUTFChars(env, (jstring)event, eventStr);
(*env)->DeleteLocalRef(env, event);
}
PopActiveSnapshot();
CommitTransactionCommand();
increment_connector_statistics(myBatchStats, STATS_TOTAL_CHANGE_EVENT, size-1);
/* read offset currently flushed to file for displaying to user */
set_shm_dbz_offset(myConnectorId);
}
else
{
elog(WARNING, "unknown change request");
}
(*env)->DeleteLocalRef(env, changeEventsList);
(*env)->DeleteLocalRef(env, listClass);
return 0;
}
/*
* dbz_engine_start - Start the Debezium engine
*
* This function starts the Debezium engine with the provided connection information.
*
* @param connInfo: Pointer to the ConnectionInfo structure containing connection details
* @param connectorType: The type of connector to start
* @param snapshotMode: Snapshot mode to start the connector with
*
* @return: 0 on success, -1 on failure
*/
static int
dbz_engine_start(const ConnectionInfo *connInfo, ConnectorType connectorType, const char * snapshotMode)
{
jmethodID mid, paramConstruct;
jstring jHostname, jUser, jPassword, jDatabase, jTable, jName, jSnapshot;
jthrowable exception;
jclass myParametersClass;
jobject myParametersObj;
elog(LOG, "dbz_engine_start: Starting dbz engine %s:%d ", connInfo->hostname, connInfo->port);
if (!jvm)
{
elog(WARNING, "jvm not initialized");
return -1;
}
if (!env)
{
elog(WARNING, "jvm env not initialized");
return -1;
}
myParametersClass = (*env)->FindClass(env, "com/example/DebeziumRunner$MyParameters");
if (!myParametersClass)
{
elog(WARNING, "failed to find MyParameters class");
return -1;
}
paramConstruct = (*env)->GetMethodID(env, myParametersClass, "<init>",
"(Lcom/example/DebeziumRunner;Ljava/lang/String;ILjava/lang/String;ILjava/lang/String;"
"Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V");
if (paramConstruct == NULL)
{
elog(WARNING, "failed to find myParameters Constructor");
return -1;
}
/* prepare required parameters */
jHostname = (*env)->NewStringUTF(env, connInfo->hostname);
jUser = (*env)->NewStringUTF(env, connInfo->user);
jPassword = (*env)->NewStringUTF(env, connInfo->pwd);
jDatabase = (*env)->NewStringUTF(env, connInfo->srcdb);
jTable = (*env)->NewStringUTF(env, connInfo->table);
jName = (*env)->NewStringUTF(env, connInfo->name);
jSnapshot = (*env)->NewStringUTF(env, snapshotMode);
myParametersObj = (*env)->NewObject(env, myParametersClass, paramConstruct, obj,
jName, connectorType, jHostname, connInfo->port, jUser, jPassword,
jDatabase, jTable, jSnapshot);
if (!myParametersObj)
{
elog(WARNING, "failed to create MyParameters object");
return -1;
}
/* set extra parameters */
set_extra_dbz_parameters(myParametersObj, myParametersClass);
/* Find the startEngine method */
mid = (*env)->GetMethodID(env, cls, "startEngine", "(Lcom/example/DebeziumRunner$MyParameters;)V");
if (mid == NULL)
{
elog(WARNING, "Failed to find startEngine method");
return -1;
}
/* Call the Java method */
(*env)->CallVoidMethod(env, obj, mid, myParametersObj);
/* Check for exceptions */
exception = (*env)->ExceptionOccurred(env);
if (exception)
{
(*env)->ExceptionDescribe(env);
(*env)->ExceptionClear(env);
elog(WARNING, "Exception occurred while starting Debezium engine");
goto cleanup;
}
elog(LOG, "Debezium engine started successfully for %s connector", connectorTypeToString(connectorType));
cleanup:
/* Clean up local references */
if (jHostname)
(*env)->DeleteLocalRef(env, jHostname);
if (jUser)
(*env)->DeleteLocalRef(env, jUser);
if (jPassword)
(*env)->DeleteLocalRef(env, jPassword);
if (jDatabase)
(*env)->DeleteLocalRef(env, jDatabase);
if (jTable)
(*env)->DeleteLocalRef(env, jTable);
if (jName)
(*env)->DeleteLocalRef(env, jName);
if (jSnapshot)
(*env)->DeleteLocalRef(env, jSnapshot);
return exception ? -1 : 0;
}
/*
* dbz_engine_get_offset - Get the current offset from the Debezium engine
*
* This function retrieves the current offset for a specific connector type
* from the Debezium engine.
*
* @param connectorId: The connector ID of interest
*
* @return: The offset as a string (caller must free), or NULL on failure
*/
static char *
dbz_engine_get_offset(int connectorId)
{
jmethodID getoffsets;
jstring jdb, result, jName;
char *resultStr = NULL;
char *db = NULL, *name = NULL;
const char *tmp;
jthrowable exception;
if (!jvm)
{
elog(WARNING, "jvm not initialized");
return NULL;
}
if (!env)
{
elog(WARNING, "jvm env not initialized");
return NULL;
}
/* Get the source database name based on connector type */
db = sdb_state->connectors[connectorId].conninfo.srcdb;
if (!db)
{
elog(WARNING, "Source database name not set for connector type: %d",
sdb_state->connectors[connectorId].type);
return NULL;
}
/* Get the unique name */
name = sdb_state->connectors[connectorId].conninfo.name;
if (!name)
{
elog(WARNING, "Unique name not set for connector type: %d",
sdb_state->connectors[connectorId].type);
return NULL;
}
getoffsets = (*env)->GetMethodID(env, cls, "getConnectorOffset",
"(ILjava/lang/String;Ljava/lang/String;)Ljava/lang/String;");
if (getoffsets == NULL)
{
elog(WARNING, "Failed to find getConnectorOffset method");
return NULL;
}
jdb = (*env)->NewStringUTF(env, db);
jName = (*env)->NewStringUTF(env, name);
result = (jstring)(*env)->CallObjectMethod(env, obj, getoffsets,
(int)sdb_state->connectors[connectorId].type, jdb, jName);
/* Check for exceptions */
exception = (*env)->ExceptionOccurred(env);
if (exception)
{
(*env)->ExceptionDescribe(env);
(*env)->ExceptionClear(env);
elog(WARNING, "Exception occurred while getting connector offset");
(*env)->DeleteLocalRef(env, jdb);
(*env)->DeleteLocalRef(env, jName);
return NULL;
}
/* Convert Java string to C string */
tmp = (*env)->GetStringUTFChars(env, result, NULL);
if (tmp && strlen(tmp) > 0)
resultStr = pstrdup(tmp);
else
resultStr = pstrdup("no offset");