trilium/src/services/backup.js

140 lines
4.5 KiB
JavaScript
Raw Normal View History

2017-10-22 09:10:33 +08:00
"use strict";
2018-04-03 08:46:46 +08:00
const dateUtils = require('./date_utils');
const optionService = require('./options');
const fs = require('fs-extra');
const dataDir = require('./data_dir');
2017-10-25 10:17:48 +08:00
const log = require('./log');
const sqlInit = require('./sql_init');
const syncMutexService = require('./sync_mutex');
2020-06-07 16:20:48 +08:00
const attributeService = require('./attributes');
const cls = require('./cls');
2020-06-07 16:20:48 +08:00
const utils = require('./utils');
2020-06-20 18:31:38 +08:00
function regularBackup() {
periodBackup('lastDailyBackupDate', 'daily', 24 * 3600);
2020-06-20 18:31:38 +08:00
periodBackup('lastWeeklyBackupDate', 'weekly', 7 * 24 * 3600);
2020-06-20 18:31:38 +08:00
periodBackup('lastMonthlyBackupDate', 'monthly', 30 * 24 * 3600);
}
2020-06-20 18:31:38 +08:00
function periodBackup(optionName, fileName, periodInSeconds) {
const now = new Date();
2020-06-20 18:31:38 +08:00
const lastDailyBackupDate = dateUtils.parseDateTime(optionService.getOption(optionName));
if (now.getTime() - lastDailyBackupDate.getTime() > periodInSeconds * 1000) {
2020-06-20 18:31:38 +08:00
backupNow(fileName);
2020-06-20 18:31:38 +08:00
optionService.setOption(optionName, dateUtils.utcNowDateTime());
}
}
2020-06-03 05:13:55 +08:00
const COPY_ATTEMPT_COUNT = 50;
2020-05-31 16:24:59 +08:00
2020-06-20 18:31:38 +08:00
function copyFile(backupFile) {
const sql = require('./sql');
2020-06-03 05:13:55 +08:00
try {
fs.unlinkSync(backupFile);
} catch (e) {
} // unlink throws exception if the file did not exist
let success = false;
let attemptCount = 0
for (; attemptCount < COPY_ATTEMPT_COUNT && !success; attemptCount++) {
try {
2020-06-20 18:31:38 +08:00
sql.executeWithoutTransaction(`VACUUM INTO '${backupFile}'`);
2020-06-03 05:13:55 +08:00
success = true;
} catch (e) {
log.info(`Copy DB attempt ${attemptCount + 1} failed with "${e.message}", retrying...`);
}
// we re-try since VACUUM is very picky and it can't run if there's any other query currently running
// which is difficult to guarantee so we just re-try
}
return attemptCount !== COPY_ATTEMPT_COUNT;
}
async function backupNow(name) {
// we don't want to backup DB in the middle of sync with potentially inconsistent DB state
2020-06-20 18:31:38 +08:00
return await syncMutexService.doExclusively(() => {
const backupFile = `${dataDir.BACKUP_DIR}/backup-${name}.db`;
2017-10-25 10:17:48 +08:00
2020-06-20 18:31:38 +08:00
const success = copyFile(backupFile);
2020-06-03 05:13:55 +08:00
if (success) {
2020-06-03 18:16:16 +08:00
log.info("Created backup at " + backupFile);
}
else {
2020-06-03 18:16:16 +08:00
log.error(`Creating backup ${backupFile} failed`);
}
return backupFile;
});
}
2020-06-20 18:31:38 +08:00
function anonymize() {
2020-06-03 05:13:55 +08:00
if (!fs.existsSync(dataDir.ANONYMIZED_DB_DIR)) {
fs.mkdirSync(dataDir.ANONYMIZED_DB_DIR, 0o700);
}
const anonymizedFile = dataDir.ANONYMIZED_DB_DIR + "/" + "anonymized-" + dateUtils.getDateTimeForFile() + ".db";
2020-06-20 18:31:38 +08:00
const success = copyFile(anonymizedFile);
2020-06-03 05:13:55 +08:00
if (!success) {
return { success: false };
}
2020-06-20 18:31:38 +08:00
const db = sqlite.open({
2020-06-03 05:13:55 +08:00
filename: anonymizedFile,
driver: sqlite3.Database
});
2020-06-20 18:31:38 +08:00
db.run("UPDATE api_tokens SET token = 'API token value'");
db.run("UPDATE notes SET title = 'title'");
db.run("UPDATE note_contents SET content = 'text' WHERE content IS NOT NULL");
db.run("UPDATE note_revisions SET title = 'title'");
db.run("UPDATE note_revision_contents SET content = 'text' WHERE content IS NOT NULL");
2020-06-07 16:20:48 +08:00
// we want to delete all non-builtin attributes because they can contain sensitive names and values
// on the other hand builtin/system attrs should not contain any sensitive info
const builtinAttrs = attributeService.getBuiltinAttributeNames().map(name => "'" + utils.sanitizeSql(name) + "'").join(', ');
2020-06-20 18:31:38 +08:00
db.run(`UPDATE attributes SET name = 'name', value = 'value' WHERE type = 'label' AND name NOT IN(${builtinAttrs})`);
db.run(`UPDATE attributes SET name = 'name' WHERE type = 'relation' AND name NOT IN (${builtinAttrs})`);
db.run("UPDATE branches SET prefix = 'prefix' WHERE prefix IS NOT NULL");
db.run(`UPDATE options SET value = 'anonymized' WHERE name IN
2020-06-08 05:55:55 +08:00
('documentId', 'documentSecret', 'encryptedDataKey',
'passwordVerificationHash', 'passwordVerificationSalt',
'passwordDerivedKeySalt', 'username', 'syncServerHost', 'syncProxy')
AND value != ''`);
2020-06-20 18:31:38 +08:00
db.run("VACUUM");
2020-06-03 05:13:55 +08:00
2020-06-20 18:31:38 +08:00
db.close();
2020-06-03 05:13:55 +08:00
return {
success: true,
anonymizedFilePath: anonymizedFile
};
}
if (!fs.existsSync(dataDir.BACKUP_DIR)) {
fs.mkdirSync(dataDir.BACKUP_DIR, 0o700);
}
2020-06-21 03:42:41 +08:00
sqlInit.dbReady.then(() => {
setInterval(cls.wrap(regularBackup), 4 * 60 * 60 * 1000);
2020-06-21 03:42:41 +08:00
// kickoff first backup soon after start up
setTimeout(cls.wrap(regularBackup), 5 * 60 * 1000);
});
module.exports = {
2020-06-03 05:13:55 +08:00
backupNow,
anonymize
};