Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Introduce backup and restore for postgres #37326

Open
wants to merge 28 commits into
base: release
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 5 commits
Commits
Show all changes
28 commits
Select commit Hold shift + click to select a range
0906372
chore: Introduce backup and restore for postgres
abhvsn Nov 11, 2024
d52d62f
chore: Dummy server side change
abhvsn Nov 11, 2024
f304f6c
chore: Fix export DB
abhvsn Nov 12, 2024
5368a68
chore: Update import script for postgres DB restore
abhvsn Nov 12, 2024
be3f228
Merge branch 'release' into feat/backup-restore-pg
abhvsn Nov 13, 2024
74f96f0
fix: Remote and local postgres permissions
abhvsn Nov 13, 2024
a31fffe
Merge branch 'feat/backup-restore-pg' of github.com:appsmithorg/appsm…
abhvsn Nov 13, 2024
7933a05
Merge branch 'release' of github.com:appsmithorg/appsmith into feat/b…
abhvsn Nov 13, 2024
a6d9be8
chore: Only export appsmith schema to avoid backing up un-necessary s…
abhvsn Nov 13, 2024
032356b
chore: Minor refactors
abhvsn Nov 14, 2024
ecd642f
Merge branch 'release' of github.com:appsmithorg/appsmith into feat/b…
abhvsn Nov 14, 2024
da77268
chore: merge release branch
sharat87 Nov 29, 2024
c56c283
fix test
sharat87 Nov 29, 2024
cfba51d
Remove extension to pg-data
sharat87 Nov 29, 2024
9bda084
cosmetics
sharat87 Nov 29, 2024
b1faada
fix test
sharat87 Nov 30, 2024
4252c0e
fix test
sharat87 Nov 30, 2024
e03d925
fix comment
sharat87 Nov 30, 2024
3f10a2c
Merge branch 'release' into feat/backup-restore-pg
sharat87 Jan 27, 2025
552044c
Use Keycloak DB URL if DB URL is that of MongoDB
sharat87 Jan 27, 2025
00e8bff
Merge branch 'release' into feat/backup-restore-pg
sharat87 Feb 4, 2025
f849878
fix lint
sharat87 Feb 4, 2025
d338415
Merge branch 'release' into feat/backup-restore-pg
sharat87 Feb 4, 2025
5890ef7
chore: merge release branch
sharat87 Feb 6, 2025
4e54e91
fix: Fix Postgres backup & restore, tested on EE
sharat87 Feb 6, 2025
96c6331
chore: merge release branch
sharat87 Feb 6, 2025
1b43c4c
fmt
sharat87 Feb 6, 2025
9ff1b9c
fix: Fix case where Postgres URL is invalid
sharat87 Feb 7, 2025
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ public MongoProperties configureMongoDB() {
if (!appsmithDbUrl.startsWith("mongodb")) {
return null;
}
log.info("Found MongoDB uri configuring now");
log.info("Found MongoDB uri configuring now.");
MongoProperties mongoProperties = new MongoProperties();
mongoProperties.setUri(appsmithDbUrl);
return mongoProperties;
Expand Down
14 changes: 12 additions & 2 deletions deploy/docker/fs/opt/appsmith/utils/bin/backup.js
Original file line number Diff line number Diff line change
Expand Up @@ -125,7 +125,12 @@ function getEncryptionPasswordFromUser(){

async function exportDatabase(destFolder) {
console.log('Exporting database');
await executeMongoDumpCMD(destFolder, utils.getDburl())
// Check the DB url
if (utils.getDburl().startsWith('mongodb')) {
await executeMongoDumpCMD(destFolder, utils.getDburl())
} else if (utils.getDburl().startsWith('postgresql')) {
await executePostgresDumpCMD(destFolder, utils.getDburl());
}
abhvsn marked this conversation as resolved.
Show resolved Hide resolved
console.log('Exporting database done.');
}

Expand All @@ -141,7 +146,7 @@ async function createGitStorageArchive(destFolder) {

async function createManifestFile(path) {
const version = await utils.getCurrentAppsmithVersion()
const manifest_data = { "appsmithVersion": version, "dbName": utils.getDatabaseNameFromMongoURI(utils.getDburl()) }
const manifest_data = { "appsmithVersion": version, "dbName": utils.getDatabaseNameFromDBURI(utils.getDburl()) }
await fsPromises.writeFile(path + '/manifest.json', JSON.stringify(manifest_data));
}

Expand All @@ -161,6 +166,10 @@ async function executeMongoDumpCMD(destFolder, appsmithMongoURI) {
return await utils.execCommand(['mongodump', `--uri=${appsmithMongoURI}`, `--archive=${destFolder}/mongodb-data.gz`, '--gzip']);// generate cmd
}

async function executePostgresDumpCMD(destFolder, appsmithDBURI) {
return await utils.execCommand(['pg_dump', appsmithDBURI, '-Fc', '-f', destFolder + '/pg-data.archive']);
}
abhvsn marked this conversation as resolved.
Show resolved Hide resolved

async function createFinalArchive(destFolder, timestamp) {
console.log('Creating final archive');

Expand Down Expand Up @@ -252,6 +261,7 @@ module.exports = {
generateBackupRootPath,
getBackupContentsPath,
executeMongoDumpCMD,
executePostgresDumpCMD,
getGitRoot,
executeCopyCMD,
removeSensitiveEnvData,
Expand Down
18 changes: 14 additions & 4 deletions deploy/docker/fs/opt/appsmith/utils/bin/backup.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,16 @@ test('Test mongodump CMD generaton', async () => {
console.log(res)
})

test('Test postgresdump CMD generaton', async () => {
var dest = '/dest'
var appsmithMongoURI = 'postgresql://username:password@host/appsmith'
var cmd = 'pg_dump postgresql://username:password@host/appsmith -Fc -f /dest/pg-data.archive'
utils.execCommand = jest.fn().mockImplementation(async (a) => a.join(' '));
const res = await backup.executePostgresDumpCMD(dest, appsmithMongoURI)
expect(res).toBe(cmd)
console.log(res)
})

test('Test get gitRoot path when APPSMITH_GIT_ROOT is \'\' ', () => {
expect(backup.getGitRoot('')).toBe('/appsmith-stacks/git-storage')
});
Expand Down Expand Up @@ -229,28 +239,28 @@ test('Test backup encryption function', async () => {
test('Get DB name from Mongo URI 1', async () => {
var mongodb_uri = "mongodb+srv://admin:[email protected]/my_db_name?retryWrites=true&minPoolSize=1&maxPoolSize=10&maxIdleTimeMS=900000&authSource=admin"
var expectedDBName = 'my_db_name'
const dbName = utils.getDatabaseNameFromMongoURI(mongodb_uri)
const dbName = utils.getDatabaseNameFromDBURI(mongodb_uri)
expect(dbName).toEqual(expectedDBName)
})

test('Get DB name from Mongo URI 2', async () => {
var mongodb_uri = "mongodb+srv://admin:[email protected]/test123?retryWrites=true&minPoolSize=1&maxPoolSize=10&maxIdleTimeMS=900000&authSource=admin"
var expectedDBName = 'test123'
const dbName = utils.getDatabaseNameFromMongoURI(mongodb_uri)
const dbName = utils.getDatabaseNameFromDBURI(mongodb_uri)
expect(dbName).toEqual(expectedDBName)
})

test('Get DB name from Mongo URI 3', async () => {
var mongodb_uri = "mongodb+srv://admin:[email protected]/test123"
var expectedDBName = 'test123'
const dbName = utils.getDatabaseNameFromMongoURI(mongodb_uri)
const dbName = utils.getDatabaseNameFromDBURI(mongodb_uri)
expect(dbName).toEqual(expectedDBName)
})

test('Get DB name from Mongo URI 4', async () => {
var mongodb_uri = "mongodb://appsmith:pAssW0rd!@localhost:27017/appsmith"
var expectedDBName = 'appsmith'
const dbName = utils.getDatabaseNameFromMongoURI(mongodb_uri)
const dbName = utils.getDatabaseNameFromDBURI(mongodb_uri)
expect(dbName).toEqual(expectedDBName)
abhvsn marked this conversation as resolved.
Show resolved Hide resolved
})

9 changes: 8 additions & 1 deletion deploy/docker/fs/opt/appsmith/utils/bin/export_db.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,14 @@ function export_database() {
console.log('export_database ....');
dbUrl = utils.getDburl();
shell.mkdir('-p', [Constants.BACKUP_PATH]);
const cmd = `mongodump --uri='${dbUrl}' --archive='${Constants.BACKUP_PATH}/${Constants.DUMP_FILE_NAME}' --gzip`;
let cmd;
if (dbUrl.startsWith('mongodb')) {
cmd = `mongodump --uri='${dbUrl}' --archive='${Constants.BACKUP_PATH}/${Constants.DUMP_FILE_NAME}' --gzip`;
abhvsn marked this conversation as resolved.
Show resolved Hide resolved
} else if (dbUrl.startsWith('postgresql')) {
cmd = `pg_dump ${dbUrl} -Fc -f '${Constants.BACKUP_PATH}/${Constants.DUMP_FILE_NAME}'`;
} else {
throw new Error('Unsupported database URL');
}
abhvsn marked this conversation as resolved.
Show resolved Hide resolved
shell.exec(cmd);
sharat87 marked this conversation as resolved.
Show resolved Hide resolved
console.log('export_database done');
}
Expand Down
30 changes: 26 additions & 4 deletions deploy/docker/fs/opt/appsmith/utils/bin/import_db.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,24 @@ const utils = require('./utils');
function import_database() {
console.log('import_database ....')
dbUrl = utils.getDburl();
const cmd = `mongorestore --uri='${dbUrl}' --drop --archive='${Constants.RESTORE_PATH}/${Constants.DUMP_FILE_NAME}' --gzip`
shell.exec(cmd)
if (utils.getDburl().startsWith('mongodb')) {
restore_mongo_db();
} else if (utils.getDburl().startsWith('postgresql')) {
restore_postgres_db();
}
abhvsn marked this conversation as resolved.
Show resolved Hide resolved
console.log('import_database done')
}

restore_mongo_db = () => {
const cmd = `mongorestore --uri='${dbUrl}' --drop --archive='${Constants.RESTORE_PATH}/${Constants.DUMP_FILE_NAME}' --gzip`;
shell.exec(cmd);
}
abhvsn marked this conversation as resolved.
Show resolved Hide resolved

restore_postgres_db = () => {
const cmd = `pg_restore -U postgres -d appsmith --verbose --clean ${Constants.RESTORE_PATH}/${Constants.DUMP_FILE_NAME}`;
shell.exec(cmd);
}

function stop_application() {
shell.exec('/usr/bin/supervisorctl stop backend rts')
}
Expand All @@ -22,6 +35,16 @@ function start_application() {
shell.exec('/usr/bin/supervisorctl start backend rts')
}

function get_table_or_collection_len() {
let count;
if (utils.getDburl().startsWith('mongodb')) {
count = shell.exec(`mongo ${utils.getDburl()} --quiet --eval "db.getCollectionNames().length"`)
} else if (utils.getDburl().startsWith('postgresql')) {
count = shell.exec(`psql -U postgres -d ${utils.getDburl()} -t -c "SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = 'appsmith';"`)
}
return parseInt(count.stdout.toString().trimEnd());
}
abhvsn marked this conversation as resolved.
Show resolved Hide resolved

// Main application workflow
const main = (forceOption) => {
let errorCode = 0
Expand All @@ -37,8 +60,7 @@ const main = (forceOption) => {

shell.echo('stop backend & rts application before import database')
stop_application()
const shellCmdResult = shell.exec(`mongo ${process.env.APPSMITH_DB_URL} --quiet --eval "db.getCollectionNames().length"`)
const collectionsLen = parseInt(shellCmdResult.stdout.toString().trimEnd())
const collectionsLen = get_table_or_collection_len();
abhvsn marked this conversation as resolved.
Show resolved Hide resolved
if (collectionsLen > 0) {
if (forceOption) {
import_database()
Expand Down
24 changes: 22 additions & 2 deletions deploy/docker/fs/opt/appsmith/utils/bin/restore.js
Original file line number Diff line number Diff line change
Expand Up @@ -59,17 +59,37 @@ async function extractArchive(backupFilePath, restoreRootPath) {

async function restoreDatabase(restoreContentsPath, dbUrl) {
console.log('Restoring database...');
if (dbUrl.startsWith('mongodb')) {
await restore_mongo_db(restoreContentsPath, dbUrl);
} else if (dbUrl.includes('postgresql')) {
await restore_postgres_db(restoreContentsPath, dbUrl);
}
abhvsn marked this conversation as resolved.
Show resolved Hide resolved
console.log('Restoring database completed');
}
abhvsn marked this conversation as resolved.
Show resolved Hide resolved

async function restore_mongo_db(restoreContentsPath, dbUrl) {
const cmd = ['mongorestore', `--uri=${dbUrl}`, '--drop', `--archive=${restoreContentsPath}/mongodb-data.gz`, '--gzip']
try {
const fromDbName = await getBackupDatabaseName(restoreContentsPath);
const toDbName = utils.getDatabaseNameFromMongoURI(dbUrl);
const toDbName = utils.getDatabaseNameFromDBURI(dbUrl);
console.log("Restoring database from " + fromDbName + " to " + toDbName)
cmd.push('--nsInclude=*', `--nsFrom=${fromDbName}.*`, `--nsTo=${toDbName}.*`)
} catch (error) {
console.warn('Error reading manifest file. Assuming same database name.', error);
}
await utils.execCommand(cmd);
console.log('Restoring database completed');
}

async function restore_postgres_db(restoreContentsPath, dbUrl) {
const cmd = ['pg_restore', '-U', 'postgres', '-c', `${restoreContentsPath}/pg-data.archive`];
try {
const toDbName = utils.getDatabaseNameFromDBURI(dbUrl);
console.log("Restoring database to " + toDbName);
cmd.push('-d' , toDbName);
} catch (error) {
console.warn('Error reading manifest file. Assuming same database name.', error);
}
await utils.execCommand(cmd);
abhvsn marked this conversation as resolved.
Show resolved Hide resolved
}

async function restoreDockerEnvFile(restoreContentsPath, backupName, overwriteEncryptionKeys) {
Expand Down
4 changes: 2 additions & 2 deletions deploy/docker/fs/opt/appsmith/utils/bin/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -179,7 +179,7 @@ function execCommandSilent(cmd, options) {
});
}

function getDatabaseNameFromMongoURI(uri) {
function getDatabaseNameFromDBURI(uri) {
const uriParts = uri.split("/");
return uriParts[uriParts.length - 1].split("?")[0];
}
abhvsn marked this conversation as resolved.
Show resolved Hide resolved
Expand All @@ -195,6 +195,6 @@ module.exports = {
getCurrentAppsmithVersion,
preprocessMongoDBURI,
execCommandSilent,
getDatabaseNameFromMongoURI,
getDatabaseNameFromDBURI,
getDburl
};
Loading