danny0405 commented on a change in pull request #12178: URL: https://github.com/apache/flink/pull/12178#discussion_r426112993
########## File path: flink-connectors/flink-connector-hbase/src/main/java/org/apache/flink/connector/hbase/sink/HBaseDynamicTableSink.java ########## @@ -0,0 +1,108 @@ +/* + * 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.flink.connector.hbase.sink; + +import org.apache.flink.annotation.Internal; +import org.apache.flink.annotation.VisibleForTesting; +import org.apache.flink.connector.hbase.options.HBaseOptions; +import org.apache.flink.connector.hbase.options.HBaseWriteOptions; +import org.apache.flink.connector.hbase.util.HBaseTableSchema; +import org.apache.flink.table.connector.ChangelogMode; +import org.apache.flink.table.connector.sink.DynamicTableSink; +import org.apache.flink.table.connector.sink.SinkFunctionProvider; +import org.apache.flink.table.data.RowData; +import org.apache.flink.types.RowKind; + +import org.apache.hadoop.conf.Configuration; +import org.apache.hadoop.hbase.HBaseConfiguration; +import org.apache.hadoop.hbase.HConstants; + +/** + * HBase table sink implementation. + */ +@Internal +public class HBaseDynamicTableSink implements DynamicTableSink { + + private final HBaseTableSchema hbaseTableSchema; + private final HBaseOptions hbaseOptions; + private final HBaseWriteOptions writeOptions; + + public HBaseDynamicTableSink( + HBaseTableSchema hbaseTableSchema, + HBaseOptions hbaseOptions, + HBaseWriteOptions writeOptions) { + this.hbaseTableSchema = hbaseTableSchema; + this.hbaseOptions = hbaseOptions; + this.writeOptions = writeOptions; + } + + @Override + public SinkRuntimeProvider getSinkRuntimeProvider(Context context) { + Configuration hbaseClientConf = HBaseConfiguration.create(); + hbaseClientConf.set(HConstants.ZOOKEEPER_QUORUM, hbaseOptions.getZkQuorum()); + hbaseOptions.getZkNodeParent().ifPresent(v -> hbaseClientConf.set(HConstants.ZOOKEEPER_ZNODE_PARENT, v)); + HBaseSinkFunction<RowData> sinkFunction = new HBaseSinkFunction<>( + hbaseOptions.getTableName(), + hbaseClientConf, + new RowDataToMutationConverter(hbaseTableSchema), + writeOptions.getBufferFlushMaxSizeInBytes(), + writeOptions.getBufferFlushMaxRows(), + writeOptions.getBufferFlushIntervalMillis()); + return SinkFunctionProvider.of(sinkFunction); + } + + @Override + public ChangelogMode getChangelogMode(ChangelogMode requestedMode) { + // UPSERT mode + ChangelogMode.Builder builder = ChangelogMode.newBuilder(); + for (RowKind kind : requestedMode.getContainedKinds()) { + if (kind != RowKind.UPDATE_BEFORE) { + builder.addContainedKind(kind); Review comment: Maybe we can have some utils like `ChangelogMode.exclude(RowKind)`, many upserts sink would reuse that. ########## File path: flink-connectors/flink-connector-hbase/src/main/java/org/apache/flink/connector/hbase/util/HBaseSerde.java ########## @@ -0,0 +1,371 @@ +/* + * 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.flink.connector.hbase.util; + +import org.apache.flink.table.data.DecimalData; +import org.apache.flink.table.data.GenericRowData; +import org.apache.flink.table.data.RowData; +import org.apache.flink.table.data.StringData; +import org.apache.flink.table.data.TimestampData; +import org.apache.flink.table.types.DataType; +import org.apache.flink.table.types.logical.DecimalType; +import org.apache.flink.table.types.logical.LogicalType; + +import org.apache.hadoop.hbase.client.Delete; +import org.apache.hadoop.hbase.client.Put; +import org.apache.hadoop.hbase.client.Result; +import org.apache.hadoop.hbase.client.Scan; +import org.apache.hadoop.hbase.util.Bytes; + +import javax.annotation.Nullable; + +import java.io.Serializable; +import java.math.BigDecimal; +import java.util.Arrays; + +import static org.apache.flink.table.types.logical.utils.LogicalTypeChecks.getPrecision; +import static org.apache.flink.util.Preconditions.checkArgument; + +/** + * Utilities for HBase serialization and deserialization. + */ +public class HBaseSerde implements Serializable { + + private static final long serialVersionUID = 1L; + private static final byte[] EMPTY_BYTES = new byte[]{}; + + // row key index in output row + private final int rowkeyIndex; + + // family keys + private final byte[][] families; + // qualifier keys + private final byte[][][] qualifiers; + + private final int fieldLength; + + private GenericRowData reusedRow; + private GenericRowData[] reusedFamilyRows; + + private final FieldEncoder keyEncoder; + private final FieldDecoder keyDecoder; + private final FieldEncoder[][] qualifierEncoders; + private final FieldDecoder[][] qualifierDecoders; + + public HBaseSerde(HBaseTableSchema hbaseSchema) { + this.families = hbaseSchema.getFamilyKeys(); + this.rowkeyIndex = hbaseSchema.getRowKeyIndex(); + LogicalType rowkeyType = hbaseSchema.getRowKeyDataType().map(DataType::getLogicalType).orElse(null); + + // field length need take row key into account if it exists. + checkArgument(rowkeyIndex != -1 && rowkeyType != null, "row key is not set."); + this.fieldLength = families.length + 1; + + // prepare output rows + this.reusedRow = new GenericRowData(fieldLength); + this.reusedFamilyRows = new GenericRowData[families.length]; + + // row key should never be null + this.keyEncoder = createFieldEncoder(rowkeyType); + this.keyDecoder = createFieldDecoder(rowkeyType); + + this.qualifiers = new byte[families.length][][]; + this.qualifierEncoders = new FieldEncoder[families.length][]; + this.qualifierDecoders = new FieldDecoder[families.length][]; + String[] familyNames = hbaseSchema.getFamilyNames(); + for (int f = 0; f < families.length; f++) { + this.qualifiers[f] = hbaseSchema.getQualifierKeys(familyNames[f]); + DataType[] dataTypes = hbaseSchema.getQualifierDataTypes(familyNames[f]); + this.qualifierEncoders[f] = Arrays.stream(dataTypes) + .map(DataType::getLogicalType) + .map(HBaseSerde::createNullableFieldEncoder) + .toArray(FieldEncoder[]::new); + this.qualifierDecoders[f] = Arrays.stream(dataTypes) + .map(DataType::getLogicalType) + .map(HBaseSerde::createNullableFieldDecoder) + .toArray(FieldDecoder[]::new); + this.reusedFamilyRows[f] = new GenericRowData(dataTypes.length); + } + } + + /** + * Returns an instance of Put that writes record to HBase table. + * + * @return The appropriate instance of Put for this use case. + */ + public @Nullable Put createPutMutation(RowData row) { + byte[] rowkey = keyEncoder.encode(row, rowkeyIndex); + if (rowkey.length == 0) { + // drop dirty records, rowkey shouldn't be zero length + return null; + } + // upsert + Put put = new Put(rowkey); + for (int i = 0; i < fieldLength; i++) { + if (i != rowkeyIndex) { + int f = i > rowkeyIndex ? i - 1 : i; + // get family key + byte[] familyKey = families[f]; + RowData familyRow = row.getRow(i, qualifiers[f].length); + for (int q = 0; q < this.qualifiers[f].length; q++) { + // get quantifier key + byte[] qualifier = qualifiers[f][q]; + // serialize value + byte[] value = qualifierEncoders[f][q].encode(familyRow, q); + put.addColumn(familyKey, qualifier, value); + } + } + } + return put; + } + + /** + * Returns an instance of Delete that remove record from HBase table. + * + * @return The appropriate instance of Delete for this use case. + */ + public @Nullable Delete createDeleteMutation(RowData row) { + byte[] rowkey = keyEncoder.encode(row, rowkeyIndex); + if (rowkey.length == 0) { + // drop dirty records, rowkey shouldn't be zero length + return null; Review comment: Should we throw here ? ########## File path: flink-connectors/flink-connector-hbase/src/main/java/org/apache/flink/connector/hbase/util/HBaseSerde.java ########## @@ -0,0 +1,371 @@ +/* + * 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.flink.connector.hbase.util; + +import org.apache.flink.table.data.DecimalData; +import org.apache.flink.table.data.GenericRowData; +import org.apache.flink.table.data.RowData; +import org.apache.flink.table.data.StringData; +import org.apache.flink.table.data.TimestampData; +import org.apache.flink.table.types.DataType; +import org.apache.flink.table.types.logical.DecimalType; +import org.apache.flink.table.types.logical.LogicalType; + +import org.apache.hadoop.hbase.client.Delete; +import org.apache.hadoop.hbase.client.Put; +import org.apache.hadoop.hbase.client.Result; +import org.apache.hadoop.hbase.client.Scan; +import org.apache.hadoop.hbase.util.Bytes; + +import javax.annotation.Nullable; + +import java.io.Serializable; +import java.math.BigDecimal; +import java.util.Arrays; + +import static org.apache.flink.table.types.logical.utils.LogicalTypeChecks.getPrecision; +import static org.apache.flink.util.Preconditions.checkArgument; + +/** + * Utilities for HBase serialization and deserialization. + */ +public class HBaseSerde implements Serializable { + + private static final long serialVersionUID = 1L; + private static final byte[] EMPTY_BYTES = new byte[]{}; + + // row key index in output row + private final int rowkeyIndex; + + // family keys + private final byte[][] families; + // qualifier keys + private final byte[][][] qualifiers; + + private final int fieldLength; + + private GenericRowData reusedRow; + private GenericRowData[] reusedFamilyRows; + + private final FieldEncoder keyEncoder; + private final FieldDecoder keyDecoder; + private final FieldEncoder[][] qualifierEncoders; + private final FieldDecoder[][] qualifierDecoders; + + public HBaseSerde(HBaseTableSchema hbaseSchema) { + this.families = hbaseSchema.getFamilyKeys(); + this.rowkeyIndex = hbaseSchema.getRowKeyIndex(); + LogicalType rowkeyType = hbaseSchema.getRowKeyDataType().map(DataType::getLogicalType).orElse(null); + + // field length need take row key into account if it exists. + checkArgument(rowkeyIndex != -1 && rowkeyType != null, "row key is not set."); + this.fieldLength = families.length + 1; + + // prepare output rows + this.reusedRow = new GenericRowData(fieldLength); + this.reusedFamilyRows = new GenericRowData[families.length]; + + // row key should never be null + this.keyEncoder = createFieldEncoder(rowkeyType); + this.keyDecoder = createFieldDecoder(rowkeyType); + + this.qualifiers = new byte[families.length][][]; + this.qualifierEncoders = new FieldEncoder[families.length][]; + this.qualifierDecoders = new FieldDecoder[families.length][]; + String[] familyNames = hbaseSchema.getFamilyNames(); + for (int f = 0; f < families.length; f++) { + this.qualifiers[f] = hbaseSchema.getQualifierKeys(familyNames[f]); + DataType[] dataTypes = hbaseSchema.getQualifierDataTypes(familyNames[f]); + this.qualifierEncoders[f] = Arrays.stream(dataTypes) + .map(DataType::getLogicalType) + .map(HBaseSerde::createNullableFieldEncoder) + .toArray(FieldEncoder[]::new); + this.qualifierDecoders[f] = Arrays.stream(dataTypes) + .map(DataType::getLogicalType) + .map(HBaseSerde::createNullableFieldDecoder) + .toArray(FieldDecoder[]::new); + this.reusedFamilyRows[f] = new GenericRowData(dataTypes.length); + } + } + + /** + * Returns an instance of Put that writes record to HBase table. + * + * @return The appropriate instance of Put for this use case. + */ + public @Nullable Put createPutMutation(RowData row) { + byte[] rowkey = keyEncoder.encode(row, rowkeyIndex); + if (rowkey.length == 0) { + // drop dirty records, rowkey shouldn't be zero length + return null; + } + // upsert + Put put = new Put(rowkey); + for (int i = 0; i < fieldLength; i++) { + if (i != rowkeyIndex) { + int f = i > rowkeyIndex ? i - 1 : i; + // get family key + byte[] familyKey = families[f]; + RowData familyRow = row.getRow(i, qualifiers[f].length); + for (int q = 0; q < this.qualifiers[f].length; q++) { + // get quantifier key + byte[] qualifier = qualifiers[f][q]; + // serialize value + byte[] value = qualifierEncoders[f][q].encode(familyRow, q); + put.addColumn(familyKey, qualifier, value); + } + } + } + return put; + } + + /** + * Returns an instance of Delete that remove record from HBase table. + * + * @return The appropriate instance of Delete for this use case. + */ + public @Nullable Delete createDeleteMutation(RowData row) { + byte[] rowkey = keyEncoder.encode(row, rowkeyIndex); + if (rowkey.length == 0) { + // drop dirty records, rowkey shouldn't be zero length + return null; + } + // delete + Delete delete = new Delete(rowkey); + for (int i = 0; i < fieldLength; i++) { + if (i != rowkeyIndex) { + int f = i > rowkeyIndex ? i - 1 : i; + // get family key + byte[] familyKey = families[f]; + for (int q = 0; q < this.qualifiers[f].length; q++) { + // get quantifier key + byte[] qualifier = qualifiers[f][q]; + delete.addColumn(familyKey, qualifier); + } + } + } + return delete; + } + + /** + * Returns an instance of Scan that retrieves the required subset of records from the HBase table. + * + * @return The appropriate instance of Scan for this use case. + */ + public Scan createScan() { + Scan scan = new Scan(); + for (int f = 0; f < families.length; f++) { + byte[] family = families[f]; + for (int q = 0; q < qualifiers[f].length; q++) { + byte[] quantifier = qualifiers[f][q]; + scan.addColumn(family, quantifier); + } + } + return scan; + } + + /** + * Converts HBase {@link Result} into {@link RowData}. + */ + public RowData convertToRow(Result result) { + Object rowkey = keyDecoder.decode(result.getRow()); + for (int i = 0; i < fieldLength; i++) { + if (rowkeyIndex == i) { + reusedRow.setField(rowkeyIndex, rowkey); + } else { + int f = (rowkeyIndex != -1 && i > rowkeyIndex) ? i - 1 : i; + // get family key + byte[] familyKey = families[f]; + GenericRowData familyRow = reusedFamilyRows[f]; + for (int q = 0; q < this.qualifiers[f].length; q++) { + // get quantifier key + byte[] qualifier = qualifiers[f][q]; + // read value + byte[] value = result.getValue(familyKey, qualifier); + familyRow.setField(q, qualifierDecoders[f][q].decode(value)); + } + reusedRow.setField(i, familyRow); + } + } + return reusedRow; + } + + // ------------------------------------------------------------------------------------ + // HBase Runtime Encoders + // ------------------------------------------------------------------------------------ + + /** + * Runtime encoder that encodes a specified field in {@link RowData} into byte[]. + */ + @FunctionalInterface + private interface FieldEncoder extends Serializable { + byte[] encode(RowData row, int pos); + } + + private static FieldEncoder createNullableFieldEncoder(LogicalType fieldType) { + final FieldEncoder encoder = createFieldEncoder(fieldType); + if (fieldType.isNullable()) { + return (row, pos) -> { + if (row.isNullAt(pos)) { + return EMPTY_BYTES; + } else { Review comment: For string, use a 'N/A' seems better which has no conflicts with empty string `""`. ---------------------------------------------------------------- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. For queries about this service, please contact Infrastructure at: [email protected]
