|
|
@@ -0,0 +1,524 @@
|
|
|
+import org.w3c.dom.Document;
|
|
|
+import org.w3c.dom.Element;
|
|
|
+import org.w3c.dom.NodeList;
|
|
|
+
|
|
|
+import javax.xml.parsers.DocumentBuilderFactory;
|
|
|
+import java.net.URI;
|
|
|
+import java.net.URLEncoder;
|
|
|
+import java.net.http.HttpClient;
|
|
|
+import java.net.http.HttpRequest;
|
|
|
+import java.net.http.HttpResponse;
|
|
|
+import java.nio.charset.StandardCharsets;
|
|
|
+import java.nio.file.Files;
|
|
|
+import java.nio.file.Path;
|
|
|
+import java.sql.Connection;
|
|
|
+import java.sql.DriverManager;
|
|
|
+import java.sql.ResultSet;
|
|
|
+import java.sql.ResultSetMetaData;
|
|
|
+import java.sql.Statement;
|
|
|
+import java.time.LocalDateTime;
|
|
|
+import java.time.format.DateTimeFormatter;
|
|
|
+import java.util.ArrayList;
|
|
|
+import java.util.Base64;
|
|
|
+import java.util.Comparator;
|
|
|
+import java.util.LinkedHashMap;
|
|
|
+import java.util.LinkedHashSet;
|
|
|
+import java.util.List;
|
|
|
+import java.util.Locale;
|
|
|
+import java.util.Map;
|
|
|
+import java.util.Set;
|
|
|
+import java.util.TreeMap;
|
|
|
+import java.util.regex.Matcher;
|
|
|
+import java.util.regex.Pattern;
|
|
|
+import java.util.stream.Stream;
|
|
|
+
|
|
|
+public class FtsDryRunInventory {
|
|
|
+
|
|
|
+ private static final Pattern JAVA_STRING_ASSIGNMENT =
|
|
|
+ Pattern.compile("super\\.(tabName|idName)\\s*=\\s*\"([^\"]+)\"");
|
|
|
+ private static final Pattern SAFE_IDENTIFIER =
|
|
|
+ Pattern.compile("[A-Za-z][A-Za-z0-9_$#]*(\\.[A-Za-z][A-Za-z0-9_$#]*)*");
|
|
|
+ private static final Pattern JSON_NUMBER = Pattern.compile("\"%s\"\\s*:\\s*([0-9]+)");
|
|
|
+ private static final Pattern JSON_STRING = Pattern.compile("\"%s\"\\s*:\\s*\"([^\"]*)\"");
|
|
|
+ private static final Pattern CHILD_OBJECT_NAME =
|
|
|
+ Pattern.compile("[\"']name[\"']\\s*:\\s*[\"']([^\"']+)[\"']");
|
|
|
+ private static final Pattern CHILD_ARRAY_STRING =
|
|
|
+ Pattern.compile("(?:\\[|,)\\s*[\"']([^\"']+)[\"']\\s*(?=,|\\])");
|
|
|
+ private static final DateTimeFormatter TIME_FORMAT = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
|
|
|
+ private static final String RECORD_FILTER = "JLZTM in (51,22,25)";
|
|
|
+
|
|
|
+ public static void main(String[] args) throws Exception {
|
|
|
+ if (args.length != 10) {
|
|
|
+ System.err.println("Usage: FtsDryRunInventory <cfgRoot> <srcRoot> <jdbcUrl> <dbUser> " +
|
|
|
+ "<dbPasswordEnv> <esBaseUrl> <esUser> <esPasswordEnv> <markdownOutput> <tsvOutput>");
|
|
|
+ System.exit(64);
|
|
|
+ }
|
|
|
+
|
|
|
+ Path cfgRoot = Path.of(args[0]);
|
|
|
+ Path srcRoot = Path.of(args[1]);
|
|
|
+ String dbPassword = requiredEnvironment(args[4]);
|
|
|
+ String esPassword = requiredEnvironment(args[7]);
|
|
|
+ Path markdownOutput = Path.of(args[8]);
|
|
|
+ Path tsvOutput = Path.of(args[9]);
|
|
|
+
|
|
|
+ Inventory inventory = loadInventory(cfgRoot, srcRoot);
|
|
|
+ EsProbe esProbe = new EsProbe(args[5], args[6], esPassword);
|
|
|
+ EsEnvironment esEnvironment = esProbe.readEnvironment();
|
|
|
+
|
|
|
+ Class.forName("oracle.jdbc.OracleDriver");
|
|
|
+ try (Connection connection = DriverManager.getConnection(args[2], args[3], dbPassword)) {
|
|
|
+ connection.setAutoCommit(false);
|
|
|
+ connection.setReadOnly(true);
|
|
|
+ for (RebuildUnit unit : inventory.units)
|
|
|
+ probeUnit(connection, esProbe, unit);
|
|
|
+ connection.rollback();
|
|
|
+ }
|
|
|
+
|
|
|
+ String createdAt = LocalDateTime.now().format(TIME_FORMAT);
|
|
|
+ String markdown = makeMarkdown(createdAt, args[2], args[3], args[5], inventory, esEnvironment);
|
|
|
+ String tsv = makeTsv(inventory.units);
|
|
|
+ Files.createDirectories(markdownOutput.toAbsolutePath().getParent());
|
|
|
+ Files.createDirectories(tsvOutput.toAbsolutePath().getParent());
|
|
|
+ Files.writeString(markdownOutput, markdown, StandardCharsets.UTF_8);
|
|
|
+ Files.writeString(tsvOutput, tsv, StandardCharsets.UTF_8);
|
|
|
+
|
|
|
+ long blocked = inventory.units.stream().filter(RebuildUnit::blocked).count();
|
|
|
+ long mismatched = inventory.units.stream().filter(RebuildUnit::countMismatch).count();
|
|
|
+ System.out.println("DRY_RUN_COMPLETED objects=" + inventory.configuredObjectCount +
|
|
|
+ " ftsCandidates=" + inventory.ftsCandidateCount +
|
|
|
+ " rootCandidates=" + inventory.rootCandidateCount +
|
|
|
+ " logicalIndexes=" + inventory.units.size() +
|
|
|
+ " blocked=" + blocked + " countMismatch=" + mismatched);
|
|
|
+ System.out.println("MARKDOWN=" + markdownOutput.toAbsolutePath());
|
|
|
+ System.out.println("TSV=" + tsvOutput.toAbsolutePath());
|
|
|
+ }
|
|
|
+
|
|
|
+ private static Inventory loadInventory(Path cfgRoot, Path srcRoot) throws Exception {
|
|
|
+ Map<String, ObjectConfig> objectMap = new LinkedHashMap<>();
|
|
|
+ List<String> globalIssues = new ArrayList<>();
|
|
|
+ DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
|
|
|
+ factory.setFeature("http://xml.org/sax/features/external-general-entities", false);
|
|
|
+ factory.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
|
|
|
+ factory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
|
|
|
+ factory.setXIncludeAware(false);
|
|
|
+ factory.setExpandEntityReferences(false);
|
|
|
+
|
|
|
+ List<Path> xmlFiles;
|
|
|
+ try (Stream<Path> paths = Files.walk(cfgRoot)) {
|
|
|
+ xmlFiles = paths.filter(path -> path.getFileName().toString().endsWith(".obj.xml"))
|
|
|
+ .sorted().toList();
|
|
|
+ }
|
|
|
+ for (Path xmlFile : xmlFiles) {
|
|
|
+ Document document = factory.newDocumentBuilder().parse(xmlFile.toFile());
|
|
|
+ NodeList nodes = document.getElementsByTagName("obj");
|
|
|
+ for (int index = 0; index < nodes.getLength(); index++) {
|
|
|
+ Element element = (Element) nodes.item(index);
|
|
|
+ ObjectConfig object = readObject(element, xmlFile, srcRoot);
|
|
|
+ ObjectConfig previous = objectMap.put(object.name, object);
|
|
|
+ if (previous != null)
|
|
|
+ globalIssues.add("对象名重复:" + object.name + ",文件 " + previous.xmlFile + " 与 " + xmlFile);
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ Set<String> referencedChildren = new LinkedHashSet<>();
|
|
|
+ for (ObjectConfig object : objectMap.values()) {
|
|
|
+ for (String childName : childNames(object.childStr)) {
|
|
|
+ if (objectMap.containsKey(childName))
|
|
|
+ referencedChildren.add(childName);
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ List<ObjectConfig> rootCandidates = objectMap.values().stream()
|
|
|
+ .filter(object -> object.hasFts && object.root && !referencedChildren.contains(object.name))
|
|
|
+ .sorted(Comparator.comparing(object -> object.name))
|
|
|
+ .toList();
|
|
|
+ Map<String, List<ObjectConfig>> grouped = new TreeMap<>();
|
|
|
+ for (ObjectConfig object : rootCandidates)
|
|
|
+ grouped.computeIfAbsent(object.logicalIndex, key -> new ArrayList<>()).add(object);
|
|
|
+
|
|
|
+ List<RebuildUnit> units = new ArrayList<>();
|
|
|
+ for (Map.Entry<String, List<ObjectConfig>> entry : grouped.entrySet()) {
|
|
|
+ List<ObjectConfig> sources = entry.getValue();
|
|
|
+ Set<String> canonicalNames = new LinkedHashSet<>();
|
|
|
+ for (ObjectConfig source : sources)
|
|
|
+ canonicalNames.add(source.canonicalName);
|
|
|
+ String canonicalName = canonicalNames.iterator().next();
|
|
|
+ ObjectConfig canonical = objectMap.get(canonicalName);
|
|
|
+ RebuildUnit unit = new RebuildUnit(entry.getKey(), sources, canonicalName, canonical);
|
|
|
+ if (canonicalNames.size() != 1)
|
|
|
+ unit.issues.add("同一逻辑索引存在多个 canonical 对象:" + String.join(", ", canonicalNames));
|
|
|
+ if (canonical == null)
|
|
|
+ unit.issues.add("配置中找不到 canonical 对象 " + canonicalName);
|
|
|
+ else {
|
|
|
+ if (canonical.searchFields.isEmpty() && canonical.keywordFields.isEmpty())
|
|
|
+ unit.issues.add("canonical 对象没有 search/keyword 字段");
|
|
|
+ if (!safeIdentifier(canonical.tableName))
|
|
|
+ unit.issues.add("表名不符合安全标识符规则:" + canonical.tableName);
|
|
|
+ if (!safeIdentifier(canonical.idName))
|
|
|
+ unit.issues.add("主键不符合安全标识符规则:" + canonical.idName);
|
|
|
+ for (String field : canonical.allFields()) {
|
|
|
+ if (!safeIdentifier(field))
|
|
|
+ unit.issues.add("字段不符合安全标识符规则:" + field);
|
|
|
+ }
|
|
|
+ }
|
|
|
+ if (sources.size() > 1 || !sources.stream().anyMatch(source -> source.name.equals(canonicalName)))
|
|
|
+ unit.warnings.add("多个来源对象归并到 canonical 对象 " + canonicalName);
|
|
|
+ units.add(unit);
|
|
|
+ }
|
|
|
+ int ftsCandidateCount = (int) objectMap.values().stream().filter(object -> object.hasFts).count();
|
|
|
+ return new Inventory(objectMap.size(), ftsCandidateCount, rootCandidates.size(), units, globalIssues);
|
|
|
+ }
|
|
|
+
|
|
|
+ private static ObjectConfig readObject(Element element, Path xmlFile, Path srcRoot) throws Exception {
|
|
|
+ String name = requiredAttribute(element, "name", xmlFile);
|
|
|
+ String description = element.getAttribute("desc");
|
|
|
+ String poClass = element.getAttribute("po");
|
|
|
+ String fts = element.getAttribute("fts");
|
|
|
+ boolean hasFts = !"false".equalsIgnoreCase(fts);
|
|
|
+ boolean root = !"child".equalsIgnoreCase(element.getAttribute("lvl"));
|
|
|
+ String childStr = element.getAttribute("child");
|
|
|
+ String canonicalName = fts.isBlank() || "true".equalsIgnoreCase(fts) ? name : fts;
|
|
|
+ String logicalIndex = canonicalName.toLowerCase(Locale.ROOT);
|
|
|
+ List<String> searchFields = splitFields(element.getAttribute("search"));
|
|
|
+ List<String> keywordFields = splitFields(element.getAttribute("keyword"));
|
|
|
+ String tableName = "";
|
|
|
+ String idName = "";
|
|
|
+ if (!poClass.isBlank()) {
|
|
|
+ Path poSource = srcRoot.resolve(poClass.replace('.', '/') + ".java");
|
|
|
+ if (Files.isRegularFile(poSource)) {
|
|
|
+ String source = Files.readString(poSource, StandardCharsets.UTF_8);
|
|
|
+ Matcher matcher = JAVA_STRING_ASSIGNMENT.matcher(source);
|
|
|
+ while (matcher.find()) {
|
|
|
+ if ("tabName".equals(matcher.group(1)))
|
|
|
+ tableName = matcher.group(2);
|
|
|
+ else if ("idName".equals(matcher.group(1)))
|
|
|
+ idName = matcher.group(2);
|
|
|
+ }
|
|
|
+ }
|
|
|
+ }
|
|
|
+ return new ObjectConfig(name, description, poClass, tableName, idName, canonicalName,
|
|
|
+ logicalIndex, searchFields, keywordFields, hasFts, root, childStr, xmlFile.toString());
|
|
|
+ }
|
|
|
+
|
|
|
+ private static Set<String> childNames(String childStr) {
|
|
|
+ Set<String> names = new LinkedHashSet<>();
|
|
|
+ if (childStr == null || childStr.isBlank())
|
|
|
+ return names;
|
|
|
+ if (!childStr.contains("[")) {
|
|
|
+ for (String value : childStr.split(",")) {
|
|
|
+ String name = value.trim();
|
|
|
+ if (!name.isEmpty())
|
|
|
+ names.add(name);
|
|
|
+ }
|
|
|
+ return names;
|
|
|
+ }
|
|
|
+ Matcher objectMatcher = CHILD_OBJECT_NAME.matcher(childStr);
|
|
|
+ while (objectMatcher.find())
|
|
|
+ names.add(objectMatcher.group(1).trim());
|
|
|
+ Matcher stringMatcher = CHILD_ARRAY_STRING.matcher(childStr);
|
|
|
+ while (stringMatcher.find())
|
|
|
+ names.add(stringMatcher.group(1).trim());
|
|
|
+ return names;
|
|
|
+ }
|
|
|
+
|
|
|
+ private static void probeUnit(Connection connection, EsProbe esProbe, RebuildUnit unit) {
|
|
|
+ ObjectConfig canonical = unit.canonical;
|
|
|
+ if (canonical != null && safeIdentifier(canonical.tableName) && safeIdentifier(canonical.idName)) {
|
|
|
+ try (Statement statement = connection.createStatement()) {
|
|
|
+ statement.setQueryTimeout(60);
|
|
|
+ try (ResultSet resultSet = statement.executeQuery("select * from " + canonical.tableName + " where 1=0")) {
|
|
|
+ ResultSetMetaData metadata = resultSet.getMetaData();
|
|
|
+ Set<String> columns = new LinkedHashSet<>();
|
|
|
+ for (int index = 1; index <= metadata.getColumnCount(); index++)
|
|
|
+ columns.add(metadata.getColumnName(index).toLowerCase(Locale.ROOT));
|
|
|
+ if (!columns.contains("jlztm"))
|
|
|
+ unit.issues.add("目标表缺少 JLZTM,无法使用统一记录状态口径");
|
|
|
+ for (String field : canonical.allFields()) {
|
|
|
+ if (!columns.contains(field.toLowerCase(Locale.ROOT)))
|
|
|
+ unit.issues.add("目标表缺少索引字段 " + field);
|
|
|
+ }
|
|
|
+ }
|
|
|
+ if (unit.issues.stream().noneMatch(issue -> issue.contains("JLZTM"))) {
|
|
|
+ try (ResultSet resultSet = statement.executeQuery("select count(*) from " + canonical.tableName +
|
|
|
+ " where " + RECORD_FILTER)) {
|
|
|
+ if (resultSet.next())
|
|
|
+ unit.dbCount = resultSet.getLong(1);
|
|
|
+ }
|
|
|
+ }
|
|
|
+ } catch (Exception exception) {
|
|
|
+ unit.issues.add("数据库只读检查失败:" + safeMessage(exception));
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ try {
|
|
|
+ unit.esExists = esProbe.indexExists(unit.logicalIndex);
|
|
|
+ if (unit.esExists)
|
|
|
+ unit.esCount = esProbe.indexCount(unit.logicalIndex);
|
|
|
+ else
|
|
|
+ unit.warnings.add("当前 Elasticsearch 中不存在该逻辑索引");
|
|
|
+ } catch (Exception exception) {
|
|
|
+ unit.issues.add("Elasticsearch 只读检查失败:" + safeMessage(exception));
|
|
|
+ }
|
|
|
+ if (unit.countMismatch())
|
|
|
+ unit.warnings.add("数据库数量与当前索引文档数不一致,差值=" + (unit.dbCount - unit.esCount));
|
|
|
+ }
|
|
|
+
|
|
|
+ private static String makeMarkdown(String createdAt, String jdbcUrl, String dbUser, String esBaseUrl,
|
|
|
+ Inventory inventory, EsEnvironment esEnvironment) {
|
|
|
+ long blocked = inventory.units.stream().filter(RebuildUnit::blocked).count();
|
|
|
+ long mismatch = inventory.units.stream().filter(RebuildUnit::countMismatch).count();
|
|
|
+ long dbTotal = inventory.units.stream().filter(unit -> unit.dbCount != null).mapToLong(unit -> unit.dbCount).sum();
|
|
|
+ long esTotal = inventory.units.stream().filter(unit -> unit.esCount != null).mapToLong(unit -> unit.esCount).sum();
|
|
|
+ StringBuilder result = new StringBuilder();
|
|
|
+ result.append("# Elasticsearch 全选 Dry-run 运行报告\n\n")
|
|
|
+ .append("> 生成时间:").append(createdAt).append(" \n")
|
|
|
+ .append("> 安全边界:仅执行 Oracle `SELECT` 和 Elasticsearch `GET/HEAD`;未创建、删除、写入或切换索引。\n\n")
|
|
|
+ .append("## 环境指纹\n\n")
|
|
|
+ .append("- 数据库:`").append(maskUser(dbUser)).append("@").append(safeMarkdown(jdbcUrl)).append("`\n")
|
|
|
+ .append("- Elasticsearch:`").append(safeMarkdown(esBaseUrl)).append("`\n")
|
|
|
+ .append("- 集群:`").append(safeMarkdown(esEnvironment.clusterName)).append("`,UUID `")
|
|
|
+ .append(safeMarkdown(esEnvironment.clusterUuid)).append("`,版本 `")
|
|
|
+ .append(safeMarkdown(esEnvironment.version)).append("`\n")
|
|
|
+ .append("- 集群健康:`").append(safeMarkdown(esEnvironment.health)).append("`\n")
|
|
|
+ .append("- IK 插件:").append(esEnvironment.hasIk ? "已发现 `analysis-ik`" : "**未发现 `analysis-ik`**").append("\n\n")
|
|
|
+ .append("## 汇总\n\n")
|
|
|
+ .append("| 指标 | 数量 |\n|---|---:|\n")
|
|
|
+ .append("| 配置对象 | ").append(inventory.configuredObjectCount).append(" |\n")
|
|
|
+ .append("| FTS 候选 | ").append(inventory.ftsCandidateCount).append(" |\n")
|
|
|
+ .append("| 根候选 | ").append(inventory.rootCandidateCount).append(" |\n")
|
|
|
+ .append("| 逻辑索引 | ").append(inventory.units.size()).append(" |\n")
|
|
|
+ .append("| BLOCKED | ").append(blocked).append(" |\n")
|
|
|
+ .append("| 数量不一致 | ").append(mismatch).append(" |\n")
|
|
|
+ .append("| 已取得数据库记录合计 | ").append(dbTotal).append(" |\n")
|
|
|
+ .append("| 已取得 ES 文档合计 | ").append(esTotal).append(" |\n\n")
|
|
|
+ .append("记录过滤口径:`").append(RECORD_FILTER).append("`。\n\n");
|
|
|
+ if (!inventory.globalIssues.isEmpty()) {
|
|
|
+ result.append("## 全局问题\n\n");
|
|
|
+ for (String issue : inventory.globalIssues)
|
|
|
+ result.append("- ").append(safeMarkdown(issue)).append("\n");
|
|
|
+ result.append("\n");
|
|
|
+ }
|
|
|
+ result.append("## 逐逻辑索引结果\n\n")
|
|
|
+ .append("| 状态 | 逻辑索引 | 来源对象 | canonical | 表/主键 | 字段 | DB | ES | 差值 | 问题/警告 |\n")
|
|
|
+ .append("|---|---|---|---|---|---|---:|---:|---:|---|\n");
|
|
|
+ for (RebuildUnit unit : inventory.units) {
|
|
|
+ Long delta = unit.dbCount == null || unit.esCount == null ? null : unit.dbCount - unit.esCount;
|
|
|
+ result.append("| ").append(unit.blocked() ? "BLOCKED" : "DRY_RUN_READY")
|
|
|
+ .append(" | `").append(unit.logicalIndex).append("` | ")
|
|
|
+ .append(safeMarkdown(unit.sourceNames())).append(" | `")
|
|
|
+ .append(safeMarkdown(unit.canonicalName)).append("` | `")
|
|
|
+ .append(safeMarkdown(unit.tableAndId())).append("` | ")
|
|
|
+ .append(safeMarkdown(unit.fields())).append(" | ")
|
|
|
+ .append(nullable(unit.dbCount)).append(" | ")
|
|
|
+ .append(nullable(unit.esCount)).append(" | ")
|
|
|
+ .append(nullable(delta)).append(" | ")
|
|
|
+ .append(safeMarkdown(unit.messages())).append(" |\n");
|
|
|
+ }
|
|
|
+ result.append("\n## 结论\n\n");
|
|
|
+ if (blocked > 0 || !inventory.globalIssues.isEmpty() || !esEnvironment.hasIk || "red".equals(esEnvironment.health))
|
|
|
+ result.append("当前结果为 **No-Go**:必须先关闭全部阻断项,再进入任何 Elasticsearch 写入阶段。\n");
|
|
|
+ else
|
|
|
+ result.append("当前只读预检无阻断项;仍需完成分页 Bulk、校验、alias 和回滚能力后才能进入写入演练。\n");
|
|
|
+ return result.toString();
|
|
|
+ }
|
|
|
+
|
|
|
+ private static String makeTsv(List<RebuildUnit> units) {
|
|
|
+ StringBuilder result = new StringBuilder("status\tlogical_index\tsource_objects\tcanonical_object\ttable\tid_field\tfields\tdb_count\tes_exists\tes_count\tdelta\tissues\twarnings\n");
|
|
|
+ for (RebuildUnit unit : units) {
|
|
|
+ Long delta = unit.dbCount == null || unit.esCount == null ? null : unit.dbCount - unit.esCount;
|
|
|
+ result.append(unit.blocked() ? "BLOCKED" : "DRY_RUN_READY").append('\t')
|
|
|
+ .append(tsv(unit.logicalIndex)).append('\t').append(tsv(unit.sourceNames())).append('\t')
|
|
|
+ .append(tsv(unit.canonicalName)).append('\t')
|
|
|
+ .append(tsv(unit.canonical == null ? "" : unit.canonical.tableName)).append('\t')
|
|
|
+ .append(tsv(unit.canonical == null ? "" : unit.canonical.idName)).append('\t')
|
|
|
+ .append(tsv(unit.fields())).append('\t').append(nullable(unit.dbCount)).append('\t')
|
|
|
+ .append(unit.esExists).append('\t').append(nullable(unit.esCount)).append('\t')
|
|
|
+ .append(nullable(delta)).append('\t').append(tsv(String.join(";", unit.issues))).append('\t')
|
|
|
+ .append(tsv(String.join(";", unit.warnings))).append('\n');
|
|
|
+ }
|
|
|
+ return result.toString();
|
|
|
+ }
|
|
|
+
|
|
|
+ private static String requiredEnvironment(String name) {
|
|
|
+ String value = System.getenv(name);
|
|
|
+ if (value == null || value.isBlank())
|
|
|
+ throw new IllegalArgumentException("Missing environment variable " + name);
|
|
|
+ return value;
|
|
|
+ }
|
|
|
+
|
|
|
+ private static String requiredAttribute(Element element, String name, Path file) {
|
|
|
+ String value = element.getAttribute(name);
|
|
|
+ if (value.isBlank())
|
|
|
+ throw new IllegalArgumentException("Missing " + name + " in " + file);
|
|
|
+ return value;
|
|
|
+ }
|
|
|
+
|
|
|
+ private static List<String> splitFields(String value) {
|
|
|
+ if (value == null || value.isBlank())
|
|
|
+ return List.of();
|
|
|
+ List<String> result = new ArrayList<>();
|
|
|
+ for (String item : value.split(",")) {
|
|
|
+ String field = item.trim();
|
|
|
+ if (!field.isBlank())
|
|
|
+ result.add(field);
|
|
|
+ }
|
|
|
+ return result;
|
|
|
+ }
|
|
|
+
|
|
|
+ private static boolean safeIdentifier(String value) {
|
|
|
+ return value != null && SAFE_IDENTIFIER.matcher(value).matches();
|
|
|
+ }
|
|
|
+
|
|
|
+ private static String safeMessage(Exception exception) {
|
|
|
+ String message = exception.getMessage();
|
|
|
+ return message == null || message.isBlank() ? exception.getClass().getSimpleName() : message.replace('\r', ' ').replace('\n', ' ');
|
|
|
+ }
|
|
|
+
|
|
|
+ private static String safeMarkdown(String value) {
|
|
|
+ return value == null ? "" : value.replace("|", "\\|").replace("\r", " ").replace("\n", " ");
|
|
|
+ }
|
|
|
+
|
|
|
+ private static String maskUser(String value) {
|
|
|
+ return value == null || value.isBlank() ? "未配置" : value.substring(0, 1) + "***";
|
|
|
+ }
|
|
|
+
|
|
|
+ private static String nullable(Object value) {
|
|
|
+ return value == null ? "" : String.valueOf(value);
|
|
|
+ }
|
|
|
+
|
|
|
+ private static String tsv(String value) {
|
|
|
+ return value == null ? "" : value.replace('\t', ' ').replace('\r', ' ').replace('\n', ' ');
|
|
|
+ }
|
|
|
+
|
|
|
+ private record ObjectConfig(String name, String description, String poClass, String tableName,
|
|
|
+ String idName, String canonicalName, String logicalIndex, List<String> searchFields,
|
|
|
+ List<String> keywordFields, boolean hasFts, boolean root, String childStr, String xmlFile) {
|
|
|
+
|
|
|
+ private List<String> allFields() {
|
|
|
+ Set<String> fields = new LinkedHashSet<>();
|
|
|
+ if (idName != null && !idName.isBlank())
|
|
|
+ fields.add(idName);
|
|
|
+ fields.addAll(searchFields);
|
|
|
+ fields.addAll(keywordFields);
|
|
|
+ return new ArrayList<>(fields);
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ private static final class RebuildUnit {
|
|
|
+ private final String logicalIndex;
|
|
|
+ private final List<ObjectConfig> sources;
|
|
|
+ private final String canonicalName;
|
|
|
+ private final ObjectConfig canonical;
|
|
|
+ private final List<String> issues = new ArrayList<>();
|
|
|
+ private final List<String> warnings = new ArrayList<>();
|
|
|
+ private Long dbCount;
|
|
|
+ private boolean esExists;
|
|
|
+ private Long esCount;
|
|
|
+
|
|
|
+ private RebuildUnit(String logicalIndex, List<ObjectConfig> sources, String canonicalName, ObjectConfig canonical) {
|
|
|
+ this.logicalIndex = logicalIndex;
|
|
|
+ this.sources = List.copyOf(sources);
|
|
|
+ this.canonicalName = canonicalName;
|
|
|
+ this.canonical = canonical;
|
|
|
+ }
|
|
|
+
|
|
|
+ private boolean blocked() {
|
|
|
+ return !issues.isEmpty();
|
|
|
+ }
|
|
|
+
|
|
|
+ private boolean countMismatch() {
|
|
|
+ return dbCount != null && esCount != null && !dbCount.equals(esCount);
|
|
|
+ }
|
|
|
+
|
|
|
+ private String sourceNames() {
|
|
|
+ return String.join(", ", sources.stream().map(source -> source.name).sorted().toList());
|
|
|
+ }
|
|
|
+
|
|
|
+ private String tableAndId() {
|
|
|
+ return canonical == null ? "" : canonical.tableName + "/" + canonical.idName;
|
|
|
+ }
|
|
|
+
|
|
|
+ private String fields() {
|
|
|
+ return canonical == null ? "" : String.join(", ", canonical.allFields());
|
|
|
+ }
|
|
|
+
|
|
|
+ private String messages() {
|
|
|
+ String issueText = issues.isEmpty() ? "" : "问题:" + String.join(";", issues);
|
|
|
+ String warningText = warnings.isEmpty() ? "" : "警告:" + String.join(";", warnings);
|
|
|
+ return issueText + (issueText.isEmpty() || warningText.isEmpty() ? "" : ";") + warningText;
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ private record Inventory(int configuredObjectCount, int ftsCandidateCount, int rootCandidateCount,
|
|
|
+ List<RebuildUnit> units, List<String> globalIssues) {
|
|
|
+ }
|
|
|
+
|
|
|
+ private record EsEnvironment(String clusterName, String clusterUuid, String version,
|
|
|
+ String health, boolean hasIk) {
|
|
|
+ }
|
|
|
+
|
|
|
+ private static final class EsProbe {
|
|
|
+ private final String baseUrl;
|
|
|
+ private final String authorization;
|
|
|
+ private final HttpClient client = HttpClient.newBuilder().build();
|
|
|
+
|
|
|
+ private EsProbe(String baseUrl, String user, String password) {
|
|
|
+ this.baseUrl = baseUrl.replaceAll("/+$", "");
|
|
|
+ this.authorization = "Basic " + Base64.getEncoder().encodeToString(
|
|
|
+ (user + ":" + password).getBytes(StandardCharsets.UTF_8));
|
|
|
+ }
|
|
|
+
|
|
|
+ private EsEnvironment readEnvironment() throws Exception {
|
|
|
+ String info = get("/");
|
|
|
+ String healthResponse = get("/_cluster/health");
|
|
|
+ String plugins = get("/_nodes/plugins?filter_path=nodes.*.plugins.name");
|
|
|
+ return new EsEnvironment(jsonString(info, "cluster_name"), jsonString(info, "cluster_uuid"),
|
|
|
+ jsonString(info, "number"), jsonString(healthResponse, "status"),
|
|
|
+ plugins.toLowerCase(Locale.ROOT).contains("analysis-ik"));
|
|
|
+ }
|
|
|
+
|
|
|
+ private boolean indexExists(String index) throws Exception {
|
|
|
+ HttpRequest request = request("/" + encode(index)).method("HEAD", HttpRequest.BodyPublishers.noBody()).build();
|
|
|
+ HttpResponse<Void> response = client.send(request, HttpResponse.BodyHandlers.discarding());
|
|
|
+ if (response.statusCode() == 404)
|
|
|
+ return false;
|
|
|
+ if (response.statusCode() < 200 || response.statusCode() >= 300)
|
|
|
+ throw new IllegalStateException("HTTP " + response.statusCode() + " checking index " + index);
|
|
|
+ return true;
|
|
|
+ }
|
|
|
+
|
|
|
+ private long indexCount(String index) throws Exception {
|
|
|
+ String response = get("/" + encode(index) + "/_count");
|
|
|
+ return jsonLong(response, "count");
|
|
|
+ }
|
|
|
+
|
|
|
+ private String get(String path) throws Exception {
|
|
|
+ HttpResponse<String> response = client.send(request(path).GET().build(), HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8));
|
|
|
+ if (response.statusCode() < 200 || response.statusCode() >= 300)
|
|
|
+ throw new IllegalStateException("HTTP " + response.statusCode() + " for GET " + path);
|
|
|
+ return response.body();
|
|
|
+ }
|
|
|
+
|
|
|
+ private HttpRequest.Builder request(String path) {
|
|
|
+ return HttpRequest.newBuilder(URI.create(baseUrl + path))
|
|
|
+ .header("Authorization", authorization)
|
|
|
+ .header("Accept", "application/json");
|
|
|
+ }
|
|
|
+
|
|
|
+ private static String encode(String value) {
|
|
|
+ return URLEncoder.encode(value, StandardCharsets.UTF_8).replace("+", "%20");
|
|
|
+ }
|
|
|
+
|
|
|
+ private static String jsonString(String json, String field) {
|
|
|
+ Matcher matcher = Pattern.compile(String.format(JSON_STRING.pattern(), Pattern.quote(field))).matcher(json);
|
|
|
+ return matcher.find() ? matcher.group(1) : "未取得";
|
|
|
+ }
|
|
|
+
|
|
|
+ private static long jsonLong(String json, String field) {
|
|
|
+ Matcher matcher = Pattern.compile(String.format(JSON_NUMBER.pattern(), Pattern.quote(field))).matcher(json);
|
|
|
+ if (!matcher.find())
|
|
|
+ throw new IllegalArgumentException("JSON field not found: " + field);
|
|
|
+ return Long.parseLong(matcher.group(1));
|
|
|
+ }
|
|
|
+ }
|
|
|
+}
|