2023-04-08 13:08:37 +00:00
|
|
|
require('require-yaml');
|
|
|
|
require('colors');
|
|
|
|
const fs = require('fs');
|
|
|
|
const path = require('path');
|
|
|
|
const ZongJi = require('./zongji');
|
|
|
|
const mysql = require('mysql2/promise');
|
|
|
|
|
|
|
|
module.exports = class MyLogger {
|
|
|
|
constructor() {
|
|
|
|
this.running = false;
|
2023-04-10 11:56:06 +00:00
|
|
|
this.isOk = null;
|
2023-04-10 09:03:26 +00:00
|
|
|
this.binlogName = null;
|
|
|
|
this.binlogPosition = null;
|
2023-04-08 13:08:37 +00:00
|
|
|
this.schemaMap = new Map();
|
|
|
|
this.logMap = new Map();
|
2023-04-10 09:03:26 +00:00
|
|
|
this.isFlushed = true;
|
|
|
|
this.queue = [];
|
2023-04-08 13:08:37 +00:00
|
|
|
}
|
|
|
|
|
2023-05-30 18:09:05 +00:00
|
|
|
loadConfig(configName) {
|
|
|
|
const defaultConfig = require(`./config/${configName}.yml`);
|
|
|
|
const conf = Object.assign({}, defaultConfig);
|
|
|
|
const localPath = path.join(__dirname, 'config', `${configName}.local.yml`);
|
2023-04-08 13:08:37 +00:00
|
|
|
if (fs.existsSync(localPath)) {
|
|
|
|
const localConfig = require(localPath);
|
|
|
|
Object.assign(conf, localConfig);
|
|
|
|
}
|
2023-05-30 18:09:05 +00:00
|
|
|
return conf;
|
|
|
|
}
|
|
|
|
|
|
|
|
async start() {
|
|
|
|
this.conf = this.loadConfig('config');
|
|
|
|
this.logsConf = this.loadConfig('logs');
|
|
|
|
const {conf, logsConf} = this;
|
2023-04-08 13:08:37 +00:00
|
|
|
|
2023-05-09 15:33:18 +00:00
|
|
|
function parseTable(tableString, defaultSchema) {
|
2023-04-08 13:08:37 +00:00
|
|
|
let name, schema;
|
|
|
|
const split = tableString.split('.');
|
|
|
|
if (split.length == 1) {
|
|
|
|
name = split[0];
|
|
|
|
schema = defaultSchema;
|
|
|
|
} else {
|
2023-05-09 15:33:18 +00:00
|
|
|
[schema, name] = split;
|
2023-04-08 13:08:37 +00:00
|
|
|
}
|
|
|
|
return {name, schema};
|
|
|
|
}
|
|
|
|
|
|
|
|
const schemaMap = this.schemaMap;
|
|
|
|
function addTable(tableConf, logInfo) {
|
|
|
|
if (typeof tableConf == 'string')
|
2023-05-09 15:33:18 +00:00
|
|
|
tableConf = {name: tableConf};
|
|
|
|
const table = parseTable(tableConf.name, logInfo.schema);
|
2023-04-08 13:08:37 +00:00
|
|
|
|
|
|
|
let tableMap = schemaMap.get(table.schema);
|
|
|
|
if (!tableMap) {
|
|
|
|
tableMap = new Map();
|
|
|
|
schemaMap.set(table.schema, tableMap);
|
|
|
|
}
|
|
|
|
|
|
|
|
let tableInfo = tableMap.get(table.name);
|
|
|
|
if (!tableInfo) {
|
|
|
|
tableInfo = {
|
|
|
|
conf: tableConf,
|
|
|
|
log: logInfo
|
|
|
|
};
|
|
|
|
tableMap.set(table.name, tableInfo);
|
|
|
|
}
|
|
|
|
|
2023-05-30 18:09:05 +00:00
|
|
|
const modelName = logsConf.upperCaseTable
|
2023-04-11 08:15:06 +00:00
|
|
|
? toUpperCamelCase(table.name)
|
|
|
|
: table.name;
|
|
|
|
|
2023-04-12 16:57:15 +00:00
|
|
|
const {
|
|
|
|
showField,
|
|
|
|
relation,
|
|
|
|
idName
|
|
|
|
} = tableConf;
|
|
|
|
|
2023-04-08 13:08:37 +00:00
|
|
|
Object.assign(tableInfo, {
|
|
|
|
conf: tableConf,
|
2023-04-11 08:15:06 +00:00
|
|
|
exclude: new Set(tableConf.exclude),
|
2023-04-12 16:57:15 +00:00
|
|
|
modelName,
|
|
|
|
showField,
|
|
|
|
relation,
|
|
|
|
idName,
|
2023-05-30 18:09:05 +00:00
|
|
|
userField: tableConf.userField || logsConf.userField
|
2023-04-08 13:08:37 +00:00
|
|
|
});
|
|
|
|
|
|
|
|
return tableInfo;
|
|
|
|
}
|
|
|
|
|
2023-05-30 18:09:05 +00:00
|
|
|
for (const logName in logsConf.logs) {
|
|
|
|
const logConf = logsConf.logs[logName];
|
2023-05-09 15:33:18 +00:00
|
|
|
const schema = logConf.schema || conf.srcDb.database;
|
2023-04-08 13:08:37 +00:00
|
|
|
const logInfo = {
|
2023-05-21 12:16:01 +00:00
|
|
|
name: logName,
|
2023-04-08 13:08:37 +00:00
|
|
|
conf: logConf,
|
2023-05-09 15:33:18 +00:00
|
|
|
schema,
|
|
|
|
table: parseTable(logConf.logTable, schema),
|
|
|
|
mainTable: parseTable(logConf.mainTable, schema)
|
2023-04-08 13:08:37 +00:00
|
|
|
};
|
|
|
|
this.logMap.set(logName, logInfo);
|
|
|
|
|
2023-05-09 15:33:18 +00:00
|
|
|
const mainTable = addTable(logConf.mainTable, logInfo);
|
2023-04-08 13:08:37 +00:00
|
|
|
mainTable.isMain = true;
|
|
|
|
|
|
|
|
if (logConf.tables)
|
|
|
|
for (const tableConf of logConf.tables){
|
|
|
|
const table = addTable(tableConf, logInfo);
|
|
|
|
if (table !== mainTable) {
|
|
|
|
Object.assign(table, {
|
|
|
|
main: mainTable,
|
|
|
|
isMain: false
|
|
|
|
});
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
const includeSchema = {};
|
|
|
|
for (const [schemaName, tableMap] of this.schemaMap)
|
|
|
|
includeSchema[schemaName] = Array.from(tableMap.keys());
|
|
|
|
|
2023-05-21 12:16:01 +00:00
|
|
|
this.zongjiOpts = {
|
2023-04-08 13:08:37 +00:00
|
|
|
includeEvents: [
|
|
|
|
'rotate',
|
|
|
|
'tablemap',
|
|
|
|
'writerows',
|
|
|
|
'updaterows',
|
|
|
|
'deleterows'
|
|
|
|
],
|
2023-04-25 16:42:21 +00:00
|
|
|
includeSchema,
|
|
|
|
serverId: conf.serverId
|
2023-04-08 13:08:37 +00:00
|
|
|
};
|
|
|
|
|
|
|
|
if (conf.testMode)
|
|
|
|
console.log('Test mode enabled, just logging queries to console.');
|
|
|
|
|
|
|
|
console.log('Starting process.');
|
|
|
|
await this.init();
|
|
|
|
console.log('Process started.');
|
|
|
|
}
|
|
|
|
|
|
|
|
async stop() {
|
|
|
|
console.log('Stopping process.');
|
|
|
|
await this.end();
|
|
|
|
console.log('Process stopped.');
|
|
|
|
}
|
|
|
|
|
|
|
|
async init() {
|
2023-05-30 18:09:05 +00:00
|
|
|
const {conf, logsConf} = this;
|
2023-04-08 13:08:37 +00:00
|
|
|
this.debug('MyLogger', 'Initializing.');
|
|
|
|
this.onErrorListener = err => this.onError(err);
|
|
|
|
|
|
|
|
// DB connection
|
|
|
|
|
2023-04-10 09:03:26 +00:00
|
|
|
const db = this.db = await mysql.createConnection(conf.dstDb);
|
2023-04-08 13:08:37 +00:00
|
|
|
db.on('error', this.onErrorListener);
|
|
|
|
|
|
|
|
for (const logInfo of this.logMap.values()) {
|
|
|
|
const table = logInfo.table;
|
|
|
|
const sqlTable = `${db.escapeId(table.schema)}.${db.escapeId(table.name)}`
|
|
|
|
logInfo.addStmt = await db.prepare(
|
|
|
|
`INSERT INTO ${sqlTable}
|
|
|
|
SET originFk = ?,
|
|
|
|
userFk = ?,
|
|
|
|
action = ?,
|
|
|
|
creationDate = ?,
|
|
|
|
changedModel = ?,
|
|
|
|
oldInstance = ?,
|
|
|
|
newInstance = ?,
|
|
|
|
changedModelId = ?,
|
|
|
|
changedModelValue = ?`
|
|
|
|
);
|
|
|
|
logInfo.fetchStmt = await db.prepare(
|
|
|
|
`SELECT id FROM ${sqlTable}
|
|
|
|
WHERE changedModel = ?
|
|
|
|
AND changedModelId = ?
|
2023-05-13 12:25:50 +00:00
|
|
|
AND action = 'delete'
|
|
|
|
AND (originFk IS NULL OR originFk = ?)
|
|
|
|
LIMIT 1`
|
2023-04-08 13:08:37 +00:00
|
|
|
);
|
|
|
|
logInfo.updateStmt = await db.prepare(
|
|
|
|
`UPDATE ${sqlTable}
|
|
|
|
SET originFk = ?,
|
|
|
|
creationDate = ?,
|
|
|
|
oldInstance = ?,
|
|
|
|
changedModelValue = ?
|
|
|
|
WHERE id = ?`
|
|
|
|
);
|
|
|
|
}
|
|
|
|
|
|
|
|
for (const [schema, tableMap] of this.schemaMap)
|
|
|
|
for (const [table, tableInfo] of tableMap) {
|
2023-04-10 11:56:06 +00:00
|
|
|
const tableConf = tableInfo.conf;
|
2023-04-08 13:08:37 +00:00
|
|
|
|
|
|
|
// Fetch columns & types
|
|
|
|
|
2023-04-10 11:56:06 +00:00
|
|
|
Object.assign (tableInfo, {
|
|
|
|
castTypes: new Map(),
|
|
|
|
columns: new Map()
|
|
|
|
});
|
|
|
|
|
|
|
|
if (tableConf.types)
|
|
|
|
for (const col in tableConf.types)
|
|
|
|
tableInfo.castTypes.set(col, tableConf.types[col]);
|
|
|
|
|
2023-04-08 13:08:37 +00:00
|
|
|
const [dbCols] = await db.query(
|
2023-05-30 18:09:05 +00:00
|
|
|
`SELECT
|
|
|
|
COLUMN_NAME \`col\`,
|
|
|
|
DATA_TYPE \`type\`,
|
|
|
|
COLUMN_DEFAULT \`def\`
|
2023-04-08 13:08:37 +00:00
|
|
|
FROM information_schema.\`COLUMNS\`
|
|
|
|
WHERE TABLE_NAME = ? AND TABLE_SCHEMA = ?`,
|
|
|
|
[table, schema]
|
|
|
|
);
|
|
|
|
|
|
|
|
for (const {col, type, def} of dbCols) {
|
2023-04-13 16:31:43 +00:00
|
|
|
if (!tableInfo.exclude.has(col) && col != tableInfo.userField)
|
2023-04-08 13:08:37 +00:00
|
|
|
tableInfo.columns.set(col, {type, def});
|
|
|
|
|
2023-05-30 18:09:05 +00:00
|
|
|
const castType = logsConf.castTypes[type];
|
2023-04-08 13:08:37 +00:00
|
|
|
if (castType && !tableInfo.castTypes.has(col))
|
|
|
|
tableInfo.castTypes.set(col, castType);
|
|
|
|
}
|
|
|
|
|
|
|
|
// Fetch primary key
|
|
|
|
|
2023-04-12 16:57:15 +00:00
|
|
|
if (!tableConf.idName) {
|
|
|
|
const [dbPks] = await db.query(
|
|
|
|
`SELECT COLUMN_NAME idName
|
|
|
|
FROM information_schema.KEY_COLUMN_USAGE
|
|
|
|
WHERE CONSTRAINT_NAME = 'PRIMARY'
|
|
|
|
AND TABLE_NAME = ?
|
|
|
|
AND TABLE_SCHEMA = ?`,
|
|
|
|
[table, schema]
|
|
|
|
);
|
|
|
|
|
|
|
|
if (!dbPks.length)
|
|
|
|
throw new Error(`Primary not found for table: ${schema}.${table}`);
|
|
|
|
if (dbPks.length > 1)
|
|
|
|
throw new Error(`Only one column primary is supported: ${schema}.${table}`);
|
|
|
|
|
|
|
|
for (const {idName} of dbPks)
|
|
|
|
tableInfo.idName = idName;
|
|
|
|
}
|
2023-04-08 13:08:37 +00:00
|
|
|
|
|
|
|
// Get show field
|
|
|
|
|
2023-04-10 11:56:06 +00:00
|
|
|
if (!tableConf.showField) {
|
2023-05-30 18:09:05 +00:00
|
|
|
for (const showField of logsConf.showFields) {
|
2023-04-08 13:08:37 +00:00
|
|
|
if (tableInfo.columns.has(showField)) {
|
|
|
|
tableInfo.showField = showField;
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-05-30 18:09:05 +00:00
|
|
|
const showValues = new Map();
|
|
|
|
|
2023-04-08 13:08:37 +00:00
|
|
|
for (const [schema, tableMap] of this.schemaMap)
|
|
|
|
for (const [table, tableInfo] of tableMap) {
|
|
|
|
|
2023-04-11 08:15:06 +00:00
|
|
|
// Fetch relation to main table
|
2023-04-08 13:08:37 +00:00
|
|
|
|
2023-04-10 11:56:06 +00:00
|
|
|
if (!tableInfo.conf.relation && !tableInfo.isMain) {
|
2023-04-08 13:08:37 +00:00
|
|
|
const mainTable = tableInfo.log.mainTable;
|
|
|
|
const mainTableInfo = this.schemaMap
|
|
|
|
.get(mainTable.schema)
|
|
|
|
.get(mainTable.name);
|
|
|
|
|
2023-04-11 08:15:06 +00:00
|
|
|
const [mainRelations] = await db.query(
|
2023-04-08 13:08:37 +00:00
|
|
|
`SELECT COLUMN_NAME relation
|
|
|
|
FROM information_schema.KEY_COLUMN_USAGE
|
|
|
|
WHERE TABLE_NAME = ?
|
|
|
|
AND TABLE_SCHEMA = ?
|
|
|
|
AND REFERENCED_TABLE_NAME = ?
|
|
|
|
AND REFERENCED_TABLE_SCHEMA = ?
|
|
|
|
AND REFERENCED_COLUMN_NAME = ?`,
|
|
|
|
[
|
|
|
|
table,
|
|
|
|
schema,
|
|
|
|
mainTable.name,
|
|
|
|
mainTable.schema,
|
|
|
|
mainTableInfo.idName
|
|
|
|
]
|
|
|
|
);
|
|
|
|
|
2023-04-11 08:15:06 +00:00
|
|
|
if (!mainRelations.length)
|
2023-04-08 13:08:37 +00:00
|
|
|
throw new Error(`No relation to main table found for table: ${schema}.${table}`);
|
2023-04-11 08:15:06 +00:00
|
|
|
if (mainRelations.length > 1)
|
2023-04-08 13:08:37 +00:00
|
|
|
throw new Error(`Found more multiple relations to main table: ${schema}.${table}`);
|
|
|
|
|
2023-04-11 08:15:06 +00:00
|
|
|
for (const {relation} of mainRelations)
|
2023-04-08 13:08:37 +00:00
|
|
|
tableInfo.relation = relation;
|
|
|
|
}
|
2023-04-11 08:15:06 +00:00
|
|
|
|
|
|
|
// Fetch relations
|
|
|
|
// TODO: Use relations to fetch names of related entities
|
|
|
|
|
|
|
|
const [relations] = await db.query(
|
|
|
|
`SELECT
|
|
|
|
COLUMN_NAME \`col\`,
|
|
|
|
REFERENCED_TABLE_SCHEMA \`schema\`,
|
|
|
|
REFERENCED_TABLE_NAME \`table\`,
|
|
|
|
REFERENCED_COLUMN_NAME \`column\`
|
|
|
|
FROM information_schema.KEY_COLUMN_USAGE
|
|
|
|
WHERE TABLE_NAME = ?
|
|
|
|
AND TABLE_SCHEMA = ?
|
|
|
|
AND REFERENCED_TABLE_NAME IS NOT NULL`,
|
2023-05-30 18:09:05 +00:00
|
|
|
[table, schema]
|
2023-04-11 08:15:06 +00:00
|
|
|
);
|
|
|
|
|
|
|
|
tableInfo.relations = new Map();
|
2023-05-30 18:09:05 +00:00
|
|
|
for (const {col, schema, table, column} of relations) {
|
2023-04-11 08:15:06 +00:00
|
|
|
tableInfo.relations.set(col, {schema, table, column});
|
2023-05-30 18:09:05 +00:00
|
|
|
|
|
|
|
let tables = showValues.get(schema);
|
|
|
|
if (!tables) {
|
|
|
|
tables = new Map();
|
|
|
|
showValues.set(schema, tables);
|
|
|
|
}
|
|
|
|
if (!tables.get(table)) tables.set(table, null);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
const showTables = [];
|
|
|
|
const showFields = logsConf.showFields;
|
|
|
|
|
|
|
|
for (const [schema, tableMap] of showValues)
|
|
|
|
for (const [table] of tableMap)
|
|
|
|
showTables.push([table, schema]);
|
|
|
|
|
|
|
|
const [result] = await db.query(
|
|
|
|
`SELECT
|
|
|
|
TABLE_NAME \`table\`,
|
|
|
|
TABLE_SCHEMA \`schema\`,
|
|
|
|
COLUMN_NAME \`col\`
|
|
|
|
FROM information_schema.\`COLUMNS\`
|
|
|
|
WHERE (TABLE_NAME, TABLE_SCHEMA) IN (?)
|
|
|
|
AND COLUMN_NAME IN (?)`,
|
|
|
|
[showTables, showFields]
|
|
|
|
);
|
|
|
|
|
|
|
|
for (const row of result) {
|
|
|
|
const tables = showValues.get(row.schema);
|
|
|
|
const showField = tables.get(row.table);
|
|
|
|
|
|
|
|
let save;
|
|
|
|
if (showField != null) {
|
|
|
|
const newIndex = showFields.indexOf(row.col);
|
|
|
|
const oldIndex = showFields.indexOf(showField);
|
|
|
|
save = newIndex < oldIndex;
|
|
|
|
} else
|
|
|
|
save = true;
|
|
|
|
|
|
|
|
if (save)
|
|
|
|
tables.set(row.table, row.col);
|
2023-04-08 13:08:37 +00:00
|
|
|
}
|
|
|
|
|
2023-05-30 18:09:05 +00:00
|
|
|
// TODO: End
|
|
|
|
|
2023-04-08 13:08:37 +00:00
|
|
|
// Zongji
|
|
|
|
|
|
|
|
this.onBinlogListener = evt => this.onBinlog(evt);
|
|
|
|
|
|
|
|
const [res] = await db.query(
|
|
|
|
'SELECT `logName`, `position` FROM `util`.`binlogQueue` WHERE code = ?',
|
|
|
|
[conf.code]
|
|
|
|
);
|
|
|
|
if (res.length) {
|
|
|
|
const [row] = res;
|
2023-04-10 09:03:26 +00:00
|
|
|
this.binlogName = row.logName;
|
|
|
|
this.binlogPosition = row.position;
|
2023-05-21 12:16:01 +00:00
|
|
|
}
|
2023-04-08 13:08:37 +00:00
|
|
|
|
2023-05-21 12:16:01 +00:00
|
|
|
await this.zongjiStart();
|
2023-04-08 13:08:37 +00:00
|
|
|
|
|
|
|
this.flushInterval = setInterval(
|
|
|
|
() => this.flushQueue(), conf.flushInterval * 1000);
|
|
|
|
this.pingInterval = setInterval(
|
|
|
|
() => this.connectionPing(), conf.pingInterval * 1000);
|
|
|
|
|
|
|
|
// Summary
|
|
|
|
|
|
|
|
this.running = true;
|
2023-04-10 11:56:06 +00:00
|
|
|
this.isOk = true;
|
2023-04-08 13:08:37 +00:00
|
|
|
this.debug('MyLogger', 'Initialized.');
|
|
|
|
}
|
|
|
|
|
|
|
|
async end(silent) {
|
2023-04-10 11:56:06 +00:00
|
|
|
if (!this.running) return;
|
|
|
|
this.running = false;
|
2023-04-08 13:08:37 +00:00
|
|
|
this.debug('MyLogger', 'Ending.');
|
2023-04-10 11:56:06 +00:00
|
|
|
|
|
|
|
this.db.off('error', this.onErrorListener);
|
2023-04-08 13:08:37 +00:00
|
|
|
|
|
|
|
clearInterval(this.flushInterval);
|
|
|
|
clearInterval(this.pingInterval);
|
2023-04-10 09:03:26 +00:00
|
|
|
clearInterval(this.flushTimeout);
|
|
|
|
|
2023-04-10 11:56:06 +00:00
|
|
|
function logError(err) {
|
|
|
|
if (!silent) console.error(err);
|
|
|
|
}
|
|
|
|
|
|
|
|
try {
|
|
|
|
await this.flushQueue();
|
|
|
|
} catch (err) {
|
|
|
|
logError(err);
|
|
|
|
}
|
|
|
|
|
|
|
|
// Zongji
|
|
|
|
|
2023-05-21 12:16:01 +00:00
|
|
|
await this.zongjiStop();
|
|
|
|
this.zongji = null;
|
|
|
|
|
|
|
|
// DB connection
|
|
|
|
|
|
|
|
// FIXME: mysql2/promise bug, db.end() ends process
|
|
|
|
this.db.on('error', () => {});
|
|
|
|
try {
|
|
|
|
this.db.end();
|
|
|
|
} catch (err) {
|
|
|
|
logError(err);
|
|
|
|
}
|
|
|
|
|
|
|
|
// Summary
|
|
|
|
|
|
|
|
this.debug('MyLogger', 'Ended.');
|
|
|
|
}
|
|
|
|
|
|
|
|
async zongjiStart() {
|
|
|
|
await this.zongjiStop();
|
|
|
|
const zongji = new ZongJi(this.conf.srcDb);
|
|
|
|
const zongjiOpts = this.zongjiOpts;
|
|
|
|
|
|
|
|
if (this.binlogName) {
|
|
|
|
this.debug('Zongji',
|
|
|
|
`Starting: ${this.binlogName}, position: ${this.binlogPosition}`
|
|
|
|
);
|
|
|
|
Object.assign(zongjiOpts, {
|
|
|
|
filename: this.binlogName,
|
|
|
|
position: this.binlogPosition
|
|
|
|
});
|
|
|
|
} else {
|
|
|
|
this.debug('Zongji', 'Starting at end.');
|
|
|
|
zongjiOpts.startAtEnd = true;
|
|
|
|
}
|
|
|
|
|
|
|
|
zongji.on('binlog', this.onBinlogListener);
|
|
|
|
|
|
|
|
await new Promise((resolve, reject) => {
|
|
|
|
const onReady = () => {
|
|
|
|
zongji.off('error', onError);
|
|
|
|
resolve();
|
|
|
|
};
|
|
|
|
const onError = err => {
|
|
|
|
zongji.off('ready', onReady);
|
|
|
|
zongji.off('binlog', this.onBinlogListener);
|
|
|
|
reject(err);
|
|
|
|
}
|
|
|
|
|
|
|
|
zongji.once('ready', onReady);
|
|
|
|
zongji.once('error', onError);
|
|
|
|
zongji.start(zongjiOpts);
|
|
|
|
});
|
|
|
|
zongji.on('error', this.onErrorListener);
|
|
|
|
this.zongji = zongji;
|
|
|
|
this.debug('Zongji', 'Started.');
|
|
|
|
}
|
|
|
|
|
|
|
|
async zongjiStop() {
|
|
|
|
if (!this.zongji) return;
|
|
|
|
this.debug('Zongji',
|
|
|
|
`Stopping: ${this.binlogName}, position: ${this.binlogPosition}`
|
|
|
|
);
|
2023-04-10 11:56:06 +00:00
|
|
|
const zongji = this.zongji;
|
2023-05-21 12:16:01 +00:00
|
|
|
this.zongji = null;
|
|
|
|
|
2023-04-08 13:08:37 +00:00
|
|
|
zongji.off('binlog', this.onBinlogListener);
|
|
|
|
zongji.off('error', this.onErrorListener);
|
|
|
|
|
|
|
|
// FIXME: Cannot call Zongji.stop(), it doesn't wait to end connection
|
|
|
|
zongji.connection.destroy(() => {
|
|
|
|
console.log('zongji.connection.destroy');
|
|
|
|
});
|
|
|
|
await new Promise(resolve => {
|
|
|
|
zongji.ctrlConnection.query('KILL ?', [zongji.connection.threadId],
|
|
|
|
err => {
|
2023-04-10 11:56:06 +00:00
|
|
|
if (err && err.code !== 'ER_NO_SUCH_THREAD')
|
|
|
|
logError(err);
|
2023-04-08 13:08:37 +00:00
|
|
|
resolve();
|
|
|
|
});
|
|
|
|
});
|
|
|
|
zongji.ctrlConnection.destroy(() => {
|
|
|
|
console.log('zongji.ctrlConnection.destroy');
|
|
|
|
});
|
|
|
|
zongji.emit('stopped');
|
|
|
|
this.debug('Zongji', 'Stopped.');
|
|
|
|
}
|
|
|
|
|
|
|
|
async tryRestart() {
|
|
|
|
try {
|
|
|
|
await this.init();
|
|
|
|
console.log('Process restarted.');
|
|
|
|
} catch(err) {
|
2023-04-10 11:56:06 +00:00
|
|
|
setTimeout(() => this.tryRestart(), this.conf.restartTimeout * 1000);
|
2023-04-08 13:08:37 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
async onError(err) {
|
2023-04-10 11:56:06 +00:00
|
|
|
if (!this.isOk) return;
|
|
|
|
this.isOk = false;
|
2023-04-08 13:08:37 +00:00
|
|
|
console.log(`Error: ${err.code}: ${err.message}`);
|
2023-04-10 11:56:06 +00:00
|
|
|
|
2023-04-08 13:08:37 +00:00
|
|
|
try {
|
|
|
|
await this.end(true);
|
|
|
|
} catch(e) {}
|
|
|
|
|
|
|
|
switch (err.code) {
|
|
|
|
case 'PROTOCOL_CONNECTION_LOST':
|
|
|
|
case 'ECONNRESET':
|
|
|
|
console.log('Trying to restart process.');
|
|
|
|
await this.tryRestart();
|
|
|
|
break;
|
|
|
|
default:
|
|
|
|
process.exit();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-04-11 08:15:06 +00:00
|
|
|
handleError(err) {
|
|
|
|
console.error(err);
|
|
|
|
}
|
|
|
|
|
2023-04-10 09:03:26 +00:00
|
|
|
async onBinlog(evt) {
|
2023-04-08 13:08:37 +00:00
|
|
|
//evt.dump();
|
2023-04-10 09:03:26 +00:00
|
|
|
try {
|
|
|
|
let shouldFlush;
|
|
|
|
const eventName = evt.getEventName();
|
|
|
|
|
|
|
|
if (eventName == 'rotate') {
|
|
|
|
if (evt.binlogName !== this.binlogName) {
|
|
|
|
shouldFlush = true;
|
|
|
|
this.binlogName = evt.binlogName;
|
|
|
|
this.binlogPosition = evt.position;
|
|
|
|
console.log(
|
|
|
|
`[${eventName}] filename: ${this.binlogName}`,
|
|
|
|
`position: ${this.binlogPosition}`
|
|
|
|
);
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
shouldFlush = true;
|
|
|
|
this.binlogPosition = evt.nextPosition;
|
|
|
|
if (catchEvents.has(eventName))
|
|
|
|
this.onRowEvent(evt, eventName);
|
|
|
|
}
|
2023-04-08 13:08:37 +00:00
|
|
|
|
2023-04-10 09:03:26 +00:00
|
|
|
if (shouldFlush) this.isFlushed = false;
|
2023-05-21 12:16:01 +00:00
|
|
|
|
|
|
|
if (this.queue.length > this.conf.maxQueueEvents) {
|
|
|
|
this.debug('MyLogger', 'Queue full, stopping Zongji.');
|
|
|
|
await this.zongjiStop();
|
|
|
|
}
|
2023-04-10 09:03:26 +00:00
|
|
|
} catch(err) {
|
|
|
|
this.handleError(err);
|
|
|
|
}
|
2023-04-08 13:08:37 +00:00
|
|
|
}
|
|
|
|
|
2023-04-10 09:03:26 +00:00
|
|
|
onRowEvent(evt, eventName) {
|
2023-04-08 13:08:37 +00:00
|
|
|
const table = evt.tableMap[evt.tableId];
|
|
|
|
const tableName = table.tableName;
|
|
|
|
const tableMap = this.schemaMap.get(table.parentSchema);
|
|
|
|
if (!tableMap) return;
|
|
|
|
|
|
|
|
const tableInfo = tableMap.get(tableName);
|
|
|
|
if (!tableInfo) return;
|
|
|
|
|
|
|
|
const action = actions[eventName];
|
|
|
|
const columns = tableInfo.columns;
|
|
|
|
let changes = [];
|
|
|
|
|
|
|
|
function castValue(col, value) {
|
|
|
|
switch(tableInfo.castTypes.get(col)) {
|
|
|
|
case 'boolean':
|
|
|
|
return !!value;
|
|
|
|
default:
|
|
|
|
return value;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-05-30 18:09:05 +00:00
|
|
|
function equals(a, b) {
|
|
|
|
if (a === b)
|
|
|
|
return true;
|
|
|
|
const type = typeof a;
|
|
|
|
if (a == null || b == null || type !== typeof b)
|
|
|
|
return false;
|
|
|
|
if (type === 'object' && a.constructor === b.constructor) {
|
|
|
|
if (a instanceof Date) {
|
|
|
|
// FIXME: zongji creates invalid dates for NULL DATE
|
|
|
|
// Error is somewhere here: zongji/lib/rows_event.js:129
|
|
|
|
let aTime = a.getTime();
|
|
|
|
if (isNaN(aTime)) aTime = null;
|
|
|
|
let bTime = b.getTime();
|
|
|
|
if (isNaN(bTime)) bTime = null;
|
|
|
|
|
|
|
|
return aTime === bTime;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
2023-04-08 13:08:37 +00:00
|
|
|
if (action == 'update') {
|
|
|
|
for (const row of evt.rows) {
|
|
|
|
let nColsChanged = 0;
|
|
|
|
const before = row.before;
|
|
|
|
const after = row.after;
|
|
|
|
const oldI = {};
|
|
|
|
const newI = {};
|
|
|
|
|
|
|
|
for (const col in before) {
|
|
|
|
if (columns.has(col)
|
|
|
|
&& !equals(after[col], before[col])) {
|
|
|
|
if (before[col] !== null)
|
|
|
|
oldI[col] = castValue(col, before[col]);
|
|
|
|
newI[col] = castValue(col, after[col]);
|
|
|
|
nColsChanged++;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if (nColsChanged)
|
|
|
|
changes.push({row: after, oldI, newI});
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
const cols = columns.keys();
|
|
|
|
|
|
|
|
for (const row of evt.rows) {
|
|
|
|
const instance = {};
|
|
|
|
for (const col of cols) {
|
|
|
|
if (row[col] !== null)
|
|
|
|
instance[col] = castValue(col, row[col]);
|
|
|
|
}
|
|
|
|
changes.push({row, instance});
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
if (!changes.length) return;
|
|
|
|
|
2023-04-10 09:03:26 +00:00
|
|
|
this.queue.push({
|
|
|
|
tableInfo,
|
|
|
|
action,
|
|
|
|
evt,
|
|
|
|
changes,
|
|
|
|
binlogName: this.binlogName
|
|
|
|
});
|
2023-05-21 12:16:01 +00:00
|
|
|
|
2023-04-10 09:03:26 +00:00
|
|
|
if (!this.flushTimeout)
|
|
|
|
this.flushTimeout = setTimeout(
|
|
|
|
() => this.flushQueue(),
|
|
|
|
this.conf.queueFlushDelay
|
|
|
|
);
|
2023-05-21 12:16:01 +00:00
|
|
|
|
|
|
|
if (this.conf.debug)
|
|
|
|
console.debug('Evt:'.blue,
|
|
|
|
`[${action}]`[actionColor[action]],
|
|
|
|
`${tableName}: ${changes.length} changes, queue: ${this.queue.length} elements`
|
|
|
|
);
|
2023-04-10 09:03:26 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
async flushQueue() {
|
2023-04-10 11:56:06 +00:00
|
|
|
if (this.isFlushed || this.isFlushing || !this.isOk) return;
|
2023-04-10 09:03:26 +00:00
|
|
|
this.isFlushing = true;
|
2023-04-30 11:09:42 +00:00
|
|
|
const {conf, db, queue} = this;
|
2023-04-11 08:15:06 +00:00
|
|
|
let op;
|
2023-04-10 09:03:26 +00:00
|
|
|
|
|
|
|
try {
|
2023-04-30 11:09:42 +00:00
|
|
|
if (queue.length) {
|
2023-04-10 09:03:26 +00:00
|
|
|
do {
|
2023-04-30 11:09:42 +00:00
|
|
|
const ops = [];
|
|
|
|
let txStarted;
|
2023-04-10 09:03:26 +00:00
|
|
|
try {
|
|
|
|
await db.query('START TRANSACTION');
|
2023-04-30 11:09:42 +00:00
|
|
|
txStarted = true;
|
2023-04-10 09:03:26 +00:00
|
|
|
|
2023-04-30 11:09:42 +00:00
|
|
|
for (let i = 0; i < conf.maxBulkLog && queue.length; i++) {
|
|
|
|
op = queue.shift();
|
|
|
|
ops.push(op);
|
2023-04-10 09:03:26 +00:00
|
|
|
await this.applyOp(op);
|
|
|
|
}
|
|
|
|
|
2023-04-30 11:09:42 +00:00
|
|
|
this.debug('Queue', `applied: ${ops.length}, remaining: ${queue.length}`);
|
2023-04-10 09:03:26 +00:00
|
|
|
await this.savePosition(op.binlogName, op.evt.nextPosition)
|
|
|
|
await db.query('COMMIT');
|
|
|
|
} catch(err) {
|
2023-04-30 11:09:42 +00:00
|
|
|
queue.unshift(...ops);
|
|
|
|
if (txStarted)
|
|
|
|
try {
|
|
|
|
await db.query('ROLLBACK');
|
|
|
|
} catch (err) {}
|
2023-04-10 09:03:26 +00:00
|
|
|
throw err;
|
|
|
|
}
|
2023-04-30 11:09:42 +00:00
|
|
|
} while (queue.length);
|
2023-05-21 12:16:01 +00:00
|
|
|
|
|
|
|
if (!this.zongji) {
|
|
|
|
this.debug('MyLogger', 'Queue flushed, restarting Zongji.');
|
|
|
|
await this.zongjiStart();
|
|
|
|
}
|
2023-04-10 09:03:26 +00:00
|
|
|
} else {
|
|
|
|
await this.savePosition(this.binlogName, this.binlogPosition);
|
|
|
|
}
|
|
|
|
} catch(err) {
|
|
|
|
this.handleError(err);
|
|
|
|
} finally {
|
|
|
|
this.flushTimeout = null;
|
|
|
|
this.isFlushing = false;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
async applyOp(op) {
|
2023-05-21 12:16:01 +00:00
|
|
|
const {conf} = this;
|
2023-04-10 09:03:26 +00:00
|
|
|
const {
|
|
|
|
tableInfo,
|
|
|
|
action,
|
|
|
|
evt,
|
2023-04-11 08:15:06 +00:00
|
|
|
changes
|
2023-04-10 09:03:26 +00:00
|
|
|
} = op;
|
|
|
|
|
2023-04-08 13:08:37 +00:00
|
|
|
const logInfo = tableInfo.log;
|
|
|
|
const isDelete = action == 'delete';
|
2023-05-30 18:09:05 +00:00
|
|
|
const isUpdate = action == 'udpate';
|
|
|
|
const isMain = tableInfo.isMain;
|
|
|
|
const relation = tableInfo.relation;
|
2023-04-08 13:08:37 +00:00
|
|
|
|
|
|
|
for (const change of changes) {
|
|
|
|
let newI, oldI;
|
|
|
|
const row = change.row;
|
|
|
|
|
|
|
|
switch(action) {
|
|
|
|
case 'update':
|
|
|
|
newI = change.newI;
|
|
|
|
oldI = change.oldI;
|
|
|
|
break;
|
|
|
|
case 'insert':
|
|
|
|
newI = change.instance;
|
|
|
|
break;
|
|
|
|
case 'delete':
|
|
|
|
oldI = change.instance;
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
|
2023-04-11 18:24:19 +00:00
|
|
|
const created = new Date(evt.timestamp);
|
2023-04-11 08:15:06 +00:00
|
|
|
const modelName = tableInfo.modelName;
|
2023-04-08 13:08:37 +00:00
|
|
|
const modelId = row[tableInfo.idName];
|
2023-05-30 18:09:05 +00:00
|
|
|
const modelValue = tableInfo.showField && !isMain
|
2023-04-08 13:08:37 +00:00
|
|
|
? row[tableInfo.showField] || null
|
|
|
|
: null;
|
|
|
|
const oldInstance = oldI ? JSON.stringify(oldI) : null;
|
2023-05-30 18:09:05 +00:00
|
|
|
const originFk = !isMain ? row[relation] : modelId;
|
|
|
|
const originChanged = isUpdate && !isMain
|
|
|
|
&& newI[relation] !== undefined;
|
2023-04-08 13:08:37 +00:00
|
|
|
|
|
|
|
let deleteRow;
|
2023-05-21 12:16:01 +00:00
|
|
|
if (conf.debug)
|
2023-04-30 11:09:42 +00:00
|
|
|
console.debug('Log:'.blue,
|
2023-05-21 12:16:01 +00:00
|
|
|
`[${action}]`[actionColor[action]],
|
|
|
|
`${logInfo.name}: ${originFk}, ${modelName}: ${modelId}`
|
|
|
|
);
|
2023-04-08 13:08:37 +00:00
|
|
|
|
2023-04-28 18:31:10 +00:00
|
|
|
try {
|
|
|
|
if (isDelete) {
|
|
|
|
[[deleteRow]] = await logInfo.fetchStmt.execute([
|
2023-05-13 12:25:50 +00:00
|
|
|
modelName, modelId, originFk
|
2023-04-28 18:31:10 +00:00
|
|
|
]);
|
2023-05-21 12:16:01 +00:00
|
|
|
if (!conf.testMode && deleteRow)
|
2023-04-28 18:31:10 +00:00
|
|
|
await logInfo.updateStmt.execute([
|
|
|
|
originFk,
|
|
|
|
created,
|
|
|
|
oldInstance,
|
|
|
|
modelValue,
|
|
|
|
deleteRow.id
|
|
|
|
]);
|
|
|
|
}
|
2023-05-21 12:16:01 +00:00
|
|
|
if (!conf.testMode && (!isDelete || !deleteRow)) {
|
2023-05-30 18:09:05 +00:00
|
|
|
async function log(originFk) {
|
|
|
|
return logInfo.addStmt.execute([
|
|
|
|
originFk,
|
|
|
|
row[tableInfo.userField] || null,
|
|
|
|
action,
|
|
|
|
created,
|
|
|
|
modelName,
|
|
|
|
oldInstance,
|
|
|
|
newI ? JSON.stringify(newI) : null,
|
|
|
|
modelId,
|
|
|
|
modelValue
|
|
|
|
]);
|
|
|
|
}
|
|
|
|
|
|
|
|
await log(originFk);
|
|
|
|
if (originChanged)
|
|
|
|
await log(oldI[relation]);
|
2023-04-28 18:31:10 +00:00
|
|
|
}
|
|
|
|
} catch (err) {
|
|
|
|
if (err.code == 'ER_NO_REFERENCED_ROW_2') {
|
|
|
|
this.debug('Log', `Ignored because of constraint failed.`);
|
|
|
|
} else
|
|
|
|
throw err;
|
2023-04-08 13:08:37 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-04-11 08:15:06 +00:00
|
|
|
async savePosition(binlogName, binlogPosition) {
|
|
|
|
this.debug('Flush', `filename: ${binlogName}, position: ${binlogPosition}`);
|
|
|
|
|
|
|
|
const replaceQuery =
|
|
|
|
'REPLACE INTO `util`.`binlogQueue` SET `code` = ?, `logName` = ?, `position` = ?';
|
|
|
|
if (!this.conf.testMode)
|
|
|
|
await this.db.query(replaceQuery, [this.conf.code, binlogName, binlogPosition]);
|
|
|
|
|
|
|
|
this.isFlushed = this.binlogName == binlogName
|
|
|
|
&& this.binlogPosition == binlogPosition;
|
|
|
|
}
|
|
|
|
|
2023-04-08 13:08:37 +00:00
|
|
|
async connectionPing() {
|
2023-04-10 11:56:06 +00:00
|
|
|
if (!this.isOk) return;
|
|
|
|
try {
|
|
|
|
this.debug('Ping', 'Sending ping to database.');
|
|
|
|
|
2023-05-21 12:16:01 +00:00
|
|
|
if (this.zongji) {
|
|
|
|
// FIXME: Should Zongji.connection be pinged?
|
|
|
|
await new Promise((resolve, reject) => {
|
|
|
|
this.zongji.ctrlConnection.ping(err => {
|
|
|
|
if (err) return reject(err);
|
|
|
|
resolve();
|
|
|
|
});
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2023-04-10 11:56:06 +00:00
|
|
|
await this.db.ping();
|
|
|
|
} catch(err) {
|
|
|
|
this.handleError(err);
|
|
|
|
}
|
2023-04-08 13:08:37 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
debug(namespace, message) {
|
|
|
|
if (this.conf.debug)
|
|
|
|
console.debug(`${namespace}:`.blue, message.yellow);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-04-11 08:15:06 +00:00
|
|
|
const catchEvents = new Set([
|
|
|
|
'writerows',
|
|
|
|
'updaterows',
|
|
|
|
'deleterows'
|
|
|
|
]);
|
|
|
|
|
|
|
|
const actions = {
|
|
|
|
writerows: 'insert',
|
|
|
|
updaterows: 'update',
|
|
|
|
deleterows: 'delete'
|
|
|
|
};
|
|
|
|
|
2023-04-30 11:09:42 +00:00
|
|
|
const actionColor = {
|
|
|
|
insert: 'green',
|
|
|
|
update: 'yellow',
|
|
|
|
delete: 'red'
|
|
|
|
};
|
|
|
|
|
2023-04-11 08:15:06 +00:00
|
|
|
function toUpperCamelCase(str) {
|
|
|
|
str = str.replace(/[-_ ][a-z]/g,
|
|
|
|
match => match.charAt(1).toUpperCase());
|
|
|
|
return str.charAt(0).toUpperCase() + str.substr(1);
|
|
|
|
}
|