File size: 80,641 Bytes
5a9e79d | 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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 | diff --git a/flink/v1.19/flink/src/main/java/org/apache/iceberg/flink/sink/FlinkManifestUtil.java b/flink/v1.19/flink/src/main/java/org/apache/iceberg/flink/sink/FlinkManifestUtil.java
index c7e8a2dea7cb..9571efdc5268 100644
--- a/flink/v1.19/flink/src/main/java/org/apache/iceberg/flink/sink/FlinkManifestUtil.java
+++ b/flink/v1.19/flink/src/main/java/org/apache/iceberg/flink/sink/FlinkManifestUtil.java
@@ -33,9 +33,14 @@
import org.apache.iceberg.io.FileIO;
import org.apache.iceberg.io.OutputFile;
import org.apache.iceberg.io.WriteResult;
+import org.apache.iceberg.relocated.com.google.common.base.MoreObjects;
import org.apache.iceberg.relocated.com.google.common.collect.Lists;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
class FlinkManifestUtil {
+
+ private static final Logger LOG = LoggerFactory.getLogger(FlinkManifestUtil.class);
private static final int FORMAT_V2 = 2;
private static final Long DUMMY_SNAPSHOT_ID = 0L;
@@ -129,4 +134,26 @@ static WriteResult readCompletedFiles(
return builder.addReferencedDataFiles(deltaManifests.referencedDataFiles()).build();
}
+
+ static void deleteCommittedManifests(
+ Table table, List<ManifestFile> manifests, String newFlinkJobId, long checkpointId) {
+ for (ManifestFile manifest : manifests) {
+ try {
+ table.io().deleteFile(manifest.path());
+ } catch (Exception e) {
+ // The flink manifests cleaning failure shouldn't abort the completed checkpoint.
+ String details =
+ MoreObjects.toStringHelper(FlinkManifestUtil.class)
+ .add("tableName", table.name())
+ .add("flinkJobId", newFlinkJobId)
+ .add("checkpointId", checkpointId)
+ .add("manifestPath", manifest.path())
+ .toString();
+ LOG.warn(
+ "The iceberg transaction has been committed, but we failed to clean the temporary flink manifests: {}",
+ details,
+ e);
+ }
+ }
+ }
}
diff --git a/flink/v1.19/flink/src/main/java/org/apache/iceberg/flink/sink/FlinkSink.java b/flink/v1.19/flink/src/main/java/org/apache/iceberg/flink/sink/FlinkSink.java
index 2256d1e874ce..be2a8db03097 100644
--- a/flink/v1.19/flink/src/main/java/org/apache/iceberg/flink/sink/FlinkSink.java
+++ b/flink/v1.19/flink/src/main/java/org/apache/iceberg/flink/sink/FlinkSink.java
@@ -406,7 +406,8 @@ private <T> DataStreamSink<T> chainIcebergOperators() {
flinkWriteConf = new FlinkWriteConf(table, writeOptions, readableConfig);
// Find out the equality field id list based on the user-provided equality field column names.
- List<Integer> equalityFieldIds = checkAndGetEqualityFieldIds();
+ List<Integer> equalityFieldIds =
+ SinkUtil.checkAndGetEqualityFieldIds(table, equalityFieldColumns);
RowType flinkRowType = toFlinkRowType(table.schema(), tableSchema);
int writerParallelism =
diff --git a/flink/v1.19/flink/src/main/java/org/apache/iceberg/flink/sink/IcebergCommittable.java b/flink/v1.19/flink/src/main/java/org/apache/iceberg/flink/sink/IcebergCommittable.java
new file mode 100644
index 000000000000..408c3e9a9d5f
--- /dev/null
+++ b/flink/v1.19/flink/src/main/java/org/apache/iceberg/flink/sink/IcebergCommittable.java
@@ -0,0 +1,95 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.iceberg.flink.sink;
+
+import java.io.Serializable;
+import java.util.Arrays;
+import java.util.Objects;
+import org.apache.iceberg.relocated.com.google.common.base.MoreObjects;
+
+/**
+ * The aggregated results of a single checkpoint which should be committed. Containing the
+ * serialized {@link org.apache.iceberg.flink.sink.DeltaManifests} file - which contains the commit
+ * data, and the jobId, operatorId, checkpointId triplet which helps identifying the specific commit
+ *
+ * <p>{@link IcebergCommittableSerializer} is used for serializing the objects between the Writer
+ * and the Aggregator operator and between the Aggregator and the Committer as well.
+ */
+class IcebergCommittable implements Serializable {
+ private final byte[] manifest;
+ private final String jobId;
+ private final String operatorId;
+ private final long checkpointId;
+
+ IcebergCommittable(byte[] manifest, String jobId, String operatorId, long checkpointId) {
+ this.manifest = manifest;
+ this.jobId = jobId;
+ this.operatorId = operatorId;
+ this.checkpointId = checkpointId;
+ }
+
+ byte[] manifest() {
+ return manifest;
+ }
+
+ String jobId() {
+ return jobId;
+ }
+
+ String operatorId() {
+ return operatorId;
+ }
+
+ Long checkpointId() {
+ return checkpointId;
+ }
+
+ @Override
+ public String toString() {
+ return MoreObjects.toStringHelper(this)
+ .add("jobId", jobId)
+ .add("checkpointId", checkpointId)
+ .add("operatorId", operatorId)
+ .toString();
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) {
+ return true;
+ }
+
+ if (o == null || getClass() != o.getClass()) {
+ return false;
+ }
+
+ IcebergCommittable that = (IcebergCommittable) o;
+ return checkpointId == that.checkpointId
+ && Arrays.equals(manifest, that.manifest)
+ && Objects.equals(jobId, that.jobId)
+ && Objects.equals(operatorId, that.operatorId);
+ }
+
+ @Override
+ public int hashCode() {
+ int result = Objects.hash(jobId, operatorId, checkpointId);
+ result = 31 * result + Arrays.hashCode(manifest);
+ return result;
+ }
+}
diff --git a/flink/v1.19/flink/src/main/java/org/apache/iceberg/flink/sink/IcebergCommittableSerializer.java b/flink/v1.19/flink/src/main/java/org/apache/iceberg/flink/sink/IcebergCommittableSerializer.java
new file mode 100644
index 000000000000..e2b388a83c75
--- /dev/null
+++ b/flink/v1.19/flink/src/main/java/org/apache/iceberg/flink/sink/IcebergCommittableSerializer.java
@@ -0,0 +1,68 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.iceberg.flink.sink;
+
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import org.apache.flink.core.io.SimpleVersionedSerializer;
+import org.apache.flink.core.memory.DataInputDeserializer;
+import org.apache.flink.core.memory.DataOutputViewStreamWrapper;
+
+/**
+ * This serializer is used for serializing the {@link IcebergCommittable} objects between the Writer
+ * and the Aggregator operator and between the Aggregator and the Committer as well.
+ *
+ * <p>In both cases only the respective part is serialized.
+ */
+class IcebergCommittableSerializer implements SimpleVersionedSerializer<IcebergCommittable> {
+ private static final int VERSION = 1;
+
+ @Override
+ public int getVersion() {
+ return VERSION;
+ }
+
+ @Override
+ public byte[] serialize(IcebergCommittable committable) throws IOException {
+ ByteArrayOutputStream out = new ByteArrayOutputStream();
+ DataOutputViewStreamWrapper view = new DataOutputViewStreamWrapper(out);
+ view.writeUTF(committable.jobId());
+ view.writeUTF(committable.operatorId());
+ view.writeLong(committable.checkpointId());
+ view.writeInt(committable.manifest().length);
+ view.write(committable.manifest());
+ return out.toByteArray();
+ }
+
+ @Override
+ public IcebergCommittable deserialize(int version, byte[] serialized) throws IOException {
+ if (version == 1) {
+ DataInputDeserializer view = new DataInputDeserializer(serialized);
+ String jobId = view.readUTF();
+ String operatorId = view.readUTF();
+ long checkpointId = view.readLong();
+ int manifestLen = view.readInt();
+ byte[] manifestBuf;
+ manifestBuf = new byte[manifestLen];
+ view.read(manifestBuf);
+ return new IcebergCommittable(manifestBuf, jobId, operatorId, checkpointId);
+ }
+ throw new IOException("Unrecognized version or corrupt state: " + version);
+ }
+}
diff --git a/flink/v1.19/flink/src/main/java/org/apache/iceberg/flink/sink/IcebergCommitter.java b/flink/v1.19/flink/src/main/java/org/apache/iceberg/flink/sink/IcebergCommitter.java
new file mode 100644
index 000000000000..2245b36f15a7
--- /dev/null
+++ b/flink/v1.19/flink/src/main/java/org/apache/iceberg/flink/sink/IcebergCommitter.java
@@ -0,0 +1,311 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.iceberg.flink.sink;
+
+import java.io.IOException;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.List;
+import java.util.Map;
+import java.util.NavigableMap;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.TimeUnit;
+import org.apache.flink.api.connector.sink2.Committer;
+import org.apache.flink.core.io.SimpleVersionedSerialization;
+import org.apache.iceberg.AppendFiles;
+import org.apache.iceberg.ManifestFile;
+import org.apache.iceberg.ReplacePartitions;
+import org.apache.iceberg.RowDelta;
+import org.apache.iceberg.SnapshotUpdate;
+import org.apache.iceberg.Table;
+import org.apache.iceberg.flink.TableLoader;
+import org.apache.iceberg.io.WriteResult;
+import org.apache.iceberg.relocated.com.google.common.annotations.VisibleForTesting;
+import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
+import org.apache.iceberg.relocated.com.google.common.collect.Lists;
+import org.apache.iceberg.relocated.com.google.common.collect.Maps;
+import org.apache.iceberg.util.PropertyUtil;
+import org.apache.iceberg.util.ThreadPools;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * This class implements the Flink SinkV2 {@link Committer} interface to implement the Iceberg
+ * commits. The implementation builds on the following assumptions:
+ *
+ * <ul>
+ * <li>There is a single {@link IcebergCommittable} for every checkpoint
+ * <li>There is no late checkpoint - if checkpoint 'x' has received in one call, then after a
+ * successful run only checkpoints > x will arrive
+ * <li>There is no other writer which would generate another commit to the same branch with the
+ * same jobId-operatorId-checkpointId triplet
+ * </ul>
+ */
+class IcebergCommitter implements Committer<IcebergCommittable> {
+ private static final Logger LOG = LoggerFactory.getLogger(IcebergCommitter.class);
+ private static final byte[] EMPTY_MANIFEST_DATA = new byte[0];
+ public static final WriteResult EMPTY_WRITE_RESULT =
+ WriteResult.builder()
+ .addDataFiles(Lists.newArrayList())
+ .addDeleteFiles(Lists.newArrayList())
+ .build();
+
+ @VisibleForTesting
+ static final String MAX_CONTINUOUS_EMPTY_COMMITS = "flink.max-continuous-empty-commits";
+
+ private final String branch;
+ private final Map<String, String> snapshotProperties;
+ private final boolean replacePartitions;
+ private IcebergFilesCommitterMetrics committerMetrics;
+ private Table table;
+ private final TableLoader tableLoader;
+ private int maxContinuousEmptyCommits;
+ private ExecutorService workerPool;
+ private int continuousEmptyCheckpoints = 0;
+
+ IcebergCommitter(
+ TableLoader tableLoader,
+ String branch,
+ Map<String, String> snapshotProperties,
+ boolean replacePartitions,
+ int workerPoolSize,
+ String sinkId,
+ IcebergFilesCommitterMetrics committerMetrics) {
+ this.branch = branch;
+ this.snapshotProperties = snapshotProperties;
+ this.replacePartitions = replacePartitions;
+ this.committerMetrics = committerMetrics;
+ this.tableLoader = tableLoader;
+ if (!tableLoader.isOpen()) {
+ tableLoader.open();
+ }
+
+ this.table = tableLoader.loadTable();
+ this.maxContinuousEmptyCommits =
+ PropertyUtil.propertyAsInt(table.properties(), MAX_CONTINUOUS_EMPTY_COMMITS, 10);
+ Preconditions.checkArgument(
+ maxContinuousEmptyCommits > 0, MAX_CONTINUOUS_EMPTY_COMMITS + " must be positive");
+ this.workerPool =
+ ThreadPools.newWorkerPool(
+ "iceberg-committer-pool-" + table.name() + "-" + sinkId, workerPoolSize);
+ this.continuousEmptyCheckpoints = 0;
+ }
+
+ @Override
+ public void commit(Collection<CommitRequest<IcebergCommittable>> commitRequests)
+ throws IOException, InterruptedException {
+ if (commitRequests.isEmpty()) {
+ return;
+ }
+
+ NavigableMap<Long, CommitRequest<IcebergCommittable>> commitRequestMap = Maps.newTreeMap();
+ for (CommitRequest<IcebergCommittable> request : commitRequests) {
+ commitRequestMap.put(request.getCommittable().checkpointId(), request);
+ }
+
+ IcebergCommittable last = commitRequestMap.lastEntry().getValue().getCommittable();
+ long maxCommittedCheckpointId =
+ SinkUtil.getMaxCommittedCheckpointId(table, last.jobId(), last.operatorId(), branch);
+ // Mark the already committed FilesCommittable(s) as finished
+ commitRequestMap
+ .headMap(maxCommittedCheckpointId, true)
+ .values()
+ .forEach(CommitRequest::signalAlreadyCommitted);
+ NavigableMap<Long, CommitRequest<IcebergCommittable>> uncommitted =
+ commitRequestMap.tailMap(maxCommittedCheckpointId, false);
+ if (!uncommitted.isEmpty()) {
+ commitPendingRequests(uncommitted, last.jobId(), last.operatorId());
+ }
+ }
+
+ /**
+ * Commits the data to the Iceberg table by reading the file data from the {@link
+ * org.apache.iceberg.flink.sink.DeltaManifests} ordered by the checkpointId, and writing the new
+ * snapshot to the Iceberg table. The {@link org.apache.iceberg.SnapshotSummary} will contain the
+ * jobId, snapshotId, checkpointId so in case of job restart we can identify which changes are
+ * committed, and which are still waiting for the commit.
+ *
+ * @param commitRequestMap The checkpointId to {@link CommitRequest} map of the changes to commit
+ * @param newFlinkJobId The jobId to store in the {@link org.apache.iceberg.SnapshotSummary}
+ * @param operatorId The operatorId to store in the {@link org.apache.iceberg.SnapshotSummary}
+ * @throws IOException On commit failure
+ */
+ private void commitPendingRequests(
+ NavigableMap<Long, CommitRequest<IcebergCommittable>> commitRequestMap,
+ String newFlinkJobId,
+ String operatorId)
+ throws IOException {
+ long checkpointId = commitRequestMap.lastKey();
+ List<ManifestFile> manifests = Lists.newArrayList();
+ NavigableMap<Long, WriteResult> pendingResults = Maps.newTreeMap();
+ for (Map.Entry<Long, CommitRequest<IcebergCommittable>> e : commitRequestMap.entrySet()) {
+ if (Arrays.equals(EMPTY_MANIFEST_DATA, e.getValue().getCommittable().manifest())) {
+ pendingResults.put(e.getKey(), EMPTY_WRITE_RESULT);
+ } else {
+ DeltaManifests deltaManifests =
+ SimpleVersionedSerialization.readVersionAndDeSerialize(
+ DeltaManifestsSerializer.INSTANCE, e.getValue().getCommittable().manifest());
+ pendingResults.put(
+ e.getKey(),
+ FlinkManifestUtil.readCompletedFiles(deltaManifests, table.io(), table.specs()));
+ manifests.addAll(deltaManifests.manifests());
+ }
+ }
+
+ CommitSummary summary = new CommitSummary(pendingResults);
+ commitPendingResult(pendingResults, summary, newFlinkJobId, operatorId);
+ if (committerMetrics != null) {
+ committerMetrics.updateCommitSummary(summary);
+ }
+
+ FlinkManifestUtil.deleteCommittedManifests(table, manifests, newFlinkJobId, checkpointId);
+ }
+
+ private void logCommitSummary(CommitSummary summary, String description) {
+ LOG.info(
+ "Preparing for commit: {} on table: {} branch: {} with summary: {}.",
+ description,
+ table,
+ branch,
+ summary);
+ }
+
+ private void commitPendingResult(
+ NavigableMap<Long, WriteResult> pendingResults,
+ CommitSummary summary,
+ String newFlinkJobId,
+ String operatorId) {
+ long totalFiles = summary.dataFilesCount() + summary.deleteFilesCount();
+ continuousEmptyCheckpoints = totalFiles == 0 ? continuousEmptyCheckpoints + 1 : 0;
+ if (totalFiles != 0 || continuousEmptyCheckpoints % maxContinuousEmptyCommits == 0) {
+ if (replacePartitions) {
+ replacePartitions(pendingResults, summary, newFlinkJobId, operatorId);
+ } else {
+ commitDeltaTxn(pendingResults, summary, newFlinkJobId, operatorId);
+ }
+ continuousEmptyCheckpoints = 0;
+ } else {
+ long checkpointId = pendingResults.lastKey();
+ LOG.info("Skip commit for checkpoint {} due to no data files or delete files.", checkpointId);
+ }
+ }
+
+ private void replacePartitions(
+ NavigableMap<Long, WriteResult> pendingResults,
+ CommitSummary summary,
+ String newFlinkJobId,
+ String operatorId) {
+ long checkpointId = pendingResults.lastKey();
+ Preconditions.checkState(
+ summary.deleteFilesCount() == 0, "Cannot overwrite partitions with delete files.");
+ // Commit the overwrite transaction.
+ ReplacePartitions dynamicOverwrite = table.newReplacePartitions().scanManifestsWith(workerPool);
+ for (WriteResult result : pendingResults.values()) {
+ Preconditions.checkState(
+ result.referencedDataFiles().length == 0, "Should have no referenced data files.");
+ Arrays.stream(result.dataFiles()).forEach(dynamicOverwrite::addFile);
+ }
+ String description = "dynamic partition overwrite";
+
+ logCommitSummary(summary, description);
+ commitOperation(dynamicOverwrite, description, newFlinkJobId, operatorId, checkpointId);
+ }
+
+ private void commitDeltaTxn(
+ NavigableMap<Long, WriteResult> pendingResults,
+ CommitSummary summary,
+ String newFlinkJobId,
+ String operatorId) {
+ long checkpointId = pendingResults.lastKey();
+ if (summary.deleteFilesCount() == 0) {
+ // To be compatible with iceberg format V1.
+ AppendFiles appendFiles = table.newAppend().scanManifestsWith(workerPool);
+ for (WriteResult result : pendingResults.values()) {
+ Preconditions.checkState(
+ result.referencedDataFiles().length == 0,
+ "Should have no referenced data files for append.");
+ Arrays.stream(result.dataFiles()).forEach(appendFiles::appendFile);
+ }
+ String description = "append";
+ logCommitSummary(summary, description);
+ // fail all commits as really its only one
+ commitOperation(appendFiles, description, newFlinkJobId, operatorId, checkpointId);
+ } else {
+ // To be compatible with iceberg format V2.
+ for (Map.Entry<Long, WriteResult> e : pendingResults.entrySet()) {
+ // We don't commit the merged result into a single transaction because for the sequential
+ // transaction txn1 and txn2, the equality-delete files of txn2 are required to be applied
+ // to data files from txn1. Committing the merged one will lead to the incorrect delete
+ // semantic.
+ WriteResult result = e.getValue();
+
+ // Row delta validations are not needed for streaming changes that write equality deletes.
+ // Equality deletes are applied to data in all previous sequence numbers, so retries may
+ // push deletes further in the future, but do not affect correctness. Position deletes
+ // committed to the table in this path are used only to delete rows from data files that are
+ // being added in this commit. There is no way for data files added along with the delete
+ // files to be concurrently removed, so there is no need to validate the files referenced by
+ // the position delete files that are being committed.
+ RowDelta rowDelta = table.newRowDelta().scanManifestsWith(workerPool);
+
+ Arrays.stream(result.dataFiles()).forEach(rowDelta::addRows);
+ Arrays.stream(result.deleteFiles()).forEach(rowDelta::addDeletes);
+
+ String description = "rowDelta";
+ logCommitSummary(summary, description);
+ commitOperation(rowDelta, description, newFlinkJobId, operatorId, e.getKey());
+ }
+ }
+ }
+
+ private void commitOperation(
+ SnapshotUpdate<?> operation,
+ String description,
+ String newFlinkJobId,
+ String operatorId,
+ long checkpointId) {
+
+ snapshotProperties.forEach(operation::set);
+ // custom snapshot metadata properties will be overridden if they conflict with internal ones
+ // used by the sink.
+ operation.set(SinkUtil.MAX_COMMITTED_CHECKPOINT_ID, Long.toString(checkpointId));
+ operation.set(SinkUtil.FLINK_JOB_ID, newFlinkJobId);
+ operation.set(SinkUtil.OPERATOR_ID, operatorId);
+ operation.toBranch(branch);
+
+ long startNano = System.nanoTime();
+ operation.commit(); // abort is automatically called if this fails.
+ long durationMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNano);
+ LOG.info(
+ "Committed {} to table: {}, branch: {}, checkpointId {} in {} ms",
+ description,
+ table.name(),
+ branch,
+ checkpointId,
+ durationMs);
+ if (committerMetrics != null) {
+ committerMetrics.commitDuration(durationMs);
+ }
+ }
+
+ @Override
+ public void close() throws IOException {
+ tableLoader.close();
+ }
+}
diff --git a/flink/v1.19/flink/src/main/java/org/apache/iceberg/flink/sink/IcebergFilesCommitter.java b/flink/v1.19/flink/src/main/java/org/apache/iceberg/flink/sink/IcebergFilesCommitter.java
index b9bceaa9311d..622daa808897 100644
--- a/flink/v1.19/flink/src/main/java/org/apache/iceberg/flink/sink/IcebergFilesCommitter.java
+++ b/flink/v1.19/flink/src/main/java/org/apache/iceberg/flink/sink/IcebergFilesCommitter.java
@@ -44,13 +44,11 @@
import org.apache.iceberg.PartitionSpec;
import org.apache.iceberg.ReplacePartitions;
import org.apache.iceberg.RowDelta;
-import org.apache.iceberg.Snapshot;
import org.apache.iceberg.SnapshotUpdate;
import org.apache.iceberg.Table;
import org.apache.iceberg.flink.TableLoader;
import org.apache.iceberg.io.WriteResult;
import org.apache.iceberg.relocated.com.google.common.annotations.VisibleForTesting;
-import org.apache.iceberg.relocated.com.google.common.base.MoreObjects;
import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
import org.apache.iceberg.relocated.com.google.common.base.Strings;
import org.apache.iceberg.relocated.com.google.common.collect.Lists;
@@ -187,7 +185,7 @@ public void initializeState(StateInitializationContext context) throws Exception
// it's safe to assign the max committed checkpoint id from restored flink job to the current
// flink job.
this.maxCommittedCheckpointId =
- getMaxCommittedCheckpointId(table, restoredFlinkJobId, operatorUniqueId, branch);
+ SinkUtil.getMaxCommittedCheckpointId(table, restoredFlinkJobId, operatorUniqueId, branch);
NavigableMap<Long, byte[]> uncommittedDataFiles =
Maps.newTreeMap(checkpointsState.get().iterator().next())
@@ -280,7 +278,7 @@ private void commitUpToCheckpoint(
commitPendingResult(pendingResults, summary, newFlinkJobId, operatorId, checkpointId);
committerMetrics.updateCommitSummary(summary);
pendingMap.clear();
- deleteCommittedManifests(manifests, newFlinkJobId, checkpointId);
+ FlinkManifestUtil.deleteCommittedManifests(table, manifests, newFlinkJobId, checkpointId);
}
private void commitPendingResult(
@@ -303,27 +301,6 @@ private void commitPendingResult(
}
}
- private void deleteCommittedManifests(
- List<ManifestFile> manifests, String newFlinkJobId, long checkpointId) {
- for (ManifestFile manifest : manifests) {
- try {
- table.io().deleteFile(manifest.path());
- } catch (Exception e) {
- // The flink manifests cleaning failure shouldn't abort the completed checkpoint.
- String details =
- MoreObjects.toStringHelper(this)
- .add("flinkJobId", newFlinkJobId)
- .add("checkpointId", checkpointId)
- .add("manifestPath", manifest.path())
- .toString();
- LOG.warn(
- "The iceberg transaction has been committed, but we failed to clean the temporary flink manifests: {}",
- details,
- e);
- }
- }
- }
-
private void replacePartitions(
NavigableMap<Long, WriteResult> pendingResults,
CommitSummary summary,
@@ -489,28 +466,4 @@ static ListStateDescriptor<SortedMap<Long, byte[]>> buildStateDescriptor() {
longComparator);
return new ListStateDescriptor<>("iceberg-files-committer-state", sortedMapTypeInfo);
}
-
- static long getMaxCommittedCheckpointId(
- Table table, String flinkJobId, String operatorId, String branch) {
- Snapshot snapshot = table.snapshot(branch);
- long lastCommittedCheckpointId = INITIAL_CHECKPOINT_ID;
-
- while (snapshot != null) {
- Map<String, String> summary = snapshot.summary();
- String snapshotFlinkJobId = summary.get(FLINK_JOB_ID);
- String snapshotOperatorId = summary.get(OPERATOR_ID);
- if (flinkJobId.equals(snapshotFlinkJobId)
- && (snapshotOperatorId == null || snapshotOperatorId.equals(operatorId))) {
- String value = summary.get(MAX_COMMITTED_CHECKPOINT_ID);
- if (value != null) {
- lastCommittedCheckpointId = Long.parseLong(value);
- break;
- }
- }
- Long parentSnapshotId = snapshot.parentId();
- snapshot = parentSnapshotId != null ? table.snapshot(parentSnapshotId) : null;
- }
-
- return lastCommittedCheckpointId;
- }
}
diff --git a/flink/v1.19/flink/src/main/java/org/apache/iceberg/flink/sink/IcebergSink.java b/flink/v1.19/flink/src/main/java/org/apache/iceberg/flink/sink/IcebergSink.java
new file mode 100644
index 000000000000..d080169544cd
--- /dev/null
+++ b/flink/v1.19/flink/src/main/java/org/apache/iceberg/flink/sink/IcebergSink.java
@@ -0,0 +1,742 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.iceberg.flink.sink;
+
+import static org.apache.iceberg.TableProperties.AVRO_COMPRESSION;
+import static org.apache.iceberg.TableProperties.AVRO_COMPRESSION_LEVEL;
+import static org.apache.iceberg.TableProperties.ORC_COMPRESSION;
+import static org.apache.iceberg.TableProperties.ORC_COMPRESSION_STRATEGY;
+import static org.apache.iceberg.TableProperties.PARQUET_COMPRESSION;
+import static org.apache.iceberg.TableProperties.PARQUET_COMPRESSION_LEVEL;
+import static org.apache.iceberg.TableProperties.WRITE_DISTRIBUTION_MODE;
+
+import java.io.IOException;
+import java.io.UncheckedIOException;
+import java.time.Duration;
+import java.util.List;
+import java.util.Map;
+import java.util.UUID;
+import java.util.function.Function;
+import org.apache.flink.annotation.Experimental;
+import org.apache.flink.api.common.functions.MapFunction;
+import org.apache.flink.api.common.typeinfo.TypeInformation;
+import org.apache.flink.api.connector.sink2.Committer;
+import org.apache.flink.api.connector.sink2.CommitterInitContext;
+import org.apache.flink.api.connector.sink2.Sink;
+import org.apache.flink.api.connector.sink2.SinkWriter;
+import org.apache.flink.api.connector.sink2.SupportsCommitter;
+import org.apache.flink.configuration.Configuration;
+import org.apache.flink.configuration.ReadableConfig;
+import org.apache.flink.core.io.SimpleVersionedSerializer;
+import org.apache.flink.streaming.api.connector.sink2.CommittableMessage;
+import org.apache.flink.streaming.api.connector.sink2.CommittableMessageTypeInfo;
+import org.apache.flink.streaming.api.connector.sink2.SupportsPostCommitTopology;
+import org.apache.flink.streaming.api.connector.sink2.SupportsPreCommitTopology;
+import org.apache.flink.streaming.api.connector.sink2.SupportsPreWriteTopology;
+import org.apache.flink.streaming.api.datastream.DataStream;
+import org.apache.flink.streaming.api.datastream.DataStreamSink;
+import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
+import org.apache.flink.table.api.TableSchema;
+import org.apache.flink.table.data.RowData;
+import org.apache.flink.table.data.util.DataFormatConverters;
+import org.apache.flink.table.types.DataType;
+import org.apache.flink.table.types.logical.RowType;
+import org.apache.flink.types.Row;
+import org.apache.flink.util.Preconditions;
+import org.apache.iceberg.DataFile;
+import org.apache.iceberg.DistributionMode;
+import org.apache.iceberg.FileFormat;
+import org.apache.iceberg.PartitionField;
+import org.apache.iceberg.PartitionSpec;
+import org.apache.iceberg.Schema;
+import org.apache.iceberg.SerializableTable;
+import org.apache.iceberg.Table;
+import org.apache.iceberg.flink.FlinkSchemaUtil;
+import org.apache.iceberg.flink.FlinkWriteConf;
+import org.apache.iceberg.flink.FlinkWriteOptions;
+import org.apache.iceberg.flink.TableLoader;
+import org.apache.iceberg.flink.util.FlinkCompatibilityUtil;
+import org.apache.iceberg.io.WriteResult;
+import org.apache.iceberg.relocated.com.google.common.collect.Maps;
+import org.apache.iceberg.types.TypeUtil;
+import org.apache.iceberg.util.SerializableSupplier;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Flink v2 sink offer different hooks to insert custom topologies into the sink. We will use the
+ * following:
+ *
+ * <ul>
+ * <li>{@link SupportsPreWriteTopology} which redistributes the data to the writers based on the
+ * {@link DistributionMode}
+ * <li>{@link org.apache.flink.api.connector.sink2.SinkWriter} which writes data/delete files, and
+ * generates the {@link org.apache.iceberg.io.WriteResult} objects for the files
+ * <li>{@link SupportsPreCommitTopology} which we use to place the {@link
+ * org.apache.iceberg.flink.sink.IcebergWriteAggregator} which merges the individual {@link
+ * org.apache.flink.api.connector.sink2.SinkWriter}'s {@link
+ * org.apache.iceberg.io.WriteResult}s to a single {@link
+ * org.apache.iceberg.flink.sink.IcebergCommittable}
+ * <li>{@link org.apache.iceberg.flink.sink.IcebergCommitter} which commits the incoming{@link
+ * org.apache.iceberg.flink.sink.IcebergCommittable}s to the Iceberg table
+ * <li>{@link SupportsPostCommitTopology} we could use for incremental compaction later. This is
+ * not implemented yet.
+ * </ul>
+ *
+ * The job graph looks like below:
+ *
+ * <pre>{@code
+ * Flink sink
+ * +-----------------------------------------------------------------------------------+
+ * | |
+ * +-------+ | +----------+ +-------------+ +---------------+ |
+ * | Map 1 | ==> | | writer 1 | | committer 1 | ---> | post commit 1 | |
+ * +-------+ | +----------+ +-------------+ +---------------+ |
+ * | \ / \ |
+ * | \ / \ |
+ * | \ / \ |
+ * +-------+ | +----------+ \ +-------------------+ / +-------------+ \ +---------------+ |
+ * | Map 2 | ==> | | writer 2 | --->| commit aggregator | | committer 2 | | post commit 2 | |
+ * +-------+ | +----------+ +-------------------+ +-------------+ +---------------+ |
+ * | Commit only on |
+ * | committer 1 |
+ * +-----------------------------------------------------------------------------------+
+ * }</pre>
+ */
+@Experimental
+public class IcebergSink
+ implements Sink<RowData>,
+ SupportsPreWriteTopology<RowData>,
+ SupportsCommitter<IcebergCommittable>,
+ SupportsPreCommitTopology<WriteResult, IcebergCommittable>,
+ SupportsPostCommitTopology<IcebergCommittable> {
+ private static final Logger LOG = LoggerFactory.getLogger(IcebergSink.class);
+ private final TableLoader tableLoader;
+ private final Map<String, String> snapshotProperties;
+ private final String uidSuffix;
+ private final String sinkId;
+ private final Map<String, String> writeProperties;
+ private final RowType flinkRowType;
+ private final SerializableSupplier<Table> tableSupplier;
+ private final transient FlinkWriteConf flinkWriteConf;
+ private final List<Integer> equalityFieldIds;
+ private final boolean upsertMode;
+ private final FileFormat dataFileFormat;
+ private final long targetDataFileSize;
+ private final String branch;
+ private final boolean overwriteMode;
+ private final int workerPoolSize;
+
+ private final Table table;
+ private final List<String> equalityFieldColumns = null;
+
+ private IcebergSink(
+ TableLoader tableLoader,
+ Table table,
+ Map<String, String> snapshotProperties,
+ String uidSuffix,
+ Map<String, String> writeProperties,
+ RowType flinkRowType,
+ SerializableSupplier<Table> tableSupplier,
+ FlinkWriteConf flinkWriteConf,
+ List<Integer> equalityFieldIds,
+ String branch,
+ boolean overwriteMode) {
+ this.tableLoader = tableLoader;
+ this.snapshotProperties = snapshotProperties;
+ this.uidSuffix = uidSuffix;
+ this.writeProperties = writeProperties;
+ this.flinkRowType = flinkRowType;
+ this.tableSupplier = tableSupplier;
+ this.flinkWriteConf = flinkWriteConf;
+ this.equalityFieldIds = equalityFieldIds;
+ this.branch = branch;
+ this.overwriteMode = overwriteMode;
+ this.table = table;
+ this.upsertMode = flinkWriteConf.upsertMode();
+ this.dataFileFormat = flinkWriteConf.dataFileFormat();
+ this.targetDataFileSize = flinkWriteConf.targetDataFileSize();
+ this.workerPoolSize = flinkWriteConf.workerPoolSize();
+ // We generate a random UUID every time when a sink is created.
+ // This is used to separate files generated by different sinks writing the same table.
+ // Also used to generate the aggregator operator name
+ this.sinkId = UUID.randomUUID().toString();
+ }
+
+ @Override
+ public SinkWriter<RowData> createWriter(InitContext context) {
+ RowDataTaskWriterFactory taskWriterFactory =
+ new RowDataTaskWriterFactory(
+ tableSupplier,
+ flinkRowType,
+ targetDataFileSize,
+ dataFileFormat,
+ writeProperties,
+ equalityFieldIds,
+ upsertMode);
+ IcebergStreamWriterMetrics metrics =
+ new IcebergStreamWriterMetrics(context.metricGroup(), table.name());
+ return new IcebergSinkWriter(
+ tableSupplier.get().name(),
+ taskWriterFactory,
+ metrics,
+ context.getSubtaskId(),
+ context.getAttemptNumber());
+ }
+
+ @Override
+ public Committer<IcebergCommittable> createCommitter(CommitterInitContext context) {
+ IcebergFilesCommitterMetrics metrics =
+ new IcebergFilesCommitterMetrics(context.metricGroup(), table.name());
+ return new IcebergCommitter(
+ tableLoader, branch, snapshotProperties, overwriteMode, workerPoolSize, sinkId, metrics);
+ }
+
+ @Override
+ public SimpleVersionedSerializer<IcebergCommittable> getCommittableSerializer() {
+ return new IcebergCommittableSerializer();
+ }
+
+ @Override
+ public void addPostCommitTopology(
+ DataStream<CommittableMessage<IcebergCommittable>> committables) {
+ // TODO Support small file compaction
+ }
+
+ @Override
+ public DataStream<RowData> addPreWriteTopology(DataStream<RowData> inputDataStream) {
+ return distributeDataStream(inputDataStream);
+ }
+
+ @Override
+ public DataStream<CommittableMessage<IcebergCommittable>> addPreCommitTopology(
+ DataStream<CommittableMessage<WriteResult>> writeResults) {
+ TypeInformation<CommittableMessage<IcebergCommittable>> typeInformation =
+ CommittableMessageTypeInfo.of(this::getCommittableSerializer);
+
+ String suffix = defaultSuffix(uidSuffix, table.name());
+ String preCommitAggregatorUid = String.format("Sink pre-commit aggregator: %s", suffix);
+
+ // global forces all output records send to subtask 0 of the downstream committer operator.
+ // This is to ensure commit only happen in one committer subtask.
+ // Once upstream Flink provides the capability of setting committer operator
+ // parallelism to 1, this can be removed.
+ return writeResults
+ .global()
+ .transform(preCommitAggregatorUid, typeInformation, new IcebergWriteAggregator(tableLoader))
+ .uid(preCommitAggregatorUid)
+ .setParallelism(1)
+ .setMaxParallelism(1)
+ // global forces all output records send to subtask 0 of the downstream committer operator.
+ // This is to ensure commit only happen in one committer subtask.
+ // Once upstream Flink provides the capability of setting committer operator
+ // parallelism to 1, this can be removed.
+ .global();
+ }
+
+ @Override
+ public SimpleVersionedSerializer<WriteResult> getWriteResultSerializer() {
+ return new WriteResultSerializer();
+ }
+
+ public static class Builder {
+ private TableLoader tableLoader;
+ private String uidSuffix = "";
+ private Function<String, DataStream<RowData>> inputCreator = null;
+ private TableSchema tableSchema;
+ private SerializableTable table;
+ private final Map<String, String> writeOptions = Maps.newHashMap();
+ private final Map<String, String> snapshotSummary = Maps.newHashMap();
+ private ReadableConfig readableConfig = new Configuration();
+ private List<String> equalityFieldColumns = null;
+
+ private Builder() {}
+
+ private Builder forRowData(DataStream<RowData> newRowDataInput) {
+ this.inputCreator = ignored -> newRowDataInput;
+ return this;
+ }
+
+ private Builder forRow(DataStream<Row> input, TableSchema inputTableSchema) {
+ RowType rowType = (RowType) inputTableSchema.toRowDataType().getLogicalType();
+ DataType[] fieldDataTypes = inputTableSchema.getFieldDataTypes();
+
+ DataFormatConverters.RowConverter rowConverter =
+ new DataFormatConverters.RowConverter(fieldDataTypes);
+ return forMapperOutputType(
+ input, rowConverter::toInternal, FlinkCompatibilityUtil.toTypeInfo(rowType))
+ .tableSchema(inputTableSchema);
+ }
+
+ private <T> Builder forMapperOutputType(
+ DataStream<T> input, MapFunction<T, RowData> mapper, TypeInformation<RowData> outputType) {
+ this.inputCreator =
+ newUidSuffix -> {
+ // Input stream order is crucial for some situation(e.g. in cdc case). Therefore, we
+ // need to set the parallelism of map operator same as its input to keep map operator
+ // chaining its input, and avoid rebalanced by default.
+ SingleOutputStreamOperator<RowData> inputStream =
+ input.map(mapper, outputType).setParallelism(input.getParallelism());
+ if (newUidSuffix != null) {
+ String uid = String.format("Sink pre-writer mapper: %s", newUidSuffix);
+ inputStream.name(uid).uid(uid);
+ }
+ return inputStream;
+ };
+ return this;
+ }
+
+ /**
+ * This iceberg {@link SerializableTable} instance is used for initializing {@link
+ * IcebergStreamWriter} which will write all the records into {@link DataFile}s and emit them to
+ * downstream operator. Providing a table would avoid so many table loading from each separate
+ * task.
+ *
+ * @param newTable the loaded iceberg table instance.
+ * @return {@link IcebergSink.Builder} to connect the iceberg table.
+ */
+ public Builder table(Table newTable) {
+ this.table = (SerializableTable) SerializableTable.copyOf(newTable);
+ return this;
+ }
+
+ /**
+ * The table loader is used for loading tables in {@link
+ * org.apache.iceberg.flink.sink.IcebergCommitter} lazily, we need this loader because {@link
+ * Table} is not serializable and could not just use the loaded table from Builder#table in the
+ * remote task manager.
+ *
+ * @param newTableLoader to load iceberg table inside tasks.
+ * @return {@link Builder} to connect the iceberg table.
+ */
+ public Builder tableLoader(TableLoader newTableLoader) {
+ this.tableLoader = newTableLoader;
+ return this;
+ }
+
+ TableLoader tableLoader() {
+ return tableLoader;
+ }
+
+ /**
+ * Set the write properties for IcebergSink. View the supported properties in {@link
+ * FlinkWriteOptions}
+ */
+ public Builder set(String property, String value) {
+ writeOptions.put(property, value);
+ return this;
+ }
+
+ /**
+ * Set the write properties for IcebergSink. View the supported properties in {@link
+ * FlinkWriteOptions}
+ */
+ public Builder setAll(Map<String, String> properties) {
+ writeOptions.putAll(properties);
+ return this;
+ }
+
+ public Builder tableSchema(TableSchema newTableSchema) {
+ this.tableSchema = newTableSchema;
+ return this;
+ }
+
+ public Builder overwrite(boolean newOverwrite) {
+ writeOptions.put(FlinkWriteOptions.OVERWRITE_MODE.key(), Boolean.toString(newOverwrite));
+ return this;
+ }
+
+ public Builder flinkConf(ReadableConfig config) {
+ this.readableConfig = config;
+ return this;
+ }
+
+ /**
+ * Configure the write {@link DistributionMode} that the IcebergSink will use. Currently, flink
+ * support {@link DistributionMode#NONE} and {@link DistributionMode#HASH}.
+ *
+ * @param mode to specify the write distribution mode.
+ * @return {@link IcebergSink.Builder} to connect the iceberg table.
+ */
+ public Builder distributionMode(DistributionMode mode) {
+ Preconditions.checkArgument(
+ !DistributionMode.RANGE.equals(mode),
+ "Flink does not support 'range' write distribution mode now.");
+ if (mode != null) {
+ writeOptions.put(FlinkWriteOptions.DISTRIBUTION_MODE.key(), mode.modeName());
+ }
+ return this;
+ }
+
+ /**
+ * Configuring the write parallel number for iceberg stream writer.
+ *
+ * @param newWriteParallelism the number of parallel iceberg stream writer.
+ * @return {@link IcebergSink.Builder} to connect the iceberg table.
+ */
+ public Builder writeParallelism(int newWriteParallelism) {
+ writeOptions.put(
+ FlinkWriteOptions.WRITE_PARALLELISM.key(), Integer.toString(newWriteParallelism));
+ return this;
+ }
+
+ /**
+ * All INSERT/UPDATE_AFTER events from input stream will be transformed to UPSERT events, which
+ * means it will DELETE the old records and then INSERT the new records. In partitioned table,
+ * the partition fields should be a subset of equality fields, otherwise the old row that
+ * located in partition-A could not be deleted by the new row that located in partition-B.
+ *
+ * @param enabled indicate whether it should transform all INSERT/UPDATE_AFTER events to UPSERT.
+ * @return {@link IcebergSink.Builder} to connect the iceberg table.
+ */
+ public Builder upsert(boolean enabled) {
+ writeOptions.put(FlinkWriteOptions.WRITE_UPSERT_ENABLED.key(), Boolean.toString(enabled));
+ return this;
+ }
+
+ /**
+ * Configuring the equality field columns for iceberg table that accept CDC or UPSERT events.
+ *
+ * @param columns defines the iceberg table's key.
+ * @return {@link Builder} to connect the iceberg table.
+ */
+ public Builder equalityFieldColumns(List<String> columns) {
+ this.equalityFieldColumns = columns;
+ return this;
+ }
+
+ /**
+ * Set the uid suffix for IcebergSink operators. Note that IcebergSink internally consists of
+ * multiple operators (like writer, committer, aggregator). Actual operator uid will be appended
+ * with a suffix like "Sink Committer: $uidSuffix".
+ *
+ * <p>Flink auto generates operator uid if not set explicitly. It is a recommended <a
+ * href="https://ci.apache.org/projects/flink/flink-docs-master/docs/ops/production_ready/">
+ * best-practice to set uid for all operators</a> before deploying to production. Flink has an
+ * option to {@code pipeline.auto-generate-uid=false} to disable auto-generation and force
+ * explicit setting of all operator uid.
+ *
+ * <p>Be careful with setting this for an existing job, because now we are changing the operator
+ * uid from an auto-generated one to this new value. When deploying the change with a
+ * checkpoint, Flink won't be able to restore the previous IcebergSink operator state (more
+ * specifically the committer operator state). You need to use {@code --allowNonRestoredState}
+ * to ignore the previous sink state. During restore IcebergSink state is used to check if last
+ * commit was actually successful or not. {@code --allowNonRestoredState} can lead to data loss
+ * if the Iceberg commit failed in the last completed checkpoint.
+ *
+ * @param newSuffix suffix for Flink sink operator uid and name
+ * @return {@link Builder} to connect the iceberg table.
+ */
+ public Builder uidSuffix(String newSuffix) {
+ this.uidSuffix = newSuffix;
+ return this;
+ }
+
+ public Builder snapshotProperties(Map<String, String> properties) {
+ snapshotSummary.putAll(properties);
+ return this;
+ }
+
+ public Builder setSnapshotProperty(String property, String value) {
+ snapshotSummary.put(property, value);
+ return this;
+ }
+
+ public Builder toBranch(String branch) {
+ writeOptions.put(FlinkWriteOptions.BRANCH.key(), branch);
+ return this;
+ }
+
+ IcebergSink build() {
+
+ Preconditions.checkArgument(
+ inputCreator != null,
+ "Please use forRowData() or forMapperOutputType() to initialize the input DataStream.");
+ Preconditions.checkNotNull(tableLoader(), "Table loader shouldn't be null");
+
+ // Set the table if it is not yet set in the builder, so we can do the equalityId checks
+ SerializableTable serializableTable = checkAndGetTable(tableLoader(), table);
+ this.table = serializableTable;
+ // Init the `flinkWriteConf` here, so we can do the checks
+ FlinkWriteConf flinkWriteConf = new FlinkWriteConf(table, writeOptions, readableConfig);
+
+ Duration tableRefreshInterval = flinkWriteConf.tableRefreshInterval();
+ SerializableSupplier<Table> tableSupplier;
+ if (tableRefreshInterval != null) {
+ tableSupplier = new CachingTableSupplier(table, tableLoader(), tableRefreshInterval);
+ } else {
+ tableSupplier = () -> serializableTable;
+ }
+
+ boolean overwriteMode = flinkWriteConf.overwriteMode();
+
+ // Validate the equality fields and partition fields if we enable the upsert mode.
+ List<Integer> equalityFieldIds =
+ SinkUtil.checkAndGetEqualityFieldIds(table, equalityFieldColumns);
+
+ if (flinkWriteConf.upsertMode()) {
+ Preconditions.checkState(
+ !overwriteMode,
+ "OVERWRITE mode shouldn't be enable when configuring to use UPSERT data stream.");
+ Preconditions.checkState(
+ !equalityFieldIds.isEmpty(),
+ "Equality field columns shouldn't be empty when configuring to use UPSERT data stream.");
+ if (!table.spec().isUnpartitioned()) {
+ for (PartitionField partitionField : table.spec().fields()) {
+ Preconditions.checkState(
+ equalityFieldIds.contains(partitionField.sourceId()),
+ "In UPSERT mode, partition field '%s' should be included in equality fields: '%s'",
+ partitionField,
+ equalityFieldColumns);
+ }
+ }
+ }
+
+ return new IcebergSink(
+ tableLoader,
+ table,
+ snapshotSummary,
+ uidSuffix,
+ writeProperties(table, flinkWriteConf.dataFileFormat(), flinkWriteConf),
+ toFlinkRowType(table.schema(), tableSchema),
+ tableSupplier,
+ flinkWriteConf,
+ equalityFieldIds,
+ flinkWriteConf.branch(),
+ overwriteMode);
+ }
+
+ /**
+ * Append the iceberg sink operators to write records to iceberg table.
+ *
+ * @return {@link DataStreamSink} for sink.
+ */
+ public DataStreamSink<RowData> append() {
+ IcebergSink sink = build();
+ String suffix = defaultSuffix(uidSuffix, table.name());
+ DataStream<RowData> rowDataInput = inputCreator.apply(suffix);
+ // Please note that V2 sink framework will apply the uid here to the framework created
+ // operators like writer,
+ // committer. E.g. "Sink writer: <uidSuffix>
+ DataStreamSink<RowData> rowDataDataStreamSink =
+ rowDataInput.sinkTo(sink).uid(suffix).name(suffix);
+
+ // Note that IcebergSink internally consists o multiple operators (like writer, committer,
+ // aggregator).
+ // The following parallelism will be propagated to all of the above operators.
+ if (sink.flinkWriteConf.writeParallelism() != null) {
+ rowDataDataStreamSink.setParallelism(sink.flinkWriteConf.writeParallelism());
+ }
+ return rowDataDataStreamSink;
+ }
+ }
+
+ private static String defaultSuffix(String uidSuffix, String defaultSuffix) {
+ if (uidSuffix == null || uidSuffix.isEmpty()) {
+ return defaultSuffix;
+ }
+ return uidSuffix;
+ }
+
+ private static SerializableTable checkAndGetTable(TableLoader tableLoader, Table table) {
+ if (table == null) {
+ if (!tableLoader.isOpen()) {
+ tableLoader.open();
+ }
+
+ try (TableLoader loader = tableLoader) {
+ return (SerializableTable) SerializableTable.copyOf(loader.loadTable());
+ } catch (IOException e) {
+ throw new UncheckedIOException(
+ "Failed to load iceberg table from table loader: " + tableLoader, e);
+ }
+ }
+
+ return (SerializableTable) SerializableTable.copyOf(table);
+ }
+
+ private static RowType toFlinkRowType(Schema schema, TableSchema requestedSchema) {
+ if (requestedSchema != null) {
+ // Convert the flink schema to iceberg schema firstly, then reassign ids to match the existing
+ // iceberg schema.
+ Schema writeSchema = TypeUtil.reassignIds(FlinkSchemaUtil.convert(requestedSchema), schema);
+ TypeUtil.validateWriteSchema(schema, writeSchema, true, true);
+
+ // We use this flink schema to read values from RowData. The flink's TINYINT and SMALLINT will
+ // be promoted to iceberg INTEGER, that means if we use iceberg's table schema to read TINYINT
+ // (backend by 1 'byte'), we will read 4 bytes rather than 1 byte, it will mess up the byte
+ // array in BinaryRowData. So here we must use flink schema.
+ return (RowType) requestedSchema.toRowDataType().getLogicalType();
+ } else {
+ return FlinkSchemaUtil.convert(schema);
+ }
+ }
+
+ /**
+ * Based on the {@link FileFormat} overwrites the table level compression properties for the table
+ * write.
+ *
+ * @param table The table to get the table level settings
+ * @param format The FileFormat to use
+ * @param conf The write configuration
+ * @return The properties to use for writing
+ */
+ private static Map<String, String> writeProperties(
+ Table table, FileFormat format, FlinkWriteConf conf) {
+ Map<String, String> writeProperties = Maps.newHashMap(table.properties());
+
+ switch (format) {
+ case PARQUET:
+ writeProperties.put(PARQUET_COMPRESSION, conf.parquetCompressionCodec());
+ String parquetCompressionLevel = conf.parquetCompressionLevel();
+ if (parquetCompressionLevel != null) {
+ writeProperties.put(PARQUET_COMPRESSION_LEVEL, parquetCompressionLevel);
+ }
+
+ break;
+ case AVRO:
+ writeProperties.put(AVRO_COMPRESSION, conf.avroCompressionCodec());
+ String avroCompressionLevel = conf.avroCompressionLevel();
+ if (avroCompressionLevel != null) {
+ writeProperties.put(AVRO_COMPRESSION_LEVEL, conf.avroCompressionLevel());
+ }
+
+ break;
+ case ORC:
+ writeProperties.put(ORC_COMPRESSION, conf.orcCompressionCodec());
+ writeProperties.put(ORC_COMPRESSION_STRATEGY, conf.orcCompressionStrategy());
+ break;
+ default:
+ throw new IllegalArgumentException(String.format("Unknown file format %s", format));
+ }
+
+ return writeProperties;
+ }
+
+ private DataStream<RowData> distributeDataStream(DataStream<RowData> input) {
+ DistributionMode mode = flinkWriteConf.distributionMode();
+ Schema schema = table.schema();
+ PartitionSpec spec = table.spec();
+ LOG.info("Write distribution mode is '{}'", mode.modeName());
+ switch (mode) {
+ case NONE:
+ if (equalityFieldIds.isEmpty()) {
+ return input;
+ } else {
+ LOG.info("Distribute rows by equality fields, because there are equality fields set");
+ return input.keyBy(new EqualityFieldKeySelector(schema, flinkRowType, equalityFieldIds));
+ }
+
+ case HASH:
+ if (equalityFieldIds.isEmpty()) {
+ if (table.spec().isUnpartitioned()) {
+ LOG.warn(
+ "Fallback to use 'none' distribution mode, because there are no equality fields set "
+ + "and table is unpartitioned");
+ return input;
+ } else {
+ if (BucketPartitionerUtil.hasOneBucketField(spec)) {
+ return input.partitionCustom(
+ new BucketPartitioner(spec),
+ new BucketPartitionKeySelector(spec, schema, flinkRowType));
+ } else {
+ return input.keyBy(new PartitionKeySelector(spec, schema, flinkRowType));
+ }
+ }
+ } else {
+ if (spec.isUnpartitioned()) {
+ LOG.info(
+ "Distribute rows by equality fields, because there are equality fields set "
+ + "and table is unpartitioned");
+ return input.keyBy(
+ new EqualityFieldKeySelector(schema, flinkRowType, equalityFieldIds));
+ } else {
+ for (PartitionField partitionField : spec.fields()) {
+ Preconditions.checkState(
+ equalityFieldIds.contains(partitionField.sourceId()),
+ "In 'hash' distribution mode with equality fields set, partition field '%s' "
+ + "should be included in equality fields: '%s'",
+ partitionField,
+ equalityFieldColumns);
+ }
+ return input.keyBy(new PartitionKeySelector(spec, schema, flinkRowType));
+ }
+ }
+
+ case RANGE:
+ if (equalityFieldIds.isEmpty()) {
+ LOG.warn(
+ "Fallback to use 'none' distribution mode, because there are no equality fields set "
+ + "and {}=range is not supported yet in flink",
+ WRITE_DISTRIBUTION_MODE);
+ return input;
+ } else {
+ LOG.info(
+ "Distribute rows by equality fields, because there are equality fields set "
+ + "and{}=range is not supported yet in flink",
+ WRITE_DISTRIBUTION_MODE);
+ return input.keyBy(new EqualityFieldKeySelector(schema, flinkRowType, equalityFieldIds));
+ }
+
+ default:
+ throw new RuntimeException("Unrecognized " + WRITE_DISTRIBUTION_MODE + ": " + mode);
+ }
+ }
+
+ /**
+ * Initialize a {@link Builder} to export the data from generic input data stream into iceberg
+ * table. We use {@link RowData} inside the sink connector, so users need to provide a mapper
+ * function and a {@link TypeInformation} to convert those generic records to a RowData
+ * DataStream.
+ *
+ * @param input the generic source input data stream.
+ * @param mapper function to convert the generic data to {@link RowData}
+ * @param outputType to define the {@link TypeInformation} for the input data.
+ * @param <T> the data type of records.
+ * @return {@link Builder} to connect the iceberg table.
+ */
+ public static <T> Builder builderFor(
+ DataStream<T> input, MapFunction<T, RowData> mapper, TypeInformation<RowData> outputType) {
+ return new Builder().forMapperOutputType(input, mapper, outputType);
+ }
+
+ /**
+ * Initialize a {@link Builder} to export the data from input data stream with {@link Row}s into
+ * iceberg table. We use {@link RowData} inside the sink connector, so users need to provide a
+ * {@link TableSchema} for builder to convert those {@link Row}s to a {@link RowData} DataStream.
+ *
+ * @param input the source input data stream with {@link Row}s.
+ * @param tableSchema defines the {@link TypeInformation} for input data.
+ * @return {@link Builder} to connect the iceberg table.
+ */
+ public static Builder forRow(DataStream<Row> input, TableSchema tableSchema) {
+ return new Builder().forRow(input, tableSchema);
+ }
+
+ /**
+ * Initialize a {@link Builder} to export the data from input data stream with {@link RowData}s
+ * into iceberg table.
+ *
+ * @param input the source input data stream with {@link RowData}s.
+ * @return {@link Builder} to connect the iceberg table.
+ */
+ public static Builder forRowData(DataStream<RowData> input) {
+ return new Builder().forRowData(input);
+ }
+}
diff --git a/flink/v1.19/flink/src/main/java/org/apache/iceberg/flink/sink/IcebergSinkWriter.java b/flink/v1.19/flink/src/main/java/org/apache/iceberg/flink/sink/IcebergSinkWriter.java
new file mode 100644
index 000000000000..7234cf74020e
--- /dev/null
+++ b/flink/v1.19/flink/src/main/java/org/apache/iceberg/flink/sink/IcebergSinkWriter.java
@@ -0,0 +1,113 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.iceberg.flink.sink;
+
+import java.io.IOException;
+import java.util.Collection;
+import java.util.concurrent.TimeUnit;
+import org.apache.flink.api.connector.sink2.CommittingSinkWriter;
+import org.apache.flink.api.connector.sink2.SinkWriter;
+import org.apache.flink.table.data.RowData;
+import org.apache.iceberg.io.TaskWriter;
+import org.apache.iceberg.io.WriteResult;
+import org.apache.iceberg.relocated.com.google.common.base.MoreObjects;
+import org.apache.iceberg.relocated.com.google.common.collect.Lists;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Iceberg writer implementation for the {@link SinkWriter} interface. Used by the {@link
+ * org.apache.iceberg.flink.sink.IcebergSink} (SinkV2). Writes out the data to the final place, and
+ * emits a single {@link WriteResult} at every checkpoint for every data/delete file created by this
+ * writer.
+ */
+class IcebergSinkWriter implements CommittingSinkWriter<RowData, WriteResult> {
+ private static final Logger LOG = LoggerFactory.getLogger(IcebergSinkWriter.class);
+
+ private final String fullTableName;
+ private final TaskWriterFactory<RowData> taskWriterFactory;
+ private final IcebergStreamWriterMetrics metrics;
+ private TaskWriter<RowData> writer;
+ private final int subTaskId;
+ private final int attemptId;
+
+ IcebergSinkWriter(
+ String fullTableName,
+ TaskWriterFactory<RowData> taskWriterFactory,
+ IcebergStreamWriterMetrics metrics,
+ int subTaskId,
+ int attemptId) {
+ this.fullTableName = fullTableName;
+ this.taskWriterFactory = taskWriterFactory;
+ // Initialize the task writer factory.
+ taskWriterFactory.initialize(subTaskId, attemptId);
+ // Initialize the task writer.
+ this.writer = taskWriterFactory.create();
+ this.metrics = metrics;
+ this.subTaskId = subTaskId;
+ this.attemptId = attemptId;
+ LOG.debug(
+ "Created Stream Writer for table {} subtask {} attemptId {}",
+ fullTableName,
+ subTaskId,
+ attemptId);
+ }
+
+ @Override
+ public void write(RowData element, Context context) throws IOException, InterruptedException {
+ writer.write(element);
+ }
+
+ @Override
+ public void flush(boolean endOfInput) {
+ // flush is used to handle flush/endOfInput, so no action is taken here.
+ }
+
+ @Override
+ public void close() throws Exception {
+ if (writer != null) {
+ writer.close();
+ }
+ }
+
+ @Override
+ public String toString() {
+ return MoreObjects.toStringHelper(this)
+ .add("tableName", fullTableName)
+ .add("subTaskId", subTaskId)
+ .add("attemptId", attemptId)
+ .toString();
+ }
+
+ @Override
+ public Collection<WriteResult> prepareCommit() throws IOException {
+ long startNano = System.nanoTime();
+ WriteResult result = writer.complete();
+ this.writer = taskWriterFactory.create();
+ metrics.updateFlushResult(result);
+ metrics.flushDuration(TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNano));
+ LOG.debug(
+ "Iceberg writer subtask {} attempt {} flushed {} data files and {} delete files",
+ subTaskId,
+ attemptId,
+ result.dataFiles().length,
+ result.deleteFiles().length);
+ return Lists.newArrayList(result);
+ }
+}
diff --git a/flink/v1.19/flink/src/main/java/org/apache/iceberg/flink/sink/IcebergStreamWriter.java b/flink/v1.19/flink/src/main/java/org/apache/iceberg/flink/sink/IcebergStreamWriter.java
index 9ea0349fb057..7d86baa14fc2 100644
--- a/flink/v1.19/flink/src/main/java/org/apache/iceberg/flink/sink/IcebergStreamWriter.java
+++ b/flink/v1.19/flink/src/main/java/org/apache/iceberg/flink/sink/IcebergStreamWriter.java
@@ -95,9 +95,9 @@ public void endInput() throws IOException {
@Override
public String toString() {
return MoreObjects.toStringHelper(this)
- .add("table_name", fullTableName)
- .add("subtask_id", subTaskId)
- .add("attempt_id", attemptId)
+ .add("tableName", fullTableName)
+ .add("subTaskId", subTaskId)
+ .add("attemptId", attemptId)
.toString();
}
diff --git a/flink/v1.19/flink/src/main/java/org/apache/iceberg/flink/sink/IcebergWriteAggregator.java b/flink/v1.19/flink/src/main/java/org/apache/iceberg/flink/sink/IcebergWriteAggregator.java
new file mode 100644
index 000000000000..794ade577976
--- /dev/null
+++ b/flink/v1.19/flink/src/main/java/org/apache/iceberg/flink/sink/IcebergWriteAggregator.java
@@ -0,0 +1,127 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.iceberg.flink.sink;
+
+import java.io.IOException;
+import java.util.Collection;
+import org.apache.flink.core.io.SimpleVersionedSerialization;
+import org.apache.flink.streaming.api.connector.sink2.CommittableMessage;
+import org.apache.flink.streaming.api.connector.sink2.CommittableSummary;
+import org.apache.flink.streaming.api.connector.sink2.CommittableWithLineage;
+import org.apache.flink.streaming.api.operators.AbstractStreamOperator;
+import org.apache.flink.streaming.api.operators.OneInputStreamOperator;
+import org.apache.flink.streaming.runtime.streamrecord.StreamRecord;
+import org.apache.iceberg.Table;
+import org.apache.iceberg.flink.TableLoader;
+import org.apache.iceberg.io.WriteResult;
+import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
+import org.apache.iceberg.relocated.com.google.common.collect.Sets;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Operator which aggregates the individual {@link WriteResult} objects) to a single {@link
+ * IcebergCommittable} per checkpoint (storing the serialized {@link
+ * org.apache.iceberg.flink.sink.DeltaManifests}, jobId, operatorId, checkpointId)
+ */
+class IcebergWriteAggregator extends AbstractStreamOperator<CommittableMessage<IcebergCommittable>>
+ implements OneInputStreamOperator<
+ CommittableMessage<WriteResult>, CommittableMessage<IcebergCommittable>> {
+ private static final Logger LOG = LoggerFactory.getLogger(IcebergWriteAggregator.class);
+ private static final byte[] EMPTY_MANIFEST_DATA = new byte[0];
+ private final Collection<WriteResult> results;
+ private transient ManifestOutputFileFactory icebergManifestOutputFileFactory;
+ private transient Table table;
+ private final TableLoader tableLoader;
+
+ IcebergWriteAggregator(TableLoader tableLoader) {
+ this.results = Sets.newHashSet();
+ this.tableLoader = tableLoader;
+ }
+
+ @Override
+ public void open() throws Exception {
+ if (!tableLoader.isOpen()) {
+ tableLoader.open();
+ }
+
+ String flinkJobId = getContainingTask().getEnvironment().getJobID().toString();
+ String operatorId = getOperatorID().toString();
+ int subTaskId = getRuntimeContext().getTaskInfo().getIndexOfThisSubtask();
+ Preconditions.checkArgument(
+ subTaskId == 0, "The subTaskId must be zero in the IcebergWriteAggregator");
+ int attemptId = getRuntimeContext().getTaskInfo().getAttemptNumber();
+ this.table = tableLoader.loadTable();
+
+ this.icebergManifestOutputFileFactory =
+ FlinkManifestUtil.createOutputFileFactory(
+ () -> table, table.properties(), flinkJobId, operatorId, subTaskId, attemptId);
+ }
+
+ @Override
+ public void finish() throws IOException {
+ prepareSnapshotPreBarrier(Long.MAX_VALUE);
+ }
+
+ @Override
+ public void prepareSnapshotPreBarrier(long checkpointId) throws IOException {
+ IcebergCommittable committable =
+ new IcebergCommittable(
+ writeToManifest(results, checkpointId),
+ getContainingTask().getEnvironment().getJobID().toString(),
+ getRuntimeContext().getOperatorUniqueID(),
+ checkpointId);
+ CommittableMessage<IcebergCommittable> summary =
+ new CommittableSummary<>(0, 1, checkpointId, 1, 1, 0);
+ output.collect(new StreamRecord<>(summary));
+ CommittableMessage<IcebergCommittable> message =
+ new CommittableWithLineage<>(committable, checkpointId, 0);
+ output.collect(new StreamRecord<>(message));
+ LOG.info("Emitted commit message to downstream committer operator");
+ results.clear();
+ }
+
+ /**
+ * Write all the completed data files to a newly created manifest file and return the manifest's
+ * avro serialized bytes.
+ */
+ public byte[] writeToManifest(Collection<WriteResult> writeResults, long checkpointId)
+ throws IOException {
+ if (writeResults.isEmpty()) {
+ return EMPTY_MANIFEST_DATA;
+ }
+
+ WriteResult result = WriteResult.builder().addAll(writeResults).build();
+ DeltaManifests deltaManifests =
+ FlinkManifestUtil.writeCompletedFiles(
+ result, () -> icebergManifestOutputFileFactory.create(checkpointId), table.spec());
+
+ return SimpleVersionedSerialization.writeVersionAndSerialize(
+ DeltaManifestsSerializer.INSTANCE, deltaManifests);
+ }
+
+ @Override
+ public void processElement(StreamRecord<CommittableMessage<WriteResult>> element)
+ throws Exception {
+
+ if (element.isRecord() && element.getValue() instanceof CommittableWithLineage) {
+ results.add(((CommittableWithLineage<WriteResult>) element.getValue()).getCommittable());
+ }
+ }
+}
diff --git a/flink/v1.19/flink/src/main/java/org/apache/iceberg/flink/sink/ManifestOutputFileFactory.java b/flink/v1.19/flink/src/main/java/org/apache/iceberg/flink/sink/ManifestOutputFileFactory.java
index da5e6e7627ae..1cb7f4dea1e8 100644
--- a/flink/v1.19/flink/src/main/java/org/apache/iceberg/flink/sink/ManifestOutputFileFactory.java
+++ b/flink/v1.19/flink/src/main/java/org/apache/iceberg/flink/sink/ManifestOutputFileFactory.java
@@ -26,13 +26,13 @@
import org.apache.iceberg.Table;
import org.apache.iceberg.TableOperations;
import org.apache.iceberg.io.OutputFile;
+import org.apache.iceberg.relocated.com.google.common.annotations.VisibleForTesting;
import org.apache.iceberg.relocated.com.google.common.base.Strings;
class ManifestOutputFileFactory {
// Users could define their own flink manifests directory by setting this value in table
// properties.
- static final String FLINK_MANIFEST_LOCATION = "flink.manifests.location";
-
+ @VisibleForTesting static final String FLINK_MANIFEST_LOCATION = "flink.manifests.location";
private final Supplier<Table> tableSupplier;
private final Map<String, String> props;
private final String flinkJobId;
diff --git a/flink/v1.19/flink/src/main/java/org/apache/iceberg/flink/sink/SinkUtil.java b/flink/v1.19/flink/src/main/java/org/apache/iceberg/flink/sink/SinkUtil.java
new file mode 100644
index 000000000000..7f28a50ecaa8
--- /dev/null
+++ b/flink/v1.19/flink/src/main/java/org/apache/iceberg/flink/sink/SinkUtil.java
@@ -0,0 +1,94 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.iceberg.flink.sink;
+
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import org.apache.flink.util.Preconditions;
+import org.apache.iceberg.Snapshot;
+import org.apache.iceberg.Table;
+import org.apache.iceberg.relocated.com.google.common.collect.Lists;
+import org.apache.iceberg.relocated.com.google.common.collect.Sets;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+class SinkUtil {
+
+ private static final long INITIAL_CHECKPOINT_ID = -1L;
+
+ public static final String FLINK_JOB_ID = "flink.job-id";
+
+ public static final String OPERATOR_ID = "flink.operator-id";
+ public static final String MAX_COMMITTED_CHECKPOINT_ID = "flink.max-committed-checkpoint-id";
+
+ private SinkUtil() {}
+
+ private static final Logger LOG = LoggerFactory.getLogger(SinkUtil.class);
+
+ static List<Integer> checkAndGetEqualityFieldIds(Table table, List<String> equalityFieldColumns) {
+ List<Integer> equalityFieldIds = Lists.newArrayList(table.schema().identifierFieldIds());
+ if (equalityFieldColumns != null && !equalityFieldColumns.isEmpty()) {
+ Set<Integer> equalityFieldSet = Sets.newHashSetWithExpectedSize(equalityFieldColumns.size());
+ for (String column : equalityFieldColumns) {
+ org.apache.iceberg.types.Types.NestedField field = table.schema().findField(column);
+ Preconditions.checkNotNull(
+ field,
+ "Missing required equality field column '%s' in table schema %s",
+ column,
+ table.schema());
+ equalityFieldSet.add(field.fieldId());
+ }
+
+ if (!equalityFieldSet.equals(table.schema().identifierFieldIds())) {
+ LOG.warn(
+ "The configured equality field column IDs {} are not matched with the schema identifier field IDs"
+ + " {}, use job specified equality field columns as the equality fields by default.",
+ equalityFieldSet,
+ table.schema().identifierFieldIds());
+ }
+ equalityFieldIds = Lists.newArrayList(equalityFieldSet);
+ }
+ return equalityFieldIds;
+ }
+
+ static long getMaxCommittedCheckpointId(
+ Table table, String flinkJobId, String operatorId, String branch) {
+ Snapshot snapshot = table.snapshot(branch);
+ long lastCommittedCheckpointId = INITIAL_CHECKPOINT_ID;
+
+ while (snapshot != null) {
+ Map<String, String> summary = snapshot.summary();
+ String snapshotFlinkJobId = summary.get(FLINK_JOB_ID);
+ String snapshotOperatorId = summary.get(OPERATOR_ID);
+ if (flinkJobId.equals(snapshotFlinkJobId)
+ && (snapshotOperatorId == null || snapshotOperatorId.equals(operatorId))) {
+ String value = summary.get(MAX_COMMITTED_CHECKPOINT_ID);
+ if (value != null) {
+ lastCommittedCheckpointId = Long.parseLong(value);
+ break;
+ }
+ }
+ Long parentSnapshotId = snapshot.parentId();
+ snapshot = parentSnapshotId != null ? table.snapshot(parentSnapshotId) : null;
+ }
+
+ return lastCommittedCheckpointId;
+ }
+}
diff --git a/flink/v1.19/flink/src/main/java/org/apache/iceberg/flink/sink/WriteResultSerializer.java b/flink/v1.19/flink/src/main/java/org/apache/iceberg/flink/sink/WriteResultSerializer.java
new file mode 100644
index 000000000000..5a44373cccaa
--- /dev/null
+++ b/flink/v1.19/flink/src/main/java/org/apache/iceberg/flink/sink/WriteResultSerializer.java
@@ -0,0 +1,61 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.iceberg.flink.sink;
+
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import org.apache.flink.core.io.SimpleVersionedSerializer;
+import org.apache.flink.core.memory.DataInputDeserializer;
+import org.apache.flink.core.memory.DataOutputViewStreamWrapper;
+import org.apache.flink.util.InstantiationUtil;
+import org.apache.iceberg.io.WriteResult;
+
+class WriteResultSerializer implements SimpleVersionedSerializer<WriteResult> {
+ private static final int VERSION = 1;
+
+ @Override
+ public int getVersion() {
+ return VERSION;
+ }
+
+ @Override
+ public byte[] serialize(WriteResult writeResult) throws IOException {
+ ByteArrayOutputStream out = new ByteArrayOutputStream();
+ DataOutputViewStreamWrapper view = new DataOutputViewStreamWrapper(out);
+ byte[] result = InstantiationUtil.serializeObject(writeResult);
+ view.write(result);
+ return out.toByteArray();
+ }
+
+ @Override
+ public WriteResult deserialize(int version, byte[] serialized) throws IOException {
+ if (version == 1) {
+ DataInputDeserializer view = new DataInputDeserializer(serialized);
+ byte[] resultBuf = new byte[serialized.length];
+ view.read(resultBuf);
+ try {
+ return InstantiationUtil.deserializeObject(
+ resultBuf, IcebergCommittableSerializer.class.getClassLoader());
+ } catch (ClassNotFoundException cnc) {
+ throw new IOException("Could not deserialize the WriteResult object", cnc);
+ }
+ }
+ throw new IOException("Unrecognized version or corrupt state: " + version);
+ }
+}
|