/
LogicalReplicationStatusTest.java
538 lines (428 loc) · 17 KB
/
LogicalReplicationStatusTest.java
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
/*
* Copyright (c) 2016, PostgreSQL Global Development Group
* See the LICENSE file in the project root for more information.
*/
package org.postgresql.replication;
import static org.hamcrest.CoreMatchers.not;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.IsEqual.equalTo;
import org.postgresql.PGConnection;
import org.postgresql.PGProperty;
import org.postgresql.core.BaseConnection;
import org.postgresql.core.ServerVersion;
import org.postgresql.test.TestUtil;
import org.postgresql.test.util.rules.ServerVersionRule;
import org.postgresql.test.util.rules.annotation.HaveMinimalServerVersion;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import java.nio.ByteBuffer;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.concurrent.TimeUnit;
@HaveMinimalServerVersion("9.4")
public class LogicalReplicationStatusTest {
private static final String SLOT_NAME = "pgjdbc_logical_replication_slot";
@Rule
public ServerVersionRule versionRule = new ServerVersionRule();
private Connection replicationConnection;
private Connection sqlConnection;
@Before
public void setUp() throws Exception {
//statistic available only for privileged user
sqlConnection = TestUtil.openPrivilegedDB();
//DriverManager.setLogWriter(new PrintWriter(System.out));
replicationConnection = openReplicationConnection();
TestUtil.createTable(sqlConnection, "test_logic_table",
"pk serial primary key, name varchar(100)");
TestUtil.recreateLogicalReplicationSlot(sqlConnection, SLOT_NAME, "test_decoding");
}
@After
public void tearDown() throws Exception {
replicationConnection.close();
TestUtil.dropTable(sqlConnection, "test_logic_table");
TestUtil.dropReplicationSlot(sqlConnection, SLOT_NAME);
sqlConnection.close();
}
@Test()
public void testSentLocationEqualToLastReceiveLSN() throws Exception {
PGConnection pgConnection = (PGConnection) replicationConnection;
LogSequenceNumber startLSN = getCurrentLSN();
Statement st = sqlConnection.createStatement();
st.execute("insert into test_logic_table(name) values('previous changes')");
st.close();
PGReplicationStream stream =
pgConnection
.getReplicationAPI()
.replicationStream()
.logical()
.withSlotName(SLOT_NAME)
.withStartPosition(startLSN)
.start();
final int countMessage = 3;
List<String> received = receiveMessageWithoutBlock(stream, countMessage);
LogSequenceNumber lastReceivedLSN = stream.getLastReceiveLSN();
stream.forceUpdateStatus();
int lastPayloadSize =
received
.get(countMessage - 1)
.getBytes()
.length;
LogSequenceNumber waitLsn = LogSequenceNumber.valueOf(lastReceivedLSN.asLong() - lastPayloadSize);
LogSequenceNumber sentByServer = getSentLocationOnView();
assertThat("When changes absent on server last receive by stream LSN "
+ "should be equal to last sent by server LSN",
sentByServer, equalTo(waitLsn)
);
}
/**
* Test fail on PG version 9.4.5 because postgresql have bug
*/
@Test
@HaveMinimalServerVersion("9.4.8")
public void testReceivedLSNDependentOnProcessMessage() throws Exception {
PGConnection pgConnection = (PGConnection) replicationConnection;
LogSequenceNumber startLSN = getCurrentLSN();
Statement st = sqlConnection.createStatement();
st.execute("insert into test_logic_table(name) values('previous changes')");
st.close();
PGReplicationStream stream =
pgConnection
.getReplicationAPI()
.replicationStream()
.logical()
.withSlotName(SLOT_NAME)
.withStartPosition(startLSN)
.start();
receiveMessageWithoutBlock(stream, 1);
LogSequenceNumber firstLSN = stream.getLastReceiveLSN();
receiveMessageWithoutBlock(stream, 1);
LogSequenceNumber secondLSN = stream.getLastReceiveLSN();
assertThat("After receive each new message current LSN updates in stream",
firstLSN, not(equalTo(secondLSN))
);
}
@Test
public void testLastReceiveLSNCorrectOnView() throws Exception {
PGConnection pgConnection = (PGConnection) replicationConnection;
LogSequenceNumber startLSN = getCurrentLSN();
Statement st = sqlConnection.createStatement();
st.execute("insert into test_logic_table(name) values('previous changes')");
st.close();
PGReplicationStream stream =
pgConnection
.getReplicationAPI()
.replicationStream()
.logical()
.withSlotName(SLOT_NAME)
.withStartPosition(startLSN)
.start();
receiveMessageWithoutBlock(stream, 2);
LogSequenceNumber lastReceivedLSN = stream.getLastReceiveLSN();
stream.forceUpdateStatus();
assertThat(
"Replication stream by execute forceUpdateStatus should send to view actual received position "
+ "that allow monitoring lag",
lastReceivedLSN, equalTo(getWriteLocationOnView())
);
}
@Test
public void testWriteLocationCanBeLessThanSendLocation() throws Exception {
PGConnection pgConnection = (PGConnection) replicationConnection;
LogSequenceNumber startLSN = getCurrentLSN();
Statement st = sqlConnection.createStatement();
st.execute("insert into test_logic_table(name) values('previous changes')");
st.close();
PGReplicationStream stream =
pgConnection
.getReplicationAPI()
.replicationStream()
.logical()
.withSlotName(SLOT_NAME)
.withStartPosition(startLSN)
.start();
receiveMessageWithoutBlock(stream, 2);
stream.forceUpdateStatus();
LogSequenceNumber writeLocation = getWriteLocationOnView();
LogSequenceNumber sentLocation = getSentLocationOnView();
assertThat(
"In view pg_stat_replication column write_location define which position consume client "
+ "but sent_location define which position was sent to client, so in current test we have 1 pending message, "
+ "so write and sent can't be equals",
writeLocation, not(equalTo(sentLocation))
);
}
@Test
public void testFlushLocationEqualToSetLocation() throws Exception {
PGConnection pgConnection = (PGConnection) replicationConnection;
LogSequenceNumber startLSN = getCurrentLSN();
Statement st = sqlConnection.createStatement();
st.execute("insert into test_logic_table(name) values('previous changes')");
st.close();
PGReplicationStream stream =
pgConnection
.getReplicationAPI()
.replicationStream()
.logical()
.withSlotName(SLOT_NAME)
.withStartPosition(startLSN)
.start();
receiveMessageWithoutBlock(stream, 1);
LogSequenceNumber flushLSN = stream.getLastReceiveLSN();
stream.setFlushedLSN(flushLSN);
//consume another messages
receiveMessageWithoutBlock(stream, 2);
stream.forceUpdateStatus();
LogSequenceNumber result = getFlushLocationOnView();
assertThat("Flush LSN use for define which wal can be recycled and it parameter should be "
+ "specify manually on replication stream, because only client "
+ "of replication stream now which wal not necessary. We wait that it status correct "
+ "send to backend and available via view, because if status will "
+ "not send it lead to problem when WALs never recycled",
result, equalTo(flushLSN)
);
}
@Test
public void testFlushLocationDoNotChangeDuringReceiveMessage() throws Exception {
PGConnection pgConnection = (PGConnection) replicationConnection;
LogSequenceNumber startLSN = getCurrentLSN();
Statement st = sqlConnection.createStatement();
st.execute("insert into test_logic_table(name) values('previous changes')");
st.close();
PGReplicationStream stream =
pgConnection
.getReplicationAPI()
.replicationStream()
.logical()
.withSlotName(SLOT_NAME)
.withStartPosition(startLSN)
.start();
receiveMessageWithoutBlock(stream, 1);
final LogSequenceNumber flushLSN = stream.getLastReceiveLSN();
stream.setFlushedLSN(flushLSN);
receiveMessageWithoutBlock(stream, 2);
assertThat(
"Flush LSN it parameter that specify manually on stream and they can not automatically "
+ "change during receive another messages, "
+ "because auto update can lead to problem when WAL recycled on postgres "
+ "because we send feedback that current position successfully flush, but in real they not flush yet",
stream.getLastFlushedLSN(), equalTo(flushLSN)
);
}
@Test
public void testApplyLocationEqualToSetLocation() throws Exception {
PGConnection pgConnection = (PGConnection) replicationConnection;
LogSequenceNumber startLSN = getCurrentLSN();
Statement st = sqlConnection.createStatement();
st.execute("insert into test_logic_table(name) values('previous changes')");
st.close();
PGReplicationStream stream =
pgConnection
.getReplicationAPI()
.replicationStream()
.logical()
.withSlotName(SLOT_NAME)
.withStartPosition(startLSN)
.start();
receiveMessageWithoutBlock(stream, 1);
final LogSequenceNumber applyLSN = stream.getLastReceiveLSN();
stream.setAppliedLSN(applyLSN);
stream.setFlushedLSN(applyLSN);
receiveMessageWithoutBlock(stream, 2);
stream.forceUpdateStatus();
LogSequenceNumber result = getReplayLocationOnView();
assertThat(
"During receive message from replication stream all feedback parameter "
+ "that we set to stream should be sent to backend"
+ "because it allow monitoring replication status and also recycle old WALs",
result, equalTo(applyLSN)
);
}
/**
* Test fail on PG version 9.4.5 because postgresql have bug
*/
@Test
@HaveMinimalServerVersion("9.4.8")
public void testApplyLocationDoNotDependOnFlushLocation() throws Exception {
PGConnection pgConnection = (PGConnection) replicationConnection;
LogSequenceNumber startLSN = getCurrentLSN();
Statement st = sqlConnection.createStatement();
st.execute("insert into test_logic_table(name) values('previous changes')");
st.close();
PGReplicationStream stream =
pgConnection
.getReplicationAPI()
.replicationStream()
.logical()
.withSlotName(SLOT_NAME)
.withStartPosition(startLSN)
.start();
receiveMessageWithoutBlock(stream, 1);
stream.setAppliedLSN(stream.getLastReceiveLSN());
stream.setFlushedLSN(stream.getLastReceiveLSN());
receiveMessageWithoutBlock(stream, 1);
stream.setFlushedLSN(stream.getLastReceiveLSN());
receiveMessageWithoutBlock(stream, 1);
stream.forceUpdateStatus();
LogSequenceNumber flushed = getFlushLocationOnView();
LogSequenceNumber applied = getReplayLocationOnView();
assertThat(
"Last applied LSN and last flushed LSN it two not depends parameters and they can be not equal between",
applied, not(equalTo(flushed))
);
}
@Test
public void testApplyLocationDoNotChangeDuringReceiveMessage() throws Exception {
PGConnection pgConnection = (PGConnection) replicationConnection;
LogSequenceNumber startLSN = getCurrentLSN();
Statement st = sqlConnection.createStatement();
st.execute("insert into test_logic_table(name) values('previous changes')");
st.close();
PGReplicationStream stream =
pgConnection
.getReplicationAPI()
.replicationStream()
.logical()
.withSlotName(SLOT_NAME)
.withStartPosition(startLSN)
.start();
receiveMessageWithoutBlock(stream, 1);
final LogSequenceNumber applyLSN = stream.getLastReceiveLSN();
stream.setAppliedLSN(applyLSN);
receiveMessageWithoutBlock(stream, 2);
assertThat(
"Apply LSN it parameter that specify manually on stream and they can not automatically "
+ "change during receive another messages, "
+ "because auto update can lead to problem when WAL recycled on postgres "
+ "because we send feedback that current position successfully flush, but in real they not flush yet",
stream.getLastAppliedLSN(), equalTo(applyLSN)
);
}
@Test
public void testStatusCanBeSentToBackendAsynchronously() throws Exception {
PGConnection pgConnection = (PGConnection) replicationConnection;
final int intervalTime = 100;
final TimeUnit timeFormat = TimeUnit.MILLISECONDS;
LogSequenceNumber startLSN = getCurrentLSN();
Statement st = sqlConnection.createStatement();
st.execute("insert into test_logic_table(name) values('previous changes')");
st.close();
PGReplicationStream stream =
pgConnection
.getReplicationAPI()
.replicationStream()
.logical()
.withSlotName(SLOT_NAME)
.withStartPosition(startLSN)
.withStatusInterval(intervalTime, timeFormat)
.start();
receiveMessageWithoutBlock(stream, 3);
LogSequenceNumber waitLSN = stream.getLastReceiveLSN();
stream.setAppliedLSN(waitLSN);
stream.setFlushedLSN(waitLSN);
timeFormat.sleep(intervalTime + 1);
//get pending message and trigger update status by timeout
stream.readPending();
LogSequenceNumber flushLSN = getFlushLocationOnView();
assertThat("Status can be sent to backend by some time interval, "
+ "by default it parameter equals to 10 second, but in current test we change it on few millisecond "
+ "and wait that set status on stream will be auto send to backend",
flushLSN, equalTo(waitLSN)
);
}
private LogSequenceNumber getSentLocationOnView() throws Exception {
return getLSNFromView("sent_location");
}
private LogSequenceNumber getWriteLocationOnView() throws Exception {
return getLSNFromView("write_location");
}
private LogSequenceNumber getFlushLocationOnView() throws Exception {
return getLSNFromView("flush_location");
}
private LogSequenceNumber getReplayLocationOnView() throws Exception {
return getLSNFromView("replay_location");
}
private List<String> receiveMessageWithoutBlock(PGReplicationStream stream, int count)
throws Exception {
List<String> result = new ArrayList<String>(3);
for (int index = 0; index < count; index++) {
ByteBuffer message;
do {
message = stream.readPending();
if (message == null) {
TimeUnit.MILLISECONDS.sleep(2);
}
} while (message == null);
result.add(toString(message));
}
return result;
}
private String toString(ByteBuffer buffer) {
int offset = buffer.arrayOffset();
byte[] source = buffer.array();
int length = source.length - offset;
return new String(source, offset, length);
}
private LogSequenceNumber getLSNFromView(String columnName) throws Exception {
int pid = ((PGConnection) replicationConnection).getBackendPID();
int repeatCount = 0;
while (true) {
Statement st = sqlConnection.createStatement();
ResultSet rs = null;
try {
rs = st.executeQuery("select * from pg_stat_replication where pid = " + pid);
String result = null;
if (rs.next()) {
result = rs.getString(columnName);
}
if (result == null || result.isEmpty()) {
//replication monitoring view updates with some delay, wait some time and try again
TimeUnit.MILLISECONDS.sleep(100L);
repeatCount++;
if (repeatCount == 10) {
return null;
}
} else {
return LogSequenceNumber.valueOf(result);
}
} finally {
if (rs != null) {
rs.close();
}
st.close();
}
}
}
private LogSequenceNumber getCurrentLSN() throws SQLException {
Statement st = sqlConnection.createStatement();
ResultSet rs = null;
try {
rs = st.executeQuery("select "
+ (((BaseConnection) sqlConnection).haveMinimumServerVersion(ServerVersion.v10)
? "pg_current_wal_location()" : "pg_current_xlog_location()"));
if (rs.next()) {
String lsn = rs.getString(1);
return LogSequenceNumber.valueOf(lsn);
} else {
return LogSequenceNumber.INVALID_LSN;
}
} finally {
if (rs != null) {
rs.close();
}
st.close();
}
}
private Connection openReplicationConnection() throws Exception {
Properties properties = new Properties();
PGProperty.ASSUME_MIN_SERVER_VERSION.set(properties, "9.4");
PGProperty.REPLICATION.set(properties, "database");
return TestUtil.openDB(properties);
}
}