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 17 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
35 changes: 31 additions & 4 deletions app/client/packages/rts/src/ctl/backup/backup.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import {
encryptBackupArchive,
executeCopyCMD,
executeMongoDumpCMD,
executePostgresDumpCMD,
getAvailableBackupSpaceInBytes,
getEncryptionPasswordFromUser,
getGitRoot,
Expand Down Expand Up @@ -66,6 +67,17 @@ describe("Backup Tests", () => {
console.log(res);
});

test("Test postgres dump CMD generation", async () => {
const dest = "/dest";
const url = "postgresql://username:password@host/appsmith";
const cmd =
"pg_dump postgresql://username:password@host/appsmith --schema=appsmith --format=custom --file=/dest/pg-data";
const res = await executePostgresDumpCMD(dest, url);

expect(res).toBe(cmd);
console.log(res);
});

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

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

expect(dbName).toEqual(expectedDBName);
});
Expand All @@ -264,15 +276,30 @@ test("Get DB name from Mongo URI 3", async () => {
const mongodb_uri =
"mongodb+srv://admin:[email protected]/test123";
const expectedDBName = "test123";
const dbName = utils.getDatabaseNameFromMongoURI(mongodb_uri);
const dbName = utils.getDatabaseNameFromUrl(mongodb_uri);

expect(dbName).toEqual(expectedDBName);
});

test("Get DB name from Mongo URI 4", async () => {
const mongodb_uri = "mongodb://appsmith:pAssW0rd!@localhost:27017/appsmith";
const expectedDBName = "appsmith";
const dbName = utils.getDatabaseNameFromMongoURI(mongodb_uri);
const dbName = utils.getDatabaseNameFromUrl(mongodb_uri);

expect(dbName).toEqual(expectedDBName);
});
test("Get DB name from Postgres URL", async () => {
const dbName = utils.getDatabaseNameFromUrl(
"postgresql://user:password@host:5432/postgres_db",
);

expect(dbName).toEqual("postgres_db");
});

test("Get DB name from Postgres URL with query params", async () => {
const dbName = utils.getDatabaseNameFromUrl(
"postgresql://user:password@host:5432/postgres_db?sslmode=disable",
);

expect(dbName).toEqual("postgres_db");
});
10 changes: 10 additions & 0 deletions app/client/packages/rts/src/ctl/backup/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,15 @@ import * as linkClasses from "./links";
import { BackupState } from "./BackupState";

export async function run(args: string[]) {
const url = utils.getDburl();

if (!url.startsWith("mongodb") && !url.startsWith("postgresql")) {
console.error("Only MongoDB and Postgres databases are supported.");
process.exitCode = 1;

return;
}

await utils.ensureSupervisorIsRunning();

const state: BackupState = new BackupState(args);
Expand All @@ -17,6 +26,7 @@ export async function run(args: string[]) {
new linkClasses.DiskSpaceLink(),
new linkClasses.ManifestLink(state),
new linkClasses.MongoDumpLink(state),
new linkClasses.PostgresDumpLink(state),
new linkClasses.GitStorageLink(state),
new linkClasses.EnvFileLink(state),

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ export class ManifestLink implements Link {
const version = await utils.getCurrentAppsmithVersion();
const manifestData = {
appsmithVersion: version,
dbName: utils.getDatabaseNameFromMongoURI(utils.getDburl()),
dbName: utils.getDatabaseNameFromUrl(utils.getDburl()),
};

await fsPromises.writeFile(
Expand Down
10 changes: 7 additions & 3 deletions app/client/packages/rts/src/ctl/backup/links/MongoDumpLink.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,13 @@ export class MongoDumpLink implements Link {
constructor(private readonly state: BackupState) {}

async doBackup() {
console.log("Exporting database");
await executeMongoDumpCMD(this.state.backupRootPath, utils.getDburl());
console.log("Exporting database done.");
const url = utils.getDburl();

if (url.startsWith("mongodb")) {
console.log("Exporting database");
await executeMongoDumpCMD(this.state.backupRootPath, url);
console.log("Exporting database done.");
}
}
}

Expand Down
33 changes: 33 additions & 0 deletions app/client/packages/rts/src/ctl/backup/links/PostgresDumpLink.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import type { Link } from ".";
import type { BackupState } from "../BackupState";
import * as utils from "../../utils";

/**
* Exports the Postgres database data using mongodump.
*/
sharat87 marked this conversation as resolved.
Show resolved Hide resolved
export class PostgresDumpLink implements Link {
constructor(private readonly state: BackupState) {}

async doBackup() {
const url = utils.getDburl();

if (url.startsWith("postgresql")) {
console.log("Exporting database");
await executePostgresDumpCMD(this.state.backupRootPath, url);
console.log("Exporting database done.");
}
}
sharat87 marked this conversation as resolved.
Show resolved Hide resolved
}

export async function executePostgresDumpCMD(
destFolder: string,
dbUrl: string,
) {
return await utils.execCommand([
"pg_dump",
dbUrl,
"--schema=appsmith",
"--format=custom",
`--file=${destFolder}/pg-data`,
]);
}
1 change: 1 addition & 0 deletions app/client/packages/rts/src/ctl/backup/links/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,3 +16,4 @@ export * from "./EnvFileLink";
export * from "./GitStorageLink";
export * from "./ManifestLink";
export * from "./MongoDumpLink";
export * from "./PostgresDumpLink";
53 changes: 52 additions & 1 deletion app/client/packages/rts/src/ctl/restore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,21 @@ async function extractArchive(backupFilePath: string, restoreRootPath: string) {

async function restoreDatabase(restoreContentsPath: string, dbUrl: string) {
console.log("Restoring database...");

if (dbUrl.startsWith("mongodb")) {
await restoreMongoDB(restoreContentsPath, dbUrl);
} else if (dbUrl.includes("postgresql")) {
await restorePostgres(restoreContentsPath, dbUrl);
} else {
throw new Error(
"Unsupported database type, only MongoDB and Postgres are supported",
);
}
sharat87 marked this conversation as resolved.
Show resolved Hide resolved

console.log("Restoring database completed");
}

async function restoreMongoDB(restoreContentsPath: string, dbUrl: string) {
const cmd = [
"mongorestore",
`--uri=${dbUrl}`,
Expand All @@ -121,7 +136,7 @@ async function restoreDatabase(restoreContentsPath: string, dbUrl: string) {

try {
const fromDbName = await getBackupDatabaseName(restoreContentsPath);
const toDbName = utils.getDatabaseNameFromMongoURI(dbUrl);
const toDbName = utils.getDatabaseNameFromUrl(dbUrl);

console.log("Restoring database from " + fromDbName + " to " + toDbName);
cmd.push(
Expand All @@ -139,6 +154,42 @@ async function restoreDatabase(restoreContentsPath: string, dbUrl: string) {
console.log("Restoring database completed");
}

async function restorePostgres(restoreContentsPath: string, dbUrl: string) {
const cmd = [
"pg_restore",
"--verbose",
"--clean",
`${restoreContentsPath}/pg-data`,
];
const url = new URL(dbUrl);
const isLocalhost = ["localhost", "127.0.0.1"].includes(url.hostname);

if (isLocalhost) {
let dbName: string;

try {
dbName = utils.getDatabaseNameFromUrl(dbUrl);
console.log("Restoring database to", dbName);
} catch (error) {
console.warn(
"Error reading manifest file. Assuming same database name as appsmith.",
error,
);
dbName = "appsmith";
}
cmd.push(
"-d",
"postgresql://localhost:5432/" + dbName,
// Use default user for local postgres
"--username=postgres",
);
sharat87 marked this conversation as resolved.
Show resolved Hide resolved
} else {
cmd.push("-d", dbUrl);
}

await utils.execCommand(cmd);
}
sharat87 marked this conversation as resolved.
Show resolved Hide resolved

async function restoreDockerEnvFile(
restoreContentsPath: string,
backupName: string,
Expand Down
13 changes: 9 additions & 4 deletions app/client/packages/rts/src/ctl/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -249,8 +249,13 @@ export async function execCommandSilent(cmd, options?) {
});
}

export function getDatabaseNameFromMongoURI(uri) {
const uriParts = uri.split("/");

return uriParts[uriParts.length - 1].split("?")[0];
/**
* Extracts database name from MongoDB or Postgres connection URL
* @param url - Database connection URL
* @returns Database name
*/
export function getDatabaseNameFromUrl(url: string) {
const parts = url.split("/");

return parts[parts.length - 1].split("?")[0];
sharat87 marked this conversation as resolved.
Show resolved Hide resolved
}
Loading