nandorsoma commented on code in PR #6368: URL: https://github.com/apache/nifi/pull/6368#discussion_r991430356
########## nifi-nar-bundles/nifi-iceberg-bundle/nifi-iceberg-processors/src/main/java/org/apache/nifi/processors/iceberg/converter/GenericDataConverters.java: ########## @@ -0,0 +1,230 @@ +/* + * 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.nifi.processors.iceberg.converter; + +import org.apache.commons.lang3.ArrayUtils; +import org.apache.commons.lang3.Validate; +import org.apache.iceberg.data.GenericRecord; +import org.apache.iceberg.types.Types; +import org.apache.nifi.serialization.record.DataType; +import org.apache.nifi.serialization.record.Record; +import org.apache.nifi.serialization.record.RecordField; + +import java.lang.reflect.Array; +import java.math.BigDecimal; +import java.nio.ByteBuffer; +import java.sql.Time; +import java.sql.Timestamp; +import java.time.LocalDateTime; +import java.time.LocalTime; +import java.time.OffsetDateTime; +import java.time.ZoneId; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; + +import static org.apache.nifi.processors.iceberg.converter.RecordFieldGetter.createFieldGetter; + +/** + * Data converter implementations for different data types. + */ +public class GenericDataConverters { + + static class SameTypeConverter implements DataConverter<Object, Object> { + + static final SameTypeConverter INSTANCE = new SameTypeConverter(); + + @Override + public Object convert(Object data) { + return data; + } + } + + static class TimeConverter implements DataConverter<Time, LocalTime> { + + static final TimeConverter INSTANCE = new TimeConverter(); + + @Override + public LocalTime convert(Time data) { + return data.toLocalTime(); + } + } + + static class TimestampConverter implements DataConverter<Timestamp, LocalDateTime> { + + static final TimestampConverter INSTANCE = new TimestampConverter(); + + @Override + public LocalDateTime convert(Timestamp data) { + return data.toLocalDateTime(); + } + } + + static class TimestampWithTimezoneConverter implements DataConverter<Timestamp, OffsetDateTime> { + + static final TimestampWithTimezoneConverter INSTANCE = new TimestampWithTimezoneConverter(); + + @Override + public OffsetDateTime convert(Timestamp data) { + return OffsetDateTime.ofInstant(data.toInstant(), ZoneId.of("UTC")); + } + } + + static class UUIDtoByteArrayConverter implements DataConverter<UUID, byte[]> { + + static final UUIDtoByteArrayConverter INSTANCE = new UUIDtoByteArrayConverter(); + + @Override + public byte[] convert(UUID data) { + ByteBuffer byteBuffer = ByteBuffer.wrap(new byte[16]); + byteBuffer.putLong(data.getMostSignificantBits()); + byteBuffer.putLong(data.getLeastSignificantBits()); + return byteBuffer.array(); + } + } + + static class FixedConverter implements DataConverter<Byte[], byte[]> { + + private final int length; + + FixedConverter(int length) { + this.length = length; + } + + @Override + public byte[] convert(Byte[] data) { + Validate.isTrue(data.length == length, String.format("Cannot write byte array of length %s as fixed[%s]", data.length, length)); + return ArrayUtils.toPrimitive(data); + } + } + + static class BinaryConverter implements DataConverter<Byte[], ByteBuffer> { + + static final BinaryConverter INSTANCE = new BinaryConverter(); + + @Override + public ByteBuffer convert(Byte[] data) { + return ByteBuffer.wrap(ArrayUtils.toPrimitive(data)); + } + } + + static class BigDecimalConverter implements DataConverter<BigDecimal, BigDecimal> { + + private final int precision; + private final int scale; + + BigDecimalConverter(int precision, int scale) { + this.precision = precision; + this.scale = scale; + } + + @Override + public BigDecimal convert(BigDecimal data) { + Validate.isTrue(data.scale() == scale, "Cannot write value as decimal(%s,%s), wrong scale: %s", precision, scale, data); + Validate.isTrue(data.precision() <= precision, "Cannot write value as decimal(%s,%s), invalid precision: %s", precision, scale, data); + return data; + } + } + + static class ArrayConverter<T, S> implements DataConverter<T[], List<S>> { + private final DataConverter<T, S> fieldConverter; + private final ArrayElementGetter.ElementGetter elementGetter; + + ArrayConverter(DataConverter<T, S> elementConverter, DataType dataType) { + this.fieldConverter = elementConverter; + this.elementGetter = ArrayElementGetter.createElementGetter(dataType); + } + + @Override + @SuppressWarnings("unchecked") + public List<S> convert(T[] data) { + final int numElements = data.length; + List<S> result = new ArrayList<>(numElements); + for (int i = 0; i < numElements; i += 1) { + result.add(i, fieldConverter.convert((T) elementGetter.getElementOrNull(data, i))); + } + return result; + } + } + + static class MapConverter<K, V, L, B> implements DataConverter<Map<K, V>, Map<L, B>> { + private final DataConverter<K, L> keyConverter; + private final DataConverter<V, B> valueConverter; + private final ArrayElementGetter.ElementGetter keyGetter; + private final ArrayElementGetter.ElementGetter valueGetter; + + MapConverter(DataConverter<K, L> keyConverter, DataType keyType, DataConverter<V, B> valueConverter, DataType valueType) { + this.keyConverter = keyConverter; + this.keyGetter = ArrayElementGetter.createElementGetter(keyType); + this.valueConverter = valueConverter; + this.valueGetter = ArrayElementGetter.createElementGetter(valueType); + } + + @Override + @SuppressWarnings("unchecked") + public Map<L, B> convert(Map<K, V> data) { + final int mapSize = data.size(); + final Object[] keyArray = data.keySet().toArray(); + final Object[] valueArray = data.values().toArray(); + Map<L, B> result = new HashMap<>(mapSize); + for (int i = 0; i < mapSize; i += 1) { + result.put(keyConverter.convert((K) keyGetter.getElementOrNull(keyArray, i)), valueConverter.convert((V) valueGetter.getElementOrNull(valueArray, i))); + } + + return result; + } + } + + static class RecordConverter implements DataConverter<Record, GenericRecord> { + + private final DataConverter<?, ?>[] converters; + private final RecordFieldGetter.FieldGetter[] getters; + + private final Types.StructType schema; + + RecordConverter(List<DataConverter<?, ?>> converters, List<RecordField> recordFields, Types.StructType schema) { + this.schema = schema; + this.converters = (DataConverter<?, ?>[]) Array.newInstance(DataConverter.class, converters.size()); + this.getters = new RecordFieldGetter.FieldGetter[converters.size()]; + for (int i = 0; i < converters.size(); i += 1) { + final RecordField recordField = recordFields.get(i); + this.converters[i] = converters.get(i); + this.getters[i] = createFieldGetter(recordField.getDataType(), recordField.getFieldName(), recordField.isNullable()); + } + } + + @Override + public GenericRecord convert(Record data) { + final GenericRecord template = GenericRecord.create(schema); + // GenericRecord.copy() is more performant then GenericRecord.create(StructType) since NAME_MAP_CACHE access is eliminated. Using copy here to gain performance. + GenericRecord result = template.copy(); Review Comment: missing final ########## nifi-assembly/pom.xml: ########## @@ -1528,5 +1528,31 @@ language governing permissions and limitations under the License. --> </plugins> </build> </profile> + <profile> Review Comment: I understand that we need a separate profile for Iceberg because the resulting nars became too big. However, this means that none of the GitHub CI jobs will include it, which is risky. It would probably be overkill to add it to all CI jobs, but is it possible to run tests in one of the CI jobs? I'm okay with handling it in a separate pr or discussing it. @turcsanyip ########## nifi-nar-bundles/nifi-iceberg-bundle/nifi-iceberg-processors/src/main/java/org/apache/nifi/processors/iceberg/AbstractIcebergProcessor.java: ########## @@ -0,0 +1,125 @@ +/* + * 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.nifi.processors.iceberg; + +import org.apache.hadoop.security.UserGroupInformation; +import org.apache.nifi.annotation.lifecycle.OnScheduled; +import org.apache.nifi.annotation.lifecycle.OnStopped; +import org.apache.nifi.components.PropertyDescriptor; +import org.apache.nifi.flowfile.FlowFile; +import org.apache.nifi.kerberos.KerberosUserService; +import org.apache.nifi.processor.AbstractProcessor; +import org.apache.nifi.processor.ProcessContext; +import org.apache.nifi.processor.ProcessSession; +import org.apache.nifi.processor.exception.ProcessException; +import org.apache.nifi.security.krb.KerberosLoginException; +import org.apache.nifi.security.krb.KerberosUser; +import org.apache.nifi.services.iceberg.IcebergCatalogService; + +import java.io.IOException; +import java.security.PrivilegedExceptionAction; + +import static org.apache.nifi.hadoop.SecurityUtil.getUgiForKerberosUser; +import static org.apache.nifi.processors.iceberg.PutIceberg.REL_FAILURE; + +/** + * Base Iceberg processor class. + */ +public abstract class AbstractIcebergProcessor extends AbstractProcessor { + + static final PropertyDescriptor CATALOG = new PropertyDescriptor.Builder() + .name("catalog-service") + .displayName("Catalog Service") + .description("Specifies the Controller Service to use for handling references to table’s metadata files.") + .identifiesControllerService(IcebergCatalogService.class) + .required(true) + .build(); + + static final PropertyDescriptor KERBEROS_USER_SERVICE = new PropertyDescriptor.Builder() + .name("kerberos-user-service") + .displayName("Kerberos User Service") + .description("Specifies the Kerberos User Controller Service that should be used for authenticating with Kerberos.") + .identifiesControllerService(KerberosUserService.class) + .build(); + + private volatile KerberosUser kerberosUser; + private volatile UserGroupInformation ugi; + + @OnScheduled + public final void onScheduled(final ProcessContext context) { + final IcebergCatalogService catalogService = context.getProperty(CATALOG).asControllerService(IcebergCatalogService.class); + final KerberosUserService kerberosUserService = context.getProperty(KERBEROS_USER_SERVICE).asControllerService(KerberosUserService.class); + + if (kerberosUserService != null) { + this.kerberosUser = kerberosUserService.createKerberosUser(); + try { + this.ugi = getUgiForKerberosUser(catalogService.getConfiguration(), kerberosUser); + } catch (IOException e) { + throw new ProcessException("Kerberos Authentication failed", e); + } + } + } + + @OnStopped + public final void onStopped() { + if (kerberosUser != null) { + try { + kerberosUser.logout(); + } catch (KerberosLoginException e) { + getLogger().error("Error logging out kerberos user", e); + } finally { + kerberosUser = null; + ugi = null; + } + } + } + + @Override + public void onTrigger(ProcessContext context, ProcessSession session) throws ProcessException { + FlowFile flowFile = session.get(); Review Comment: missing final ########## nifi-nar-bundles/nifi-iceberg-bundle/nifi-iceberg-processors/src/main/java/org/apache/nifi/processors/iceberg/converter/IcebergRecordConverter.java: ########## @@ -0,0 +1,190 @@ +/* + * 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.nifi.processors.iceberg.converter; + +import org.apache.commons.lang.Validate; +import org.apache.iceberg.FileFormat; +import org.apache.iceberg.Schema; +import org.apache.iceberg.data.GenericRecord; +import org.apache.iceberg.schema.SchemaWithPartnerVisitor; +import org.apache.iceberg.types.Type; +import org.apache.iceberg.types.Types; +import org.apache.nifi.serialization.record.DataType; +import org.apache.nifi.serialization.record.Record; +import org.apache.nifi.serialization.record.RecordField; +import org.apache.nifi.serialization.record.RecordFieldType; +import org.apache.nifi.serialization.record.RecordSchema; +import org.apache.nifi.serialization.record.type.ArrayDataType; +import org.apache.nifi.serialization.record.type.MapDataType; +import org.apache.nifi.serialization.record.type.RecordDataType; + +import java.util.List; +import java.util.Optional; + +/** + * This class is responsible for schema traversal and data conversion between NiFi and Iceberg internal record structure. + */ +public class IcebergRecordConverter { + + private final DataConverter<Record, GenericRecord> converter; + + public GenericRecord convert(Record record) { + return converter.convert(record); + } + + @SuppressWarnings("unchecked") + public IcebergRecordConverter(Schema schema, RecordSchema recordSchema, FileFormat fileFormat) { + this.converter = (DataConverter<Record, GenericRecord>) IcebergSchemaVisitor.visit(schema, new RecordDataType(recordSchema), fileFormat); + } + + private static class IcebergSchemaVisitor extends SchemaWithPartnerVisitor<DataType, DataConverter<?, ?>> { + + public static DataConverter<?, ?> visit(Schema schema, RecordDataType recordDataType, FileFormat fileFormat) { + return visit(schema, recordDataType, new IcebergSchemaVisitor(), new IcebergPartnerAccessors(fileFormat)); + } + + @Override + public DataConverter<?, ?> schema(Schema schema, DataType dataType, DataConverter<?, ?> converter) { + return converter; + } + + @Override + public DataConverter<?, ?> field(Types.NestedField field, DataType dataType, DataConverter<?, ?> converter) { + return converter; + } + + @Override + public DataConverter<?, ?> primitive(Type.PrimitiveType type, DataType dataType) { + if (type.typeId() != null) { + switch (type.typeId()) { + case BOOLEAN: + case INTEGER: + case LONG: + case FLOAT: + case DOUBLE: + case DATE: + case STRING: + return GenericDataConverters.SameTypeConverter.INSTANCE; + case TIME: + return GenericDataConverters.TimeConverter.INSTANCE; + case TIMESTAMP: + Types.TimestampType timestampType = (Types.TimestampType) type; + if (timestampType.shouldAdjustToUTC()) { + return GenericDataConverters.TimestampWithTimezoneConverter.INSTANCE; + } + return GenericDataConverters.TimestampConverter.INSTANCE; + case UUID: + UUIDDataType uuidType = (UUIDDataType) dataType; + if (uuidType.getFileFormat() == FileFormat.PARQUET) { + return GenericDataConverters.UUIDtoByteArrayConverter.INSTANCE; + } + return GenericDataConverters.SameTypeConverter.INSTANCE; + case FIXED: + Types.FixedType fixedType = (Types.FixedType) type; + return new GenericDataConverters.FixedConverter(fixedType.length()); + case BINARY: + return GenericDataConverters.BinaryConverter.INSTANCE; + case DECIMAL: + Types.DecimalType decimalType = (Types.DecimalType) type; + return new GenericDataConverters.BigDecimalConverter(decimalType.precision(), decimalType.scale()); + default: + throw new UnsupportedOperationException("Unsupported type: " + type.typeId()); + } + } + return null; Review Comment: I'm still uncertain about this part. I think we should handle the same way a non existent and an unknown type. -- 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. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected]
