cmvr-wms/scripts/projectdev/BackupReplayTarget.java

163 lines
12 KiB
Java
Raw Normal View History

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.security.*;
import java.sql.*;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.util.*;
/** Backup only. No database write, cleanup, import, or restore operations exist here. */
public class BackupReplayTarget {
private static final String DATABASE = "cmvr-project-dev";
private static final HexFormat HEX = HexFormat.of();
public static void main(String[] args) throws Exception {
if (args.length != 0) throw new IllegalArgumentException("Backup takes no database override");
Map<String,String> config = new HashMap<>();
boolean master = false;
for (String line : Files.readAllLines(Path.of("ruoyi-admin/src/main/resources/application-druid.yml"))) {
if (line.trim().equals("master:")) { master = true; continue; }
if (line.trim().equals("slave:")) break;
if (master && line.indexOf(':') > 0) {
int colon = line.indexOf(':');
config.put(line.substring(0,colon).trim(), DatabaseTool.value(line.substring(colon+1).trim()));
}
}
String url = config.get("url");
if (url == null || !url.matches("^jdbc:mysql://192\\.168\\.28\\.10:3306/cmvr-project-dev(?:\\?.*)?$"))
throw new IllegalStateException("Refusing a backup outside the named target");
String stamp = ZonedDateTime.now(ZoneId.of("Asia/Shanghai")).format(DateTimeFormatter.ofPattern("yyyyMMdd-HHmmss"));
Path directory = Path.of(".codex-tmp/database-backups", DATABASE + "-" + stamp);
Files.createDirectories(directory);
Path partial = directory.resolve(DATABASE + ".sql.incomplete");
Path complete = directory.resolve(DATABASE + ".sql");
Properties props = new Properties();
props.setProperty("user", config.get("username"));
props.setProperty("password", config.get("password"));
props.setProperty("connectTimeout", "5000");
props.setProperty("socketTimeout", "60000");
props.setProperty("tinyInt1isBit", "false");
Map<String,Object> tables = new LinkedHashMap<>();
List<Map<String,Object>> foreignKeys;
List<String> views, triggers, routines, events;
try (Connection c = DriverManager.getConnection(url, props)) {
c.setReadOnly(true);
c.setAutoCommit(false);
try (Statement s = c.createStatement()) {
s.execute("SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ");
s.execute("START TRANSACTION WITH CONSISTENT SNAPSHOT, READ ONLY");
}
if (!DATABASE.equals(scalar(c,"select database()"))) throw new IllegalStateException("Database mismatch");
List<Map<String,Object>> inventory = records(c,
"select table_name,table_type,engine from information_schema.tables where table_schema=? order by table_name", DATABASE);
for (var table : inventory) if ("BASE TABLE".equals(table.get("TABLE_TYPE")) && !"InnoDB".equalsIgnoreCase(String.valueOf(table.get("ENGINE"))))
throw new IllegalStateException("Nontransactional table requires a separate consistent backup: " + table.get("TABLE_NAME"));
foreignKeys = records(c,"select table_name,column_name,referenced_table_name,referenced_column_name from information_schema.key_column_usage where table_schema=? and referenced_table_name is not null order by table_name,column_name", DATABASE);
views = names(c,"select table_name from information_schema.views where table_schema=? order by table_name",DATABASE);
triggers = names(c,"select trigger_name from information_schema.triggers where trigger_schema=? order by trigger_name",DATABASE);
routines = names(c,"select concat(routine_type,':',routine_name) from information_schema.routines where routine_schema=? order by routine_type,routine_name",DATABASE);
events = names(c,"select event_name from information_schema.events where event_schema=? order by event_name",DATABASE);
try (BufferedWriter out = Files.newBufferedWriter(partial, StandardCharsets.UTF_8, StandardOpenOption.CREATE_NEW)) {
out.write("-- Read-only consistent snapshot backup; restore only into the authorized target.\n");
out.write("-- Created " + stamp + " Asia/Shanghai\nUSE " + id(DATABASE) + ";\nSET NAMES utf8mb4;\nSET @REPLAY_OLD_FK=@@FOREIGN_KEY_CHECKS;\nSET FOREIGN_KEY_CHECKS=0;\n");
for (String view : views) out.write("DROP VIEW IF EXISTS " + id(view) + ";\n");
for (var table : inventory) {
if (!"BASE TABLE".equals(table.get("TABLE_TYPE"))) continue;
String name = String.valueOf(table.get("TABLE_NAME"));
out.write("\nDROP TABLE IF EXISTS " + id(name) + ";\n" + create(c,"TABLE",name) + ";\n");
List<Map<String,Object>> columns = records(c,"select column_name,extra from information_schema.columns where table_schema=? and table_name=? order by ordinal_position",DATABASE,name);
List<String> writable = new ArrayList<>();
for (var column : columns) if (!String.valueOf(column.get("EXTRA")).contains("GENERATED")) writable.add(String.valueOf(column.get("COLUMN_NAME")));
String columnList = String.join(",", writable.stream().map(BackupReplayTarget::id).toList());
long count = 0;
List<String> hashes = new ArrayList<>();
try (Statement s = c.createStatement(); ResultSet rs = s.executeQuery("select " + columnList + " from " + id(name))) {
ResultSetMetaData meta = rs.getMetaData();
while (rs.next()) {
StringJoiner values = new StringJoiner(",");
for (int col=1; col<=meta.getColumnCount(); col++) values.add(literal(rs,meta,col));
String insert = "INSERT INTO " + id(name) + " (" + columnList + ") VALUES (" + values + ");\n";
out.write(insert);
hashes.add(hash(insert.getBytes(StandardCharsets.UTF_8)));
count++;
}
}
Collections.sort(hashes);
tables.put(name, Map.of("rows",count,"rowFingerprint",hash(String.join("\n",hashes).getBytes(StandardCharsets.UTF_8)),"columns",writable));
System.out.println("BACKED UP " + name + " rows=" + count);
}
for (String view : views) out.write("\n" + create(c,"VIEW",view) + ";\n");
for (String trigger : triggers) writeProgram(out,"TRIGGER",trigger,create(c,"TRIGGER",trigger));
for (String routine : routines) {
int split = routine.indexOf(':'); String type = routine.substring(0,split), name = routine.substring(split+1);
writeProgram(out,type,name,create(c,type,name));
}
for (String event : events) writeProgram(out,"EVENT",event,create(c,"EVENT",event));
out.write("SET FOREIGN_KEY_CHECKS=@REPLAY_OLD_FK;\n-- BACKUP COMPLETE\n");
}
c.rollback();
}
// An incomplete read never gets the completion marker or finalized filename.
Files.move(partial,complete,StandardCopyOption.ATOMIC_MOVE);
String checksum;
MessageDigest digest = MessageDigest.getInstance("SHA-256");
try (InputStream in=Files.newInputStream(complete)) { byte[] buffer=new byte[65536]; int n; while((n=in.read(buffer))>0) digest.update(buffer,0,n); }
checksum = HEX.formatHex(digest.digest());
Map<String,Object> manifest = new LinkedHashMap<>();
manifest.put("database",DATABASE);manifest.put("createdAsiaShanghai",stamp);manifest.put("readOnly",true);
manifest.put("complete",true);manifest.put("sqlFile",complete.toAbsolutePath().toString());
manifest.put("bytes",Files.size(complete));manifest.put("sha256",checksum);manifest.put("tables",tables);
manifest.put("views",views);manifest.put("triggers",triggers);manifest.put("routines",routines);manifest.put("events",events);
manifest.put("foreignKeys",foreignKeys);
Files.writeString(directory.resolve("manifest.json"), ReadOnlyDataInventory.json(manifest), StandardCharsets.UTF_8, StandardOpenOption.CREATE_NEW);
Files.writeString(directory.resolve("SHA256.txt"), checksum + " " + complete.getFileName() + "\n", StandardCharsets.US_ASCII, StandardOpenOption.CREATE_NEW);
System.out.println("BACKUP COMPLETE " + complete.toAbsolutePath() + " bytes=" + Files.size(complete) + " sha256=" + checksum);
}
static String id(String value) {
if (!value.matches("[A-Za-z0-9_-]+")) throw new IllegalArgumentException("Unexpected SQL identifier");
return "`" + value + "`";
}
static String hash(byte[] bytes) throws Exception { return HEX.formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); }
static String literal(ResultSet rs, ResultSetMetaData meta, int col) throws Exception {
Object value = rs.getObject(col);
if (value == null) return "NULL";
int type = meta.getColumnType(col);
if (Set.of(Types.TINYINT,Types.SMALLINT,Types.INTEGER,Types.BIGINT,Types.FLOAT,Types.REAL,Types.DOUBLE,Types.NUMERIC,Types.DECIMAL).contains(type)) {
String numeric=rs.getString(col);
if(!numeric.matches("[+-]?[0-9]+(?:\\.[0-9]+)?(?:[eE][+-]?[0-9]+)?"))throw new IllegalStateException("Unexpected number");
return numeric;
}
if (type==Types.BOOLEAN) return rs.getBoolean(col)?"1":"0";
if (value instanceof byte[] || Set.of(Types.BINARY,Types.VARBINARY,Types.LONGVARBINARY,Types.BLOB,Types.BIT).contains(type)) return "X'" + HEX.formatHex(rs.getBytes(col)) + "'";
return "CONVERT(X'" + HEX.formatHex(rs.getString(col).getBytes(StandardCharsets.UTF_8)) + "' USING utf8mb4)";
}
static List<Map<String,Object>> records(Connection c, String sql, Object... args) throws Exception {
try (PreparedStatement s=c.prepareStatement(sql)) {
for(int i=0;i<args.length;i++)s.setObject(i+1,args[i]);
try(ResultSet rs=s.executeQuery()){
List<Map<String,Object>> rows=new ArrayList<>();ResultSetMetaData meta=rs.getMetaData();
while(rs.next()){Map<String,Object> row=new LinkedHashMap<>();for(int col=1;col<=meta.getColumnCount();col++)row.put(meta.getColumnLabel(col).toUpperCase(Locale.ROOT),rs.getObject(col));rows.add(row);}return rows;
}
}
}
static String scalar(Connection c,String sql) throws Exception { try(Statement s=c.createStatement();ResultSet rs=s.executeQuery(sql)){rs.next();return rs.getString(1);} }
private static List<String> names(Connection c,String sql,Object... args) throws Exception { List<String> result=new ArrayList<>();for(var row:records(c,sql,args))result.add(String.valueOf(row.values().iterator().next()));return result; }
private static String create(Connection c,String type,String name) throws Exception {
try(Statement s=c.createStatement();ResultSet rs=s.executeQuery("SHOW CREATE " + type + " " + id(name))){
if(!rs.next())throw new IllegalStateException("Object disappeared during backup");
ResultSetMetaData meta=rs.getMetaData();
for(int i=1;i<=meta.getColumnCount();i++)if(meta.getColumnLabel(i).equalsIgnoreCase("Create "+type)||meta.getColumnLabel(i).equalsIgnoreCase("SQL Original Statement")) {
String ddl=rs.getString(i);if(ddl==null||ddl.isBlank())throw new IllegalStateException("Cannot read full object definition");return ddl;
}
throw new IllegalStateException("Missing full definition: " + type + " " + name);
}
}
private static void writeProgram(BufferedWriter out,String type,String name,String ddl) throws Exception {
String delimiter="$$BACKUP_END$$";
if(ddl.contains(delimiter))throw new IllegalStateException("Delimiter collision");
out.write("\nDROP " + type + " IF EXISTS " + id(name) + ";\nDELIMITER " + delimiter + "\n" + ddl + delimiter + "\nDELIMITER ;\n");
}
}