wernerdv commented on code in PR #13897: URL: https://github.com/apache/ignite/pull/13897#discussion_r4788251750
########## modules/compatibility/src/test/java/org/apache/ignite/compatibility/persistence/WalSampleRecordsFactory.java: ########## @@ -0,0 +1,335 @@ +/* + * 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.ignite.compatibility.persistence; + +import java.lang.reflect.Array; +import java.lang.reflect.Field; +import java.lang.reflect.Modifier; +import java.lang.reflect.ParameterizedType; +import java.lang.reflect.Type; +import java.nio.file.FileSystem; +import java.nio.file.FileSystems; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Comparator; +import java.util.EnumMap; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.TreeMap; +import java.util.UUID; +import java.util.stream.Collectors; +import java.util.stream.Stream; +import org.apache.ignite.IgniteException; +import org.apache.ignite.IgniteLogger; +import org.apache.ignite.internal.pagemem.wal.record.CacheState; +import org.apache.ignite.internal.pagemem.wal.record.DataEntry; +import org.apache.ignite.internal.pagemem.wal.record.DataRecord; +import org.apache.ignite.internal.pagemem.wal.record.WALRecord; +import org.apache.ignite.internal.pagemem.wal.record.WALRecord.RecordType; +import org.apache.ignite.internal.processors.cache.CacheObject; +import org.apache.ignite.internal.processors.cache.CacheObjectValueContext; +import org.apache.ignite.internal.processors.cache.persistence.tree.io.BPlusIO; +import org.apache.ignite.internal.processors.cache.persistence.tree.io.PageIO; +import org.apache.ignite.internal.processors.cache.tree.DataInnerIO; +import org.apache.ignite.internal.util.GridUnsafe; +import org.apache.ignite.lang.IgniteBiTuple; +import org.apache.ignite.lang.IgniteProductVersion; +import org.jetbrains.annotations.Nullable; + +/** + * Generates sample WAL records with no code per record type: record classes are found by a scan, a sample is created + * without a constructor, and its fields are set by their declared types to values that are never default ones. + * Also tells the values of the fields of a record, for two versions to compare what they read from the same bytes. + */ +public class WalSampleRecordsFactory { + /** Root package of the product. */ + private static final String IGNITE_PKG = "org.apache.ignite."; + + /** IO of the rows of B+tree records: a fixed version, the latest one may differ between the versions. */ + private static final BPlusIO<?> ROW_IO = DataInnerIO.VERSIONS.forVersion(1); + + /** @return Record classes of the running version by record type. */ + static Map<RecordType, Class<?>> recordClasses() throws Exception { + Map<RecordType, Class<?>> res = new EnumMap<>(RecordType.class); + + for (String clsName : classNames()) { + Class<?> cls = Class.forName(clsName, false, WALRecord.class.getClassLoader()); + + if (!WALRecord.class.isAssignableFrom(cls) || Modifier.isAbstract(cls.getModifiers())) + continue; + + RecordType type = ((WALRecord)GridUnsafe.allocateInstance(cls)).type(); + + // A wrapper of other records has no type of its own. + if (type == null) + continue; + + Class<?> prev = res.put(type, cls); + + if (prev != null) { + throw new IgniteException("Several classes of WAL records of one type [type=" + type + + ", classes=" + prev.getName() + ", " + cls.getName() + ']'); + } + } + + // Otherwise all record types look like having no records. + if (res.isEmpty()) + throw new IgniteException("No classes of WAL records are found"); + + return res; + } + + /** @return Sample record with all fields set; {@code entry} is for the data records: only a node can create cache objects. */ + static WALRecord buildSampleRecord(Class<?> cls, DataEntry entry) throws Exception { + return (WALRecord)fill(GridUnsafe.allocateInstance(cls), null, entry); + } + + /** @return Values of the fields of the record by the path of a field. */ + static Map<String, String> fieldValues(WALRecord rec) throws Exception { + Map<String, String> res = new TreeMap<>(); + + res.put("type()", String.valueOf(rec.type())); + + values(rec, "", res); + + return res; + } + + /** @return Names of the product classes located with {@link WALRecord}: in a jar or in a directory. */ + private static List<String> classNames() throws Exception { + Path src = Paths.get(WALRecord.class.getProtectionDomain().getCodeSource().getLocation().toURI()); + + // A jar is a file system of its own. + try (FileSystem jar = Files.isDirectory(src) ? null : FileSystems.newFileSystem(src, (ClassLoader)null)) { + Path root = jar == null ? src : jar.getPath("/"); + + String ext = ".class"; + + try (Stream<Path> files = Files.walk(root)) { + return files + .map(file -> root.relativize(file).toString().replace(root.getFileSystem().getSeparator(), ".")) + .filter(name -> name.startsWith(IGNITE_PKG) && name.endsWith(ext)) + .map(name -> name.substring(0, name.length() - ext.length())) + .collect(Collectors.toList()); + } + } + } + + /** @return Fields of the object, the ones of {@link WALRecord} itself excluded: the writer sets them. */ + private static List<Field> fields(Object obj) { + List<Field> res = new ArrayList<>(); + + for (Class<?> cls = obj.getClass(); cls != WALRecord.class && cls != Object.class; cls = cls.getSuperclass()) { + for (Field fld : cls.getDeclaredFields()) { + if (!Modifier.isStatic(fld.getModifiers())) { + fld.setAccessible(true); + + res.add(fld); + } + } + } + + return res; + } + + /** @return The object with all fields set; {@code path} is {@code null} for a record itself. */ + private static Object fill(Object obj, @Nullable String path, DataEntry entry) throws Exception { + for (Field fld : fields(obj)) { + String fldPath = (path == null ? fld.getDeclaringClass().getSimpleName() : path) + '.' + fld.getName(); + + fld.set(obj, value(fld.getGenericType(), fldPath, obj, entry)); + } + + return obj; + } + + /** @return Value of a field by its declared type, derived from the path of the field. */ + private static Object value(Type type, String path, Object owner, DataEntry entry) throws Exception { + if (type instanceof ParameterizedType paramType) { + Class<?> raw = (Class<?>)paramType.getRawType(); + Type[] args = paramType.getActualTypeArguments(); + + if (raw == Map.class) { + Map<Object, Object> map = new HashMap<>(); + + map.put(value(args[0], path + ".key", owner, entry), value(args[1], path + ".val", owner, entry)); + + return map; + } + + if (raw == Collection.class || raw == List.class || raw == Set.class) { + Collection<Object> col = raw == Set.class ? new HashSet<>() : new ArrayList<>(); + + col.add(value(args[0], path + ".elem", owner, entry)); + + return col; + } + + if (IgniteBiTuple.class.isAssignableFrom(raw)) { + return raw.getConstructor(Object.class, Object.class) + .newInstance(value(args[0], path + ".1", owner, entry), value(args[1], path + ".2", owner, entry)); + } + + type = raw; + } + + Class<?> cls = (Class<?>)type; + + long seed = Integer.toUnsignedLong(path.hashCode()); + + if (cls == boolean.class || cls == Boolean.class) + return true; + + // Small: may be an ordinal or a size, some are written as shorter types. + if (cls == byte.class || cls == Byte.class) + return (byte)(1 + seed % 3); + + if (cls == short.class || cls == Short.class) + return (short)(1 + seed % 1_000); + + if (cls == int.class || cls == Integer.class) + return (int)(1 + seed % 10_000); + + if (cls == long.class || cls == Long.class) + return 1 + seed % 1_000_000; + + if (cls == String.class) + return path; + + if (cls == UUID.class) + return new UUID(seed, seed + 1); + + // As long as an item of the IO: a row of a B+tree record must be. + if (cls == byte[].class) + return bytes(seed, ROW_IO.getItemSize()); + + if (cls.isEnum()) { + Object[] consts = cls.getEnumConstants(); + + return consts[consts.length == 1 ? 0 : (int)(1 + seed % (consts.length - 1))]; + } + + // Values that cannot be derived from the declared type. + if (cls == IgniteLogger.class) + return null; + + // Must be a registered IO. + if (BPlusIO.class.isAssignableFrom(cls)) + return ROW_IO; + + // The revision hash has a fixed length. + if (cls == IgniteProductVersion.class) + return new IgniteProductVersion((byte)1, (byte)2, (byte)3, seed, bytes(seed, IgniteProductVersion.REV_HASH_SIZE)); + + // Consistent only if filled by its own method. + if (cls == CacheState.class) { + CacheState state = new CacheState(1); + + state.addPartitionState((int)(1 + seed % 1_000), 1 + seed % 10_000, 1 + seed % 100_000, (byte)(1 + seed % 3)); + + return state; + } + + // A data record keeps its entries in an untyped field. + if (cls == Object.class && owner instanceof DataRecord) + return entry; + + if (cls.getName().startsWith(IGNITE_PKG) && !cls.isInterface() && !Modifier.isAbstract(cls.getModifiers())) + return fill(GridUnsafe.allocateInstance(cls), path, entry); + + throw new IgniteException("No sample value for a field of such type [field=" + path + ", type=" + cls.getName() + ']'); + } + + /** Puts the values of the object, a field by a field, under the path. */ + private static void values(@Nullable Object obj, String path, Map<String, String> res) throws Exception { + if (obj != null && obj.getClass().isArray() && !(obj instanceof byte[])) { + List<Object> elems = new ArrayList<>(); + + for (int i = 0; i < Array.getLength(obj); i++) + elems.add(Array.get(obj, i)); + + obj = elems; + } + + if (obj == null || obj instanceof Number || obj instanceof Boolean || obj instanceof String || obj instanceof UUID) + res.put(path, String.valueOf(obj)); + // By name: the numbers of the constants may differ between the versions. + else if (obj instanceof Enum) + res.put(path, ((Enum<?>)obj).name()); + else if (obj instanceof byte[]) + res.put(path, Arrays.toString((byte[])obj)); + // A tuple is a map too. + else if (obj instanceof Collection || obj instanceof Map) { + List<Map<String, String>> elems = new ArrayList<>(); + + for (Object elem : obj instanceof Map ? ((Map<?, ?>)obj).entrySet() : (Collection<?>)obj) { + Map<String, String> elemVals = new TreeMap<>(); + + if (elem instanceof Map.Entry<?, ?> e) { + values(e.getKey(), "key", elemVals); + values(e.getValue(), "val", elemVals); + } + else + values(elem, "", elemVals); + + elems.add(elemVals); + } + + // The order of a set or of a map means nothing. + if (!(obj instanceof List)) + elems.sort(Comparator.comparing(Object::toString)); + + res.put(path + ".size", String.valueOf(elems.size())); + + for (int i = 0; i < elems.size(); i++) { + String elemPath = path + '[' + i + ']'; + + elems.get(i).forEach((k, v) -> res.put(k.isEmpty() ? elemPath : elemPath + '.' + k, v)); + } + } + else if (obj instanceof CacheObject) + res.put(path, ((CacheObject)obj).cacheObjectType() + ":" + Arrays.toString(((CacheObject)obj).valueBytes(null))); + else if (obj instanceof PageIO) + res.put(path, ((PageIO)obj).getType() + ":" + ((PageIO)obj).getVersion()); + // A logger and a context of cache objects are not data. + else if (!(obj instanceof IgniteLogger) && !(obj instanceof CacheObjectValueContext)) { + if (!obj.getClass().getName().startsWith(IGNITE_PKG)) + throw new IgniteException("No rule to tell the value of a field [field=" + path + ", type=" + obj.getClass() + ']'); + + for (Field fld : fields(obj)) + values(fld.get(obj), path.isEmpty() ? fld.getName() : path + '.' + fld.getName(), res); Review Comment: Fixed. -- 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]
