├── .husky └── pre-commit ├── src ├── constants │ ├── message.ts │ ├── notifications.ts │ ├── log.ts │ └── logger.ts ├── destinations │ ├── sender.ts │ ├── local.ts │ ├── s3.ts │ └── email.ts ├── utils │ ├── file.utils.ts │ ├── cli.utils.ts │ ├── notify.utils.ts │ ├── location.utils.ts │ └── backup.utils.ts ├── notifiers │ ├── notifier.ts │ ├── slack_notifier.ts │ ├── custom_notifier.ts │ ├── discord_notifier.ts │ └── telegram_notifier.ts ├── dbs │ ├── index.ts │ ├── mysql.ts │ ├── postgres.ts │ └── mongo.ts ├── commands │ ├── promptWithCancel.ts │ ├── commandChecker.ts │ ├── install.ts │ ├── general.ts │ └── database.ts ├── @types │ ├── types.ts │ └── config.ts ├── validators │ ├── s3.ts │ ├── email.ts │ ├── config.ts │ ├── notification.ts │ └── destination.ts ├── index.ts └── setup.ts ├── docs ├── guide │ ├── automate-backup.md │ ├── cli │ │ ├── db-list.md │ │ ├── db-backup.md │ │ └── general.md │ ├── getting-started.md │ ├── what-is-backupdbee.md │ └── configuration.md ├── index.md ├── api-examples.md ├── markdown-examples.md └── .vitepress │ └── config.mts ├── .gitignore ├── tsconfig.json ├── eslint.config.mjs ├── scripts └── dump_data_for_test.sh ├── README.md ├── package.json ├── index.ts ├── backupdbee.yaml.sample ├── .github └── workflows │ └── deploy.yml └── LICENSE.md /.husky/pre-commit: -------------------------------------------------------------------------------- 1 | pnpm lint -------------------------------------------------------------------------------- /src/constants/message.ts: -------------------------------------------------------------------------------- 1 | export const NotificationMessage = { 2 | SUCCESS: `[+] Backup successful at ${new Date()}`, 3 | FAILURE: `[-] Backup failed at ${new Date()}`, 4 | }; 5 | -------------------------------------------------------------------------------- /docs/guide/automate-backup.md: -------------------------------------------------------------------------------- 1 | # Automate Backup 2 | 3 | You can use process managers to automate your backup 4 | 5 | ```bash 6 | pm2 start ts-node index.ts db:backup --name dbbackup --cron "* * * * *" 7 | ``` 8 | -------------------------------------------------------------------------------- /src/destinations/sender.ts: -------------------------------------------------------------------------------- 1 | export interface SenderOption { 2 | fileName: string; 3 | fileContent: unknown; 4 | } 5 | 6 | export interface Sender { 7 | validate(): void; 8 | send(): Promise; 9 | } 10 | -------------------------------------------------------------------------------- /src/utils/file.utils.ts: -------------------------------------------------------------------------------- 1 | import { existsSync, mkdirSync } from "fs"; 2 | 3 | export const ensureDirectory = (dirPath: string) => { 4 | if (!existsSync(dirPath)) { 5 | mkdirSync(dirPath, { recursive: true }); 6 | } 7 | }; -------------------------------------------------------------------------------- /src/notifiers/notifier.ts: -------------------------------------------------------------------------------- 1 | export interface Notifier { 2 | validate(): void; 3 | notify(): Promise; 4 | } 5 | 6 | export interface NotifierOption { 7 | databaseName: string; 8 | databaseDumpFile?: string; 9 | databaseDumpPath?: string; 10 | } 11 | -------------------------------------------------------------------------------- /src/constants/notifications.ts: -------------------------------------------------------------------------------- 1 | export const NOTIFICATION = { 2 | SLACK: "SLACK", 3 | CUSTOM: "CUSTOM", 4 | DISCORD: "DISCORD", 5 | TELEGRAM: "TELEGRAM", 6 | }; 7 | 8 | export const DESTINATION = { 9 | EMAIL: "EMAIL", 10 | S3_BUCKET: "S3_BUCKET", 11 | LOCAL: "LOCAL", 12 | }; 13 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | log 3 | .sql 4 | yarn.lock 5 | package-lock.json 6 | .env 7 | .DS_Store 8 | config.db.json 9 | backups/ 10 | .zip 11 | .vscode/ 12 | limited_dump.sql 13 | tmp/ 14 | config.ts 15 | backupdbee.yaml 16 | backupdbee.yml 17 | docs/.vitepress/dist 18 | docs/.vitepress/cache -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "target": "ES2022", 4 | "module": "CommonJS", 5 | "strict": true, 6 | "esModuleInterop": true, 7 | "skipLibCheck": true, 8 | "forceConsistentCasingInFileNames": true 9 | }, 10 | "include": ["src", "index.ts"], 11 | "exclude": [] 12 | } 13 | -------------------------------------------------------------------------------- /docs/guide/cli/db-list.md: -------------------------------------------------------------------------------- 1 | # `db:list` Command Documentation 2 | 3 | The `db:list` command lists all the databases defined in the YAML configuration file and shows the total count of databases. 4 | 5 | ## Usage 6 | 7 | Run the following command in your terminal: 8 | 9 | ```bash 10 | ts-node index.ts db:list 11 | ``` 12 | -------------------------------------------------------------------------------- /src/dbs/index.ts: -------------------------------------------------------------------------------- 1 | import { 2 | ChildProcessWithoutNullStreams, 3 | spawn, 4 | SpawnOptionsWithoutStdio, 5 | } from "child_process"; 6 | 7 | export const spawnDumpProcess = ( 8 | command: string, 9 | args: string[], 10 | env: Record 11 | ): ChildProcessWithoutNullStreams => { 12 | return spawn(command, args, { env } as SpawnOptionsWithoutStdio); 13 | }; 14 | -------------------------------------------------------------------------------- /eslint.config.mjs: -------------------------------------------------------------------------------- 1 | import globals from "globals"; 2 | import pluginJs from "@eslint/js"; 3 | import tseslint from "typescript-eslint"; 4 | 5 | 6 | export default [ 7 | {files: ["**/*.{js,mjs,cjs,ts}"]}, 8 | {languageOptions: { globals: globals.browser }}, 9 | pluginJs.configs.recommended, 10 | ...tseslint.configs.recommended, 11 | { 12 | rules: { 13 | "no-unused-vars": "error", 14 | "no-undef": "error" 15 | } 16 | } 17 | ]; -------------------------------------------------------------------------------- /src/commands/promptWithCancel.ts: -------------------------------------------------------------------------------- 1 | import { isCancel } from "@clack/prompts"; 2 | import process from "process"; 3 | 4 | // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type 5 | export const promptWithCancel = async (promptFn: Function, options: object) => { 6 | const result = await promptFn(options); 7 | if (isCancel(result)) { 8 | console.log("Operation cancelled"); 9 | process.exit(0); 10 | } 11 | return result; 12 | }; 13 | -------------------------------------------------------------------------------- /src/constants/log.ts: -------------------------------------------------------------------------------- 1 | import { Logger } from "./logger"; 2 | 3 | class Log { 4 | static error(message: string) { 5 | Logger.error(message); 6 | } 7 | 8 | static info(message: string) { 9 | Logger.info(message); 10 | } 11 | 12 | static warn(message: string) { 13 | Logger.warn(message); 14 | } 15 | 16 | // eslint-disable-next-line @typescript-eslint/no-explicit-any 17 | static debug(message: any) { 18 | Logger.debug(message); 19 | } 20 | } 21 | 22 | export default Log; 23 | -------------------------------------------------------------------------------- /src/@types/types.ts: -------------------------------------------------------------------------------- 1 | import { ChildProcessWithoutNullStreams } from "child_process"; 2 | 3 | export type NotifyOnMedium = "SLACK" | "DISCORD" | "CUSTOM"; 4 | 5 | export type ConfigType = { 6 | name: string; 7 | host: string; 8 | db_name: string; 9 | user: string; 10 | password: string; 11 | type: "postgres" | "mysql" |"mongo"; 12 | port: number; 13 | }; 14 | 15 | export interface DumpType { 16 | databaseName: string; 17 | dumpedContent: ChildProcessWithoutNullStreams; 18 | } 19 | 20 | export type DumpInfo = { 21 | databaseName: string; 22 | compressedFilePath: string; 23 | databaseType: string; 24 | dumpFilePath: string; 25 | dumpFileName: string; 26 | }; 27 | -------------------------------------------------------------------------------- /scripts/dump_data_for_test.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # Scripts that dumps 10 rows from each table in a database. 3 | 4 | DB_NAME="location" 5 | DB_USER="root" 6 | DB_PASS="iamsohappy" 7 | OUTPUT_FILE="limited_dump.sql" 8 | 9 | # Clear output file before writing 10 | > $OUTPUT_FILE 11 | 12 | # Get list of tables 13 | tables=$(mysql -u $DB_USER -p$DB_PASS -D $DB_NAME -e "SHOW TABLES;" | awk '{ print $1}' | grep -v '^Tables') 14 | 15 | # Dump 10 rows from each table 16 | for table in $tables; do 17 | echo "Dumping table: $table" 18 | mysqldump -u $DB_USER -p$DB_PASS --no-create-info --skip-lock-tables --compact --quick \ 19 | --where="TRUE LIMIT 10" "$DB_NAME" "$table" >> "$OUTPUT_FILE" 20 | done 21 | 22 | -------------------------------------------------------------------------------- /src/dbs/mysql.ts: -------------------------------------------------------------------------------- 1 | import { spawnDumpProcess } from "."; 2 | import { ConfigType, DumpType } from "../@types/types"; 3 | 4 | export const handleMysqlDump = (data: ConfigType, dumps: DumpType[]): DumpType[] => { 5 | const dbNames = data.db_name?.includes(",") 6 | ? data.db_name.split(",") 7 | : [data.db_name]; 8 | const args = ["-h", data.host, "-u", data.user, "--databases", ...dbNames]; 9 | // eslint-disable-next-line no-undef 10 | const env = { ...process.env, MYSQL_PWD: data.password }; 11 | 12 | const dumpProcess = spawnDumpProcess("mysqldump", args, env); 13 | 14 | dumps.push({ 15 | databaseName: data.db_name, 16 | dumpedContent: dumpProcess, 17 | }); 18 | return dumps; 19 | }; -------------------------------------------------------------------------------- /src/dbs/postgres.ts: -------------------------------------------------------------------------------- 1 | import { spawnDumpProcess } from "."; 2 | import { ConfigType, DumpType } from "../@types/types"; 3 | 4 | export const handlePostgresDump = ( 5 | data: ConfigType, 6 | dumps: DumpType[] 7 | ): DumpType[] => { 8 | const dbNames = data.db_name.includes(",") 9 | ? data.db_name.split(",") 10 | : [data.db_name]; 11 | 12 | dbNames.forEach((dbName) => { 13 | const args = ["-h", data.host, "-U", data.user, "-d", dbName]; 14 | // eslint-disable-next-line no-undef 15 | const env = { ...process.env, PGPASSWORD: data.password }; 16 | 17 | const dumpedData = spawnDumpProcess("pg_dump", args, env); 18 | dumps.push({ databaseName: dbName, dumpedContent: dumpedData }); 19 | }); 20 | return dumps; 21 | }; 22 | -------------------------------------------------------------------------------- /docs/guide/getting-started.md: -------------------------------------------------------------------------------- 1 | # Getting Started 2 | 3 | ## Installation 4 | 5 | ### Prerequisites 6 | 7 | - [Node.js](https://nodejs.org/) version 18 or higher. 8 | - Terminal for accessing BackupDBee cli via its command line interface (CLI). 9 | - [zip] 10 | - [pg_dump] 11 | - [mysqldump] 12 | 13 | ### Clone the project 📦 14 | 15 | ``` 16 | git clone https://github.com/28softwares/backupdbee.git 17 | cd backupdbee 18 | ``` 19 | 20 | ### Install Required Dependencies 21 | 22 | ```bash 23 | pnpm install 24 | ``` 25 | 26 | ### Initial Setup 27 | 28 | ```bash 29 | ts-node index.ts install #this creates backupdbee.yaml 30 | ``` 31 | 32 | ### Configurations ⚒️ 33 | 34 | According to your requirements, you can configure from `backupdbee.yaml` file or using cli 35 | -------------------------------------------------------------------------------- /src/dbs/mongo.ts: -------------------------------------------------------------------------------- 1 | import { spawnDumpProcess } from "."; 2 | import { ConfigType, DumpType } from "../@types/types"; 3 | 4 | export const handleMongodbsDump = ( 5 | data: ConfigType, 6 | dumps: DumpType[] 7 | ): DumpType[] => { 8 | const dbNames = data.db_name.includes(",") 9 | ? data.db_name.split(",") 10 | : [data.db_name]; 11 | 12 | dbNames.forEach((dbName) => { 13 | const args = [`--host=${data.host}`, 14 | `--port=${data.port}`, 15 | `--username=${data.user}`, 16 | `--password=${data.password}`, 17 | `--db=${dbName}`]; 18 | // eslint-disable-next-line no-undef 19 | const env = { ...process.env }; 20 | 21 | const dumpedData = spawnDumpProcess("mongodb_dump", args, env); 22 | dumps.push({ databaseName: dbName, dumpedContent: dumpedData }); 23 | }); 24 | return dumps; 25 | }; 26 | -------------------------------------------------------------------------------- /docs/index.md: -------------------------------------------------------------------------------- 1 | --- 2 | # https://vitepress.dev/reference/default-theme-home-page 3 | layout: home 4 | 5 | hero: 6 | name: "BackupDBee 🐝" 7 | text: "Automatic CLI Based Advance DB Backup System" 8 | actions: 9 | - theme: brand 10 | text: Documentation 11 | link: /guide/what-is-backupdbee 12 | - theme: alt 13 | text: Github 14 | link: https://github.com/28softwares/backupdbee 15 | 16 | features: 17 | - title: Multiple Database Support 18 | details: Seamlessly back up MySQL & PostgreSQL in one go. 19 | - title: Notifify on different channels 20 | details: Notify on Discord or Slack or Telegram for successful and failed backups. 21 | - title: Automated Backups 22 | details: Schedule and automate backups (using crons or pm2) to ensure your data is always protected without manual intervention. 23 | --- 24 | -------------------------------------------------------------------------------- /src/commands/commandChecker.ts: -------------------------------------------------------------------------------- 1 | import { execSync } from "child_process"; 2 | import process from "process"; 3 | import chalk from "chalk"; 4 | 5 | /** 6 | * Checks if the required commands are available. 7 | * 8 | * @param commands - An array of commands to check. 9 | * @returns void 10 | */ 11 | export const checkCommands = (commands: string[]) => { 12 | console.log(chalk.cyan("Checking required commands...")); 13 | for (const command of commands) { 14 | try { 15 | execSync(`which ${command}`); 16 | console.log(chalk.green(`✓ ${command} is available`)); 17 | } catch (error) { 18 | console.log(chalk.red(`✗ ${command} command not found!`)); 19 | console.log(chalk.red(`Error details: ${error}`)); 20 | process.exit(1); 21 | } 22 | } 23 | 24 | console.log(chalk.green("All required commands are available.")); 25 | }; 26 | -------------------------------------------------------------------------------- /src/destinations/local.ts: -------------------------------------------------------------------------------- 1 | import * as fs from "fs"; 2 | import { ensureDirectory } from "../utils/file.utils"; 3 | import { Sender } from "./sender"; 4 | import path from "path"; 5 | 6 | export class LocalSender implements Sender { 7 | private backupDir: string = ""; 8 | constructor(private filePath: string, private compressedFilePath: string) { 9 | this.filePath = filePath; 10 | this.compressedFilePath = compressedFilePath; 11 | } 12 | 13 | validate(): void { 14 | const backupDir = path.resolve(this.filePath); 15 | this.backupDir = backupDir; 16 | ensureDirectory(backupDir); 17 | } 18 | 19 | async send(): Promise { 20 | fs.copyFileSync( 21 | this.compressedFilePath, 22 | path.resolve( 23 | this.backupDir, 24 | this.compressedFilePath.split("/").pop() as string 25 | ) 26 | ); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/validators/s3.ts: -------------------------------------------------------------------------------- 1 | import { S3Bucket } from "../@types/config"; 2 | import { config } from "../utils/cli.utils"; 3 | import Log from "../constants/log"; 4 | 5 | export function validateS3Destination(s3_bucket: S3Bucket): boolean { 6 | if (s3_bucket?.enabled) { 7 | if (!s3_bucket?.bucket_name) { 8 | Log.error("S3 bucket name not set in the config file."); 9 | return false; 10 | } 11 | 12 | if (!s3_bucket?.region) { 13 | Log.error("S3 region not set in the config file."); 14 | return false; 15 | } 16 | 17 | if ( 18 | !config.destinations.s3_bucket.access_key || 19 | !config.destinations.s3_bucket.secret_key || 20 | !config.destinations.s3_bucket.region 21 | ) { 22 | Log.error("AWS credentials not set in the environment variables."); 23 | return false; 24 | } 25 | } 26 | return true; 27 | } 28 | -------------------------------------------------------------------------------- /docs/guide/what-is-backupdbee.md: -------------------------------------------------------------------------------- 1 | # What is BackupDBee 🐝? 2 | 3 | BackupDBee is a automatic CLI based advance DB backup system. It helps to effortlessly manage your database backups at one go. This easy-to-use tool supports MySQL & PostgreSQL allowing you to back up multiple databases at once. 4 | 5 |
6 | 7 | Just want to try it out? Skip to the [Quickstart](./getting-started). 8 | 9 |
10 | 11 | #### Key features: 🚀 12 | 13 | ✅ Multiple Database Support: Seamlessly back up MySQL & PostgreSQL in one go. (Note: For now we support MySQL and PostgreSQl.) 14 | 15 | ✅ Support for GMAIL,S3 BUCKET for storing the backup. (Backups are transfered in zip format, reducing backup size.) 16 | 17 | ✅ Notify on Discord or Slack or Telegram for successful and failed backups. 18 | 19 | ✅ Automated Backups: Schedule and automate backups (using crons or pm2) to ensure your data is always protected without manual intervention. 20 | -------------------------------------------------------------------------------- /docs/guide/cli/db-backup.md: -------------------------------------------------------------------------------- 1 | # `db:backup` Command Documentation 2 | 3 | The `db:backup` command is used to back up all databases defined in the YAML configuration or specific ones using the `--name` flag. You can pass multiple databases to `--name` flag by providing a comma-separated list of database names. 4 | 5 | ## Usage 6 | 7 | ### Backup All Databases 8 | 9 | To back up all databases, simply run the following command: 10 | 11 | ```bash 12 | ts-node index.ts db:backup 13 | ``` 14 | 15 | ### Backup Specific Database(s) 16 | 17 | To back up one or more specific databases, use the `--name` flag followed by the database name(s). You can provide a single database name or multiple names separated by commas. 18 | 19 | #### Backup a Single Database: 20 | 21 | ```bash 22 | ts-node index.ts db:backup --name 23 | ``` 24 | 25 | #### Backup Multiple Databases: 26 | 27 | ```bash 28 | ts-node index.ts db:backup --name ,, 29 | ``` 30 | -------------------------------------------------------------------------------- /docs/api-examples.md: -------------------------------------------------------------------------------- 1 | --- 2 | outline: deep 3 | --- 4 | 5 | # Runtime API Examples 6 | 7 | This page demonstrates usage of some of the runtime APIs provided by VitePress. 8 | 9 | The main `useData()` API can be used to access site, theme, and page data for the current page. It works in both `.md` and `.vue` files: 10 | 11 | ```md 12 | 17 | 18 | ## Results 19 | 20 | ### Theme Data 21 |
{{ theme }}
22 | 23 | ### Page Data 24 |
{{ page }}
25 | 26 | ### Page Frontmatter 27 |
{{ frontmatter }}
28 | ``` 29 | 30 | 35 | 36 | ## Results 37 | 38 | ### Theme Data 39 |
{{ theme }}
40 | 41 | ### Page Data 42 |
{{ page }}
43 | 44 | ### Page Frontmatter 45 |
{{ frontmatter }}
46 | 47 | ## More 48 | 49 | Check out the documentation for the [full list of runtime APIs](https://vitepress.dev/reference/runtime-api#usedata). 50 | -------------------------------------------------------------------------------- /src/constants/logger.ts: -------------------------------------------------------------------------------- 1 | import winston from "winston"; 2 | 3 | const levels = { 4 | error: 0, 5 | warn: 1, 6 | info: 2, 7 | http: 3, 8 | debug: 4, 9 | }; 10 | 11 | const level = () => { 12 | return "debug"; 13 | }; 14 | 15 | const colors = { 16 | error: "red", 17 | warn: "yellow", 18 | info: "green", 19 | http: "magenta", 20 | debug: "white", 21 | }; 22 | 23 | winston.addColors(colors); 24 | 25 | const format = winston.format.combine( 26 | winston.format.timestamp({ format: "YYYY-MM-DD HH:mm:ss:ms" }), 27 | winston.format.colorize({ all: true }), 28 | winston.format.printf( 29 | // eslint-disable-next-line @typescript-eslint/no-explicit-any 30 | (info: any) => `${info.timestamp} ${info.level}: ${info.message}` 31 | ) 32 | ); 33 | 34 | const transports = [ 35 | new winston.transports.Console(), 36 | new winston.transports.File({ 37 | filename: "log/error.log", 38 | level: "error", 39 | }), 40 | new winston.transports.File({ filename: "log/all.log" }), 41 | ]; 42 | 43 | export const Logger = winston.createLogger({ 44 | level: level(), 45 | levels, 46 | format, 47 | transports, 48 | }); 49 | -------------------------------------------------------------------------------- /src/validators/email.ts: -------------------------------------------------------------------------------- 1 | import { Email } from "../@types/config"; 2 | import Log from "../constants/log"; 3 | import { config } from "../utils/cli.utils"; 4 | 5 | export function validateEmailDestination(email?: Email): boolean { 6 | if (email?.enabled) { 7 | if (!email?.from) { 8 | Log.error("Email from address not set in the config file."); 9 | return false; 10 | } 11 | 12 | if (!email?.to?.length) { 13 | Log.error("Email to address not set in the config file."); 14 | return false; 15 | } 16 | 17 | if ( 18 | !config.destinations.email.smtp_username || 19 | !config.destinations.email.smtp_password 20 | ) { 21 | Log.error("Mail credentials not set in the environment variables."); 22 | return false; 23 | } 24 | } 25 | return true; 26 | } 27 | 28 | export function validateEmailNotification(email: Email): boolean { 29 | if (!email.from) { 30 | Log.error("Email from address not set in the config file."); 31 | return false; 32 | } 33 | 34 | if (!email.to.length) { 35 | Log.error("Email to address not set in the config file."); 36 | return false; 37 | } 38 | 39 | return true; 40 | } 41 | -------------------------------------------------------------------------------- /src/utils/cli.utils.ts: -------------------------------------------------------------------------------- 1 | import { readFileSync, writeFileSync } from "fs"; 2 | import path from "path"; 3 | import * as yaml from "yaml"; 4 | import * as fs from "fs"; 5 | import { DataBeeConfig } from "../@types/config"; 6 | 7 | // eslint-disable-next-line no-undef 8 | export const sourceFile = path.join(__dirname, "../../backupdbee.yaml.sample"); 9 | // eslint-disable-next-line no-undef 10 | export const destinationFile = path.join(__dirname, "../../backupdbee.yaml"); 11 | 12 | export function parseConfigFile(): DataBeeConfig { 13 | const configFile = readFileSync(destinationFile, "utf-8"); 14 | const yamlConfig = yaml.parse(configFile) as DataBeeConfig; 15 | return yamlConfig; 16 | } 17 | 18 | export function saveConfig(config: DataBeeConfig) { 19 | const yamlString = yaml.stringify(config); 20 | writeFileSync(destinationFile, yamlString, "utf8"); 21 | } 22 | 23 | function parseSampleFileBeforeInstall(): DataBeeConfig { 24 | const configFile = readFileSync(sourceFile, "utf-8"); 25 | const yamlConfig = yaml.parse(configFile) as DataBeeConfig; 26 | return yamlConfig; 27 | } 28 | 29 | export const config = fs.existsSync(destinationFile) 30 | ? parseConfigFile() 31 | : parseSampleFileBeforeInstall(); 32 | -------------------------------------------------------------------------------- /src/validators/config.ts: -------------------------------------------------------------------------------- 1 | import { ConfigType } from "../@types/types"; 2 | import Log from "../constants/log"; 3 | 4 | export function validateDBConfig(config: ConfigType): boolean { 5 | let isValid = true; 6 | if (!config.host) { 7 | isValid = false; 8 | Log.error("Host is not set in the config file."); 9 | } 10 | 11 | if (!config.db_name) { 12 | isValid = false; 13 | Log.error("Database name is not set in the config file."); 14 | } 15 | 16 | if (!config.user) { 17 | isValid = false; 18 | Log.error("Username is not set in the config file."); 19 | } 20 | 21 | if (!config.password) { 22 | isValid = false; 23 | Log.error("Password is not set in the config file."); 24 | } 25 | 26 | if (!config.type) { 27 | isValid = false; 28 | Log.error("Database type is not set in the config file."); 29 | } 30 | 31 | if (config.type !== "postgres" && config.type !== "mysql") { 32 | isValid = false; 33 | Log.error( 34 | "Unsupported database type. Supported types are postgres and mysql." 35 | ); 36 | } 37 | 38 | if (!config.port) { 39 | Log.warn( 40 | `Port is not set in the config file. Using default port for ${config.type}` 41 | ); 42 | } 43 | 44 | return isValid; 45 | } -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # BackupDBee 🐝 2 | 3 | Effortlessly manage your database backups at one go. This easy-to-use tool supports MySQL & PostgreSQL allowing you to back up multiple databases at once. 4 | 5 | #### Key features: 🚀 6 | 7 | ✅ Multiple Database Support: Seamlessly back up MySQL & PostgreSQL in one go. (Note: For now we support MySQL and PostgreSQl.) 8 | 9 | ✅ Support for GMAIL,S3 BUCKET for storing the backup. (Backups are transfered in zip format, reducing backup size.) 10 | 11 | ✅ Multiple Email Recipients: Send backups to multiple email recipients. (if `BACKUP_DEST` is set to `GMAIL`) 12 | 13 | ✅ Notify on Discord or Slack for successful and failed backups. 14 | 15 | ✅ Automated Backups: Schedule and automate backups (using crons or pm2) to ensure your data is always protected without manual intervention. 16 | 17 | ## Documentation 18 | 19 | Check out the documentation at: [https://28softwares.github.com/BackupDBee](https://28softwares.github.com/BackupDBee) 20 | 21 | ## Feel Free To Contribute 👌 22 | 23 | Customize it further based on your tool’s specific features and benefits! PR are welcome. 24 | 25 | Current work updates can be found at: 26 | [https://github.com/orgs/28softwares/projects/1](https://github.com/orgs/28softwares/projects/1) 27 | 28 | ## Contributors 🤝 29 | 30 | 31 | 32 | 33 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "auto-db-backup-and-email", 3 | "version": "1.0.0", 4 | "description": "", 5 | "main": "index.js", 6 | "scripts": { 7 | "test": "echo \"Error: no test specified\" && exit 1", 8 | "lint": "eslint \"**/*.{ts,tsx}\"", 9 | "start": "ts-node index.ts db:backup", 10 | "prepare": "husky", 11 | "docs:dev": "vitepress dev docs", 12 | "docs:build": "vitepress build docs", 13 | "docs:preview": "vitepress preview docs" 14 | }, 15 | "keywords": [], 16 | "author": "", 17 | "license": "ISC", 18 | "dependencies": { 19 | "@aws-sdk/client-s3": "^3.637.0", 20 | "@clack/prompts": "^0.7.0", 21 | "@types/nodemailer": "^6.4.15", 22 | "chalk": "^4.1.2", 23 | "class-transformer": "^0.5.1", 24 | "commander": "^12.1.0", 25 | "nodemailer": "^6.9.14", 26 | "ts-node": "^10.9.2", 27 | "winston": "^3.14.1", 28 | "yaml": "^2.5.1" 29 | }, 30 | "devDependencies": { 31 | "@eslint/js": "^9.9.0", 32 | "@types/express": "^4.17.21", 33 | "@types/node": "^18.19.44", 34 | "eslint": "^9.9.0", 35 | "globals": "^15.9.0", 36 | "husky": "^9.1.5", 37 | "ts-node-dev": "^2.0.0", 38 | "typescript": "^5.5.4", 39 | "typescript-eslint": "^8.1.0", 40 | "vitepress": "^1.3.4" 41 | }, 42 | "packageManager": "pnpm@9.1.4+sha512.9df9cf27c91715646c7d675d1c9c8e41f6fce88246f1318c1aa6a1ed1aeb3c4f032fcdf4ba63cc69c4fe6d634279176b5358727d8f2cc1e65b65f43ce2f8bfb0" 43 | } 44 | -------------------------------------------------------------------------------- /docs/markdown-examples.md: -------------------------------------------------------------------------------- 1 | # Markdown Extension Examples 2 | 3 | This page demonstrates some of the built-in markdown extensions provided by VitePress. 4 | 5 | ## Syntax Highlighting 6 | 7 | VitePress provides Syntax Highlighting powered by [Shiki](https://github.com/shikijs/shiki), with additional features like line-highlighting: 8 | 9 | **Input** 10 | 11 | ````md 12 | ```js{4} 13 | export default { 14 | data () { 15 | return { 16 | msg: 'Highlighted!' 17 | } 18 | } 19 | } 20 | ``` 21 | ```` 22 | 23 | **Output** 24 | 25 | ```js{4} 26 | export default { 27 | data () { 28 | return { 29 | msg: 'Highlighted!' 30 | } 31 | } 32 | } 33 | ``` 34 | 35 | ## Custom Containers 36 | 37 | **Input** 38 | 39 | ```md 40 | ::: info 41 | This is an info box. 42 | ::: 43 | 44 | ::: tip 45 | This is a tip. 46 | ::: 47 | 48 | ::: warning 49 | This is a warning. 50 | ::: 51 | 52 | ::: danger 53 | This is a dangerous warning. 54 | ::: 55 | 56 | ::: details 57 | This is a details block. 58 | ::: 59 | ``` 60 | 61 | **Output** 62 | 63 | ::: info 64 | This is an info box. 65 | ::: 66 | 67 | ::: tip 68 | This is a tip. 69 | ::: 70 | 71 | ::: warning 72 | This is a warning. 73 | ::: 74 | 75 | ::: danger 76 | This is a dangerous warning. 77 | ::: 78 | 79 | ::: details 80 | This is a details block. 81 | ::: 82 | 83 | ## More 84 | 85 | Check out the documentation for the [full list of markdown extensions](https://vitepress.dev/guide/markdown). 86 | -------------------------------------------------------------------------------- /src/index.ts: -------------------------------------------------------------------------------- 1 | import backupHelper from "./utils/backup.utils"; 2 | import { exec } from "child_process"; 3 | import { ConfigType } from "./@types/types"; 4 | import { promisify } from "util"; 5 | import Log from "./constants/log"; 6 | import { sendNotification } from "./utils/notify.utils"; 7 | import { Destinations, Notifications } from "./@types/config"; 8 | import { validateDBConfig } from "./validators/config"; 9 | import { getDefaultPortOfDBType } from "./setup"; 10 | // Promisify exec to use with async/await 11 | export const execAsync = promisify(exec); 12 | 13 | export const main = async ( 14 | configs: ConfigType[], 15 | destinations: Destinations, 16 | notifications: Notifications 17 | ) => { 18 | for (const config of configs) { 19 | // if no config provided, then only backup will be done 20 | if (validateDBConfig(config)) { 21 | try { 22 | if (!config.port) { 23 | config.port = getDefaultPortOfDBType(config.type); 24 | } 25 | const dumpInfo = await backupHelper(config, destinations); 26 | if (!dumpInfo) { 27 | Log.error("Backup failed."); 28 | return; 29 | } 30 | if (!dumpInfo.compressedFilePath) { 31 | Log.error("Backup failed."); 32 | return; 33 | } 34 | await sendNotification(dumpInfo, notifications); 35 | } catch (e: unknown) { 36 | Log.error("Backup failed." + e); 37 | } 38 | } 39 | } 40 | }; 41 | -------------------------------------------------------------------------------- /index.ts: -------------------------------------------------------------------------------- 1 | import process from "process"; 2 | import { Command } from "commander"; 3 | import install from "./src/commands/install"; 4 | import { dbBackup, dbList } from "./src/commands/database"; 5 | import general from "./src/commands/general"; 6 | 7 | const program = new Command(); 8 | program.version("1.0.0").description("BackupDBee CLI"); 9 | 10 | program 11 | .command("install") 12 | .alias("i") 13 | .description("Check required commands, create backupdbee.yaml file") 14 | .action(async () => await install()); 15 | 16 | program 17 | .command("db:list") 18 | .description("List all databases and show the total count") 19 | .action(dbList); 20 | 21 | program 22 | .command("db:backup") 23 | .description("Backup all databases or a specific one with --name flag") 24 | .option("--name ", "Name of the database to backup") 25 | .action((options: { name?: string }) => { 26 | dbBackup(options); 27 | }); 28 | 29 | program 30 | .command("general") 31 | .description("Configure general settings in backupdbee.yaml") 32 | .option("--backup-location ", "Set the backup location") 33 | .option("--log-location ", "Set the log location") 34 | .option("--log-level ", "Set the log level (e.g., INFO, DEBUG)") 35 | .option("--retention-policy ", "Set retention policy in days", parseInt) 36 | .option("--backup-schedule ", "Set backup schedule in cron format") 37 | .action(async (options) => { 38 | general(options); 39 | }); 40 | 41 | program.parse(process.argv); 42 | -------------------------------------------------------------------------------- /src/validators/notification.ts: -------------------------------------------------------------------------------- 1 | import { Email } from "../@types/config"; 2 | import Log from "../constants/log"; 3 | 4 | export function validateDiscordNotification(webhook_url: string): boolean { 5 | if (!webhook_url) { 6 | Log.error("Discord webhook URL not set in the config file."); 7 | return false; 8 | } 9 | return true; 10 | } 11 | 12 | export function validateSlackNotification(webhook_url: string): boolean { 13 | if (!webhook_url) { 14 | Log.error("Slack webhook URL not set in the config file."); 15 | return false; 16 | } 17 | return true; 18 | } 19 | 20 | export function validateWebhookNotification(url: string): boolean { 21 | if (!url) { 22 | Log.error("Webhook URL not set in the config file."); 23 | return false; 24 | } 25 | return true; 26 | } 27 | 28 | export function validateTelegramNotification( 29 | webHook: string, 30 | chatId: number 31 | ): boolean { 32 | if (!webHook) { 33 | Log.error("Telegram webhook URL not set in the config file."); 34 | return false; 35 | } 36 | if (!chatId) { 37 | Log.error("chatId not set in the config file."); 38 | return false; 39 | } 40 | return true; 41 | } 42 | 43 | export function validateEmailNotification(email: Email): boolean { 44 | if (!email.from) { 45 | Log.error("Email from address not set in the config file."); 46 | return false; 47 | } 48 | 49 | if (!email.to.length) { 50 | Log.error("Email to address not set in the config file."); 51 | return false; 52 | } 53 | 54 | return true; 55 | } 56 | -------------------------------------------------------------------------------- /docs/.vitepress/config.mts: -------------------------------------------------------------------------------- 1 | import { defineConfig, type DefaultTheme } from "vitepress"; 2 | 3 | // https://vitepress.dev/reference/site-config 4 | export default defineConfig({ 5 | base: "/BackupDBee/", 6 | title: "BackupDBee 🐝", 7 | description: "Automatic CLI Based Advance DB Backup System", 8 | themeConfig: { 9 | // https://vitepress.dev/reference/default-theme-config 10 | nav: [ 11 | { text: "Home", link: "/" }, 12 | { 13 | text: "Guide", 14 | link: "/guide/what-is-backupdbee", 15 | activeMatch: "/guide/", 16 | }, 17 | ], 18 | 19 | sidebar: { 20 | "/guide/": { base: "/guide/", items: sidebarGuide() }, 21 | }, 22 | 23 | socialLinks: [ 24 | { icon: "github", link: "https://github.com/28softwares/BackupDBee" }, 25 | ], 26 | }, 27 | }); 28 | 29 | function sidebarGuide(): DefaultTheme.SidebarItem[] { 30 | return [ 31 | { 32 | text: "Introduction", 33 | collapsed: false, 34 | items: [ 35 | { text: "What is backupdbee?", link: "what-is-backupdbee" }, 36 | { text: "Getting Started", link: "getting-started" }, 37 | { text: "Configuration", link: "configuration" }, 38 | ], 39 | }, 40 | { 41 | text: "Cli Commands", 42 | collapsed: false, 43 | items: [ 44 | { text: "general", link: "cli/general" }, 45 | { text: "db:list", link: "cli/db-list" }, 46 | { text: "db:backup", link: "cli/db-backup" }, 47 | ], 48 | }, 49 | { 50 | text: "Automation", 51 | link: "automate-backup", 52 | }, 53 | ]; 54 | } 55 | -------------------------------------------------------------------------------- /backupdbee.yaml.sample: -------------------------------------------------------------------------------- 1 | general: 2 | backup_location: backups 3 | log_location: logs 4 | log_level: INFO 5 | retention_policy_days: 7 6 | backup_schedule: "0 3 * * *" 7 | 8 | destinations: 9 | local: 10 | enabled: true 11 | path: backups 12 | 13 | s3: 14 | enabled: false 15 | bucket_name: backupbee 16 | region: us-east-1 17 | access_key: XXXXXXXXXXX 18 | secret_key: XXXXXXXXXXX 19 | 20 | email: 21 | enabled: false 22 | smtp_server: smtp.gmail.com 23 | smtp_port: 587 24 | smtp_username: 25 | smtp_password: 26 | from: no-reply@backupbee.com 27 | to: 28 | - master@backupbee.com 29 | 30 | notifications: 31 | slack: 32 | enabled: true 33 | webhook_url: https://hooks.slack.com/services/XXXXXXXXXXXXXXXXXXXXXXXX 34 | 35 | custom: 36 | enabled: false 37 | web_url: https://backupbee.com/api/v1/backup 38 | 39 | discord: 40 | enabled: false 41 | webhook_url: https://discord.com/api/webhooks/XXXXXXXXX/XXXXXXXXX 42 | 43 | telegram: 44 | enabled: true 45 | webhook_url: https://api.telegram.org/botXXXXXXXXXX:XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/sendMessage 46 | chatId: XXXXXXX 47 | 48 | databases: 49 | - name: primary_db 50 | type: postgres 51 | host: localhost 52 | port: 5432 53 | username: postgres 54 | password: pass 55 | database_name: asterconsult 56 | backup_schedule: "0 3 * * *" 57 | 58 | # - name: secondary_db 59 | # type: mysql 60 | # host: 192.168.1.10 61 | # port: 3306 62 | # username: backup_user 63 | # password: supersecret 64 | # database_name: my_secondary_db 65 | # backup_schedule: "0 4 * * *" 66 | -------------------------------------------------------------------------------- /src/@types/config.ts: -------------------------------------------------------------------------------- 1 | export interface General { 2 | backup_location: string; 3 | log_location: string; 4 | log_level: string; 5 | retention_policy_days: number; 6 | backup_schedule: string; 7 | } 8 | 9 | export interface Notifications { 10 | email: Email; 11 | slack: Slack; 12 | custom: Custom; 13 | discord: Discord; 14 | telegram: Telegram; 15 | } 16 | 17 | export interface Slack { 18 | enabled: boolean; 19 | webhook_url: string; 20 | } 21 | 22 | export interface Custom { 23 | enabled: boolean; 24 | webhook_url: string; 25 | } 26 | 27 | export interface Discord { 28 | enabled: boolean; 29 | webhook_url: string; 30 | } 31 | 32 | export interface Telegram { 33 | enabled: boolean; 34 | webhook_url: string; 35 | chatId: number; 36 | } 37 | 38 | export interface Database { 39 | name: string; 40 | type: string; 41 | host: string; 42 | port: number; 43 | username: string; 44 | password: string; 45 | database_name: string; 46 | backup_schedule: string; 47 | } 48 | 49 | export interface Local { 50 | enabled: boolean; 51 | path: string; 52 | } 53 | 54 | export interface S3Bucket { 55 | enabled: boolean; 56 | bucket_name: string; 57 | region: string; 58 | access_key: string; 59 | secret_key: string; 60 | } 61 | 62 | export interface Email { 63 | enabled: boolean; 64 | smtp_server: string; 65 | smtp_port: number; 66 | smtp_username: string; 67 | smtp_password: string; 68 | from: string; 69 | to: string[]; 70 | } 71 | 72 | export interface Destinations { 73 | local: Local; 74 | s3_bucket: S3Bucket; 75 | email: Email; 76 | } 77 | 78 | export interface DataBeeConfig { 79 | general: General; 80 | notifications: Notifications; 81 | databases: Database[]; 82 | destinations: Destinations; 83 | } 84 | -------------------------------------------------------------------------------- /src/validators/destination.ts: -------------------------------------------------------------------------------- 1 | import { Email, Local, S3Bucket } from "../@types/config"; 2 | import Log from "../constants/log"; 3 | import { config } from "../utils/cli.utils"; 4 | 5 | export function validateLocalDestination(local: Local): boolean { 6 | if (local?.enabled) { 7 | if (!local?.path) { 8 | console.error("Local path not set in the config file."); 9 | return false; 10 | } 11 | } 12 | return true; 13 | } 14 | 15 | export function validateEmailDestination(email?: Email): boolean { 16 | if (email?.enabled) { 17 | if (!email?.from) { 18 | Log.error("Email from address not set in the config file."); 19 | return false; 20 | } 21 | 22 | if (!email?.to?.length) { 23 | Log.error("Email to address not set in the config file."); 24 | return false; 25 | } 26 | 27 | if ( 28 | !config.destinations.email.smtp_username || 29 | !config.destinations.email.smtp_password 30 | ) { 31 | Log.error("Mail credentials not set in the environment variables."); 32 | return false; 33 | } 34 | } 35 | return true; 36 | } 37 | 38 | export function validateS3Destination(s3_bucket: S3Bucket): boolean { 39 | if (s3_bucket?.enabled) { 40 | if (!s3_bucket?.bucket_name) { 41 | Log.error("S3 bucket name not set in the config file."); 42 | return false; 43 | } 44 | 45 | if (!s3_bucket?.region) { 46 | Log.error("S3 region not set in the config file."); 47 | return false; 48 | } 49 | 50 | if ( 51 | !config.destinations.s3_bucket.access_key || 52 | !config.destinations.s3_bucket.secret_key || 53 | !config.destinations.s3_bucket.region 54 | ) { 55 | Log.error("AWS credentials not set in the environment variables."); 56 | return false; 57 | } 58 | } 59 | return true; 60 | } 61 | -------------------------------------------------------------------------------- /.github/workflows/deploy.yml: -------------------------------------------------------------------------------- 1 | name: Deploy VitePress site to Pages 2 | 3 | on: 4 | push: 5 | branches: [main] 6 | paths: 7 | - "docs/**" # Only trigger when files in the docs/ directory change 8 | 9 | # Allows you to run this workflow manually from the Actions tab 10 | workflow_dispatch: 11 | 12 | permissions: 13 | contents: read 14 | pages: write 15 | id-token: write 16 | 17 | concurrency: 18 | group: pages 19 | cancel-in-progress: false 20 | 21 | jobs: 22 | # Build job 23 | build: 24 | runs-on: ubuntu-latest 25 | steps: 26 | - name: Checkout 27 | uses: actions/checkout@v4 28 | with: 29 | fetch-depth: 0 # Not needed if lastUpdated is not enabled 30 | - uses: pnpm/action-setup@v3 # Uncomment this if you're using pnpm 31 | # - uses: oven-sh/setup-bun@v1 # Uncomment this if you're using Bun 32 | - name: Setup Node 33 | uses: actions/setup-node@v4 34 | with: 35 | node-version: 20 36 | cache: pnpm # or pnpm / yarn 37 | - name: Setup Pages 38 | uses: actions/configure-pages@v4 39 | - name: Install dependencies 40 | run: pnpm install # or pnpm install / yarn install / bun install 41 | - name: Build with VitePress 42 | run: pnpm docs:build # or pnpm docs:build / yarn docs:build / bun run docs:build 43 | - name: Upload artifact 44 | uses: actions/upload-pages-artifact@v3 45 | with: 46 | path: docs/.vitepress/dist 47 | 48 | # Deployment job 49 | deploy: 50 | environment: 51 | name: github-pages 52 | url: ${{ steps.deployment.outputs.page_url }} 53 | needs: build 54 | runs-on: ubuntu-latest 55 | name: Deploy 56 | steps: 57 | - name: Deploy to GitHub Pages 58 | id: deployment 59 | uses: actions/deploy-pages@v4 60 | -------------------------------------------------------------------------------- /src/notifiers/slack_notifier.ts: -------------------------------------------------------------------------------- 1 | import Log from "../constants/log"; 2 | import { Notifier } from "./notifier"; 3 | 4 | export class SlackNotifier implements Notifier { 5 | private webhookUrl: string; 6 | private message: string; 7 | 8 | constructor(webhookUrl: string, message: string) { 9 | this.webhookUrl = webhookUrl; 10 | this.message = message; 11 | } 12 | 13 | validate(): void { 14 | if (!this.webhookUrl) { 15 | throw new Error("[-] Webhook URL is not set"); 16 | } 17 | 18 | const newUrl = new URL(this.webhookUrl); 19 | if (newUrl.protocol !== "http:" && newUrl.protocol !== "https:") { 20 | throw new Error("[-] Webhook URL is invalid."); 21 | } 22 | } 23 | 24 | async notify(): Promise { 25 | try { 26 | const response = await fetch(this.webhookUrl, { 27 | method: "POST", 28 | headers: { 29 | "Content-Type": "application/json", 30 | }, 31 | body: JSON.stringify({ 32 | text: this.message, 33 | }), 34 | }); 35 | 36 | if (!response.ok) { 37 | console.error( 38 | `[-] Failed to send notification to ${new URL( 39 | this.webhookUrl 40 | ).hostname.replace(".com", "")}: ${response.status} ${ 41 | response.statusText 42 | } ` 43 | ); 44 | } else { 45 | console.log( 46 | `[+] Notification sent successfully to ${new URL( 47 | this.webhookUrl 48 | ).hostname.replace(".com", "")}` 49 | ); 50 | } 51 | } catch (error: unknown) { 52 | if (error instanceof Error) { 53 | Log.error(`Error sending notification: ${error.message}`); 54 | console.error(`[-] Error sending notification: ${error.message}`); 55 | } else { 56 | Log.error(`Unknown error occurred.`); 57 | console.error(`[-] Unknown error occurred.`); 58 | } 59 | } 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /src/notifiers/custom_notifier.ts: -------------------------------------------------------------------------------- 1 | import Log from "../constants/log"; 2 | import { Notifier } from "./notifier"; 3 | 4 | export class CustomNotifier implements Notifier { 5 | private webhookUrl: string; 6 | private message: string; 7 | 8 | constructor(webhookUrl: string, message: string) { 9 | this.webhookUrl = webhookUrl; 10 | this.message = message; 11 | } 12 | 13 | validate(): void { 14 | if (!this.webhookUrl) { 15 | throw new Error("[-] Webhook URL is not set"); 16 | } 17 | 18 | const newUrl = new URL(this.webhookUrl); 19 | if (newUrl.protocol !== "http:" && newUrl.protocol !== "https:") { 20 | throw new Error("[-] Webhook URL is invalid."); 21 | } 22 | } 23 | 24 | async notify(): Promise { 25 | try { 26 | const response = await fetch(this.webhookUrl, { 27 | method: "POST", 28 | headers: { 29 | "Content-Type": "application/json", 30 | }, 31 | body: JSON.stringify({ 32 | text: this.message, 33 | }), 34 | }); 35 | 36 | if (!response.ok) { 37 | console.error( 38 | `[-] Failed to send notification to ${new URL( 39 | this.webhookUrl 40 | ).hostname.replace(".com", "")}: ${response.status} ${ 41 | response.statusText 42 | } ` 43 | ); 44 | } else { 45 | console.log( 46 | `[+] Notification sent successfully to ${new URL( 47 | this.webhookUrl 48 | ).hostname.replace(".com", "")}` 49 | ); 50 | } 51 | } catch (error: unknown) { 52 | if (error instanceof Error) { 53 | Log.error(`Error sending notification: ${error.message}`); 54 | console.error(`[-] Error sending notification: ${error.message}`); 55 | } else { 56 | Log.error(`Unknown error occurred.`); 57 | console.error(`[-] Unknown error occurred.`); 58 | } 59 | } 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /src/notifiers/discord_notifier.ts: -------------------------------------------------------------------------------- 1 | import Log from "../constants/log"; 2 | import { Notifier } from "./notifier"; 3 | 4 | export class DiscordNotifier implements Notifier { 5 | private webhookUrl: string; 6 | private message: string; 7 | 8 | constructor(webhookUrl: string, message: string) { 9 | this.webhookUrl = webhookUrl; 10 | this.message = message; 11 | } 12 | 13 | validate(): void { 14 | if (!this.webhookUrl) { 15 | throw new Error("[-] Webhook URL is not set"); 16 | } 17 | 18 | const newUrl = new URL(this.webhookUrl); 19 | if (newUrl.protocol !== "http:" && newUrl.protocol !== "https:") { 20 | throw new Error("[-] Webhook URL is invalid."); 21 | } 22 | } 23 | 24 | async notify(): Promise { 25 | try { 26 | const response = await fetch(this.webhookUrl, { 27 | method: "POST", 28 | headers: { 29 | "Content-Type": "application/json", 30 | }, 31 | body: JSON.stringify({ 32 | content: this.message, 33 | }), 34 | }); 35 | 36 | if (!response.ok) { 37 | console.error( 38 | `[-] Failed to send notification to ${new URL( 39 | this.webhookUrl 40 | ).hostname.replace(".com", "")}: ${response.status} ${ 41 | response.statusText 42 | } ` 43 | ); 44 | } else { 45 | console.log( 46 | `[+] Notification sent successfully to ${new URL( 47 | this.webhookUrl 48 | ).hostname.replace(".com", "")}` 49 | ); 50 | } 51 | } catch (error: unknown) { 52 | if (error instanceof Error) { 53 | Log.error(`Error sending notification: ${error.message}`); 54 | console.error(`[-] Error sending notification: ${error.message}`); 55 | } else { 56 | Log.error(`Unknown error occurred.`); 57 | console.error(`[-] Unknown error occurred.`); 58 | } 59 | } 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /src/notifiers/telegram_notifier.ts: -------------------------------------------------------------------------------- 1 | import Log from "../constants/log"; 2 | import { Notifier } from "./notifier"; 3 | 4 | export class TelegramNotifier implements Notifier { 5 | private webhookUrl: string; 6 | private message: string; 7 | private chatId: number; 8 | 9 | constructor(webhookUrl: string, message: string, chatId: number) { 10 | this.webhookUrl = webhookUrl; 11 | this.message = message; 12 | this.chatId = chatId; 13 | } 14 | 15 | validate(): void { 16 | if (!this.webhookUrl) { 17 | throw new Error("[-] Webhook URL is not set"); 18 | } 19 | 20 | if (!this.chatId) { 21 | throw new Error("[-] Chat Id is not set"); 22 | } 23 | 24 | const newUrl = new URL(this.webhookUrl); 25 | if (newUrl.protocol !== "http:" && newUrl.protocol !== "https:") { 26 | throw new Error("[-] Webhook URL is invalid."); 27 | } 28 | } 29 | 30 | async notify(): Promise { 31 | try { 32 | const response = await fetch(this.webhookUrl, { 33 | method: "POST", 34 | headers: { 35 | "Content-Type": "application/json", 36 | }, 37 | body: JSON.stringify({ 38 | text: this.message, 39 | chat_id: this.chatId, 40 | }), 41 | }); 42 | 43 | if (!response.ok) { 44 | console.error( 45 | `[-] Failed to send notification to ${new URL( 46 | this.webhookUrl 47 | ).hostname.replace(".com", "")}: ${response.status} ${ 48 | response.statusText 49 | } ` 50 | ); 51 | } else { 52 | console.log( 53 | `[+] Notification sent successfully to ${new URL( 54 | this.webhookUrl 55 | ).hostname.replace(".com", "")}` 56 | ); 57 | } 58 | } catch (error: unknown) { 59 | if (error instanceof Error) { 60 | Log.error(`Error sending notification: ${error.message}`); 61 | console.error(`[-] Error sending notification: ${error.message}`); 62 | } else { 63 | Log.error(`Unknown error occurred.`); 64 | console.error(`[-] Unknown error occurred.`); 65 | } 66 | } 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /docs/guide/cli/general.md: -------------------------------------------------------------------------------- 1 | # `general` Command Documentation 2 | 3 | The `general` command is used to configure the general settings of your `backupdbee.yaml` file. You can either use flags to update specific settings or use an interactive mode where you'll be prompted to provide input. 4 | 5 | ## Command: `general` 6 | 7 | ```bash 8 | ts-node index.ts general [options] 9 | ``` 10 | 11 | ### Description 12 | 13 | The `general` command allows you to modify the following general settings in the `backupdbee.yaml` file: 14 | 15 | - Backup location 16 | - Log location 17 | - Log level (INFO, DEBUG, ERROR) 18 | - Retention policy (number of days) 19 | - Backup schedule (in cron format) 20 | 21 | You can configure each setting individually using the provided flags or choose to use the interactive mode (i.e., no flags) to update settings step-by-step. 22 | 23 | --- 24 | 25 | ## Flags 26 | 27 | Below is a table describing each flag you can use with the `general` command. 28 | 29 | | Flag | Description | Example Command | 30 | | -------------------- | --------------------------------------------------------------------------- | --------------------------------------------------------------- | 31 | | `--backup-location` | Specify the directory where backups will be stored. | `ts-node index.ts general --backup-location "/path/to/backups"` | 32 | | `--log-location` | Set the directory where logs will be stored. | `ts-node index.ts general --log-location "/path/to/logs"` | 33 | | `--log-level` | Set the log verbosity level. Accepts values: `INFO`, `DEBUG`, `ERROR`. | `ts-node index.ts general --log-level DEBUG` | 34 | | `--retention-policy` | Specify how many days backups will be retained. Takes a number as an input. | `ts-node index.ts general --retention-policy 10` | 35 | | `--backup-schedule` | Set the cron schedule for automatic backups. | `ts-node index.ts general --backup-schedule "0 3 * * *"` | 36 | 37 | --- 38 | 39 | ## Interactive Mode 40 | 41 | If no flags are provided, the `general` command will enter an interactive mode, where you will be prompted to input values for each setting. 42 | -------------------------------------------------------------------------------- /src/commands/install.ts: -------------------------------------------------------------------------------- 1 | import { confirm } from "@clack/prompts"; 2 | import * as fs from "fs"; 3 | import process from "process"; 4 | import chalk from "chalk"; 5 | import { checkCommands } from "./commandChecker"; 6 | import { destinationFile, sourceFile } from "../utils/cli.utils"; 7 | 8 | /** 9 | * Creates a backupdbee.yaml file by reading the content from a source file and writing it to a destination file. 10 | * 11 | * @remarks 12 | * This function uses the `fs.readFile` and `fs.writeFile` methods to read and write files respectively. 13 | * It also utilizes a spinner to display the progress of the operation. 14 | * 15 | * @param sourceFile - The path to the source file. 16 | * @param destinationFile - The path to the destination file. 17 | */ 18 | const createBackupdbeeYaml = () => { 19 | fs.readFile(sourceFile, "utf8", (err, data) => { 20 | if (err) { 21 | console.error("Error reading the source file:", err); 22 | process.exit(0); 23 | } 24 | 25 | // Write the content to the destination file 26 | fs.writeFile(destinationFile, data, (err) => { 27 | if (err) { 28 | console.log(chalk.red(`Error writing to the destination file: ${err}`)); 29 | process.exit(0); 30 | } else { 31 | console.log(`\nFile copied successfully to ${destinationFile}`); 32 | } 33 | }); 34 | }); 35 | }; 36 | 37 | /** 38 | * Checks the necessary dependencies and create backupdbee.yaml file. 39 | * 40 | * @returns {Promise} A promise that resolves once the installation is complete. 41 | */ 42 | const install = async (): Promise => { 43 | const commands = ["zip", "pg_dump", "mysqldump", "pnpm", "node"]; 44 | checkCommands(commands); 45 | console.log(); 46 | 47 | try { 48 | // check if backupdbee.yaml file exists in root folder or not 49 | if (!fs.existsSync("backupdbee.yaml")) { 50 | createBackupdbeeYaml(); 51 | } else { 52 | const shouldContinue = await confirm({ 53 | message: "Backupdbee.yaml file exits. Do you want to override?", 54 | initialValue: false, 55 | }); 56 | if (!shouldContinue) { 57 | process.exit(0); 58 | } else { 59 | createBackupdbeeYaml(); 60 | } 61 | } 62 | 63 | console.log( 64 | "\nNext Step: Update the backupdbee.yaml file with your configurations." 65 | ); 66 | } catch (err) { 67 | console.log(err); 68 | } 69 | }; 70 | 71 | export default install; 72 | -------------------------------------------------------------------------------- /src/destinations/s3.ts: -------------------------------------------------------------------------------- 1 | import { Sender, SenderOption } from "./sender"; 2 | import { 3 | S3Client, 4 | PutObjectCommand, 5 | PutObjectCommandInput, 6 | } from "@aws-sdk/client-s3"; 7 | import { config } from "../utils/cli.utils"; 8 | 9 | export class S3Sender implements Sender { 10 | private static s3ClientInstance: S3Client | null = null; 11 | private static getS3ClientInstance(): S3Client { 12 | if (!S3Sender.s3ClientInstance) { 13 | S3Sender.s3ClientInstance = new S3Client({ 14 | region: config.destinations.s3_bucket.region, 15 | credentials: { 16 | accessKeyId: config.destinations.s3_bucket.access_key, 17 | secretAccessKey: config.destinations.s3_bucket.secret_key, 18 | }, 19 | }); 20 | } 21 | return S3Sender.s3ClientInstance; 22 | } 23 | 24 | private options: SenderOption; 25 | constructor(options: SenderOption) { 26 | this.options = options; 27 | } 28 | 29 | // Method to validate file information 30 | validate(fileName?: string): void { 31 | if (!fileName) { 32 | throw new Error("[-] File name is not set"); 33 | } 34 | } 35 | 36 | // Method to upload file to S3 37 | async uploadToS3(fileName?: string, fileContent?: unknown) { 38 | try { 39 | const uploadParams = { 40 | Bucket: config.destinations.s3_bucket.bucket_name, 41 | Key: fileName, 42 | Body: fileContent, 43 | ContentType: "application/octet-stream", 44 | }; 45 | 46 | const command = new PutObjectCommand( 47 | uploadParams as PutObjectCommandInput 48 | ); 49 | const s3Client = S3Sender.getS3ClientInstance(); 50 | 51 | const response = await s3Client.send(command); 52 | console.log("[+] File uploaded successfully:", response); 53 | } catch (err) { 54 | console.error("[-] Error uploading file:", err); 55 | } 56 | } 57 | 58 | // Method to send file to S3 59 | async send(options?: SenderOption): Promise { 60 | try { 61 | if (options?.fileName) { 62 | this.options.fileName = options.fileName; 63 | } 64 | if (options?.fileContent) { 65 | this.options.fileContent = options.fileContent; 66 | } 67 | await this.uploadToS3(this.options.fileName, this.options.fileContent); 68 | } catch (error: unknown) { 69 | if (error instanceof Error) { 70 | console.error(`[-] Error sending file to S3: ${error.message}`); 71 | } else { 72 | console.error(`[-] Unknown error occurred.`); 73 | } 74 | } 75 | } 76 | } 77 | -------------------------------------------------------------------------------- /src/commands/general.ts: -------------------------------------------------------------------------------- 1 | import { select, text } from "@clack/prompts"; 2 | import { promptWithCancel } from "./promptWithCancel"; 3 | import { config, saveConfig } from "../utils/cli.utils"; 4 | 5 | const general = async (options: { 6 | backupLocation?: string; 7 | logLocation?: string; 8 | logLevel?: string; 9 | retentionPolicy?: number; 10 | backupSchedule?: string; 11 | }) => { 12 | if (!Object.keys(options).length) { 13 | const backupLocation = await promptWithCancel(text, { 14 | message: "Enter backup location", 15 | initialValue: config.general.backup_location, 16 | }); 17 | 18 | const logLocation = await promptWithCancel(text, { 19 | message: "Enter log location", 20 | initialValue: config.general.log_location, 21 | }); 22 | 23 | const logLevel = await promptWithCancel(select, { 24 | message: "Select log level", 25 | options: [ 26 | { value: "INFO", label: "INFO" }, 27 | { value: "DEBUG", label: "DEBUG" }, 28 | { value: "ERROR", label: "ERROR" }, 29 | ], 30 | initialValue: config.general.log_level, 31 | }); 32 | 33 | const retentionPolicy = Number( 34 | await promptWithCancel(text, { 35 | message: "Enter retention policy (days)", 36 | initialValue: String(config.general.retention_policy_days), 37 | }) 38 | ); 39 | 40 | const backupSchedule = await promptWithCancel(text, { 41 | message: "Enter backup schedule (cron format)", 42 | initialValue: config.general.backup_schedule, 43 | }); 44 | 45 | config.general.backup_location = backupLocation as string; 46 | config.general.log_location = logLocation as string; 47 | config.general.log_level = logLevel as string; 48 | config.general.retention_policy_days = retentionPolicy; 49 | config.general.backup_schedule = backupSchedule as string; 50 | } else { 51 | // If flags are provided, use them to update the config directly 52 | if (options.backupLocation) 53 | config.general.backup_location = options.backupLocation; 54 | if (options.logLocation) config.general.log_location = options.logLocation; 55 | if (options.logLevel) config.general.log_level = options.logLevel; 56 | if (options.retentionPolicy) 57 | config.general.retention_policy_days = options.retentionPolicy; 58 | if (options.backupSchedule) 59 | config.general.backup_schedule = options.backupSchedule; 60 | } 61 | 62 | // Save the updated config back to the YAML file 63 | saveConfig(config); 64 | 65 | console.log("General settings updated successfully!"); 66 | }; 67 | 68 | export default general; 69 | -------------------------------------------------------------------------------- /src/destinations/email.ts: -------------------------------------------------------------------------------- 1 | import { createTransport } from "nodemailer"; 2 | import Log from "../constants/log"; 3 | import { Sender, SenderOption } from "./sender"; 4 | import Mail from "nodemailer/lib/mailer"; 5 | import { config } from "../utils/cli.utils"; 6 | 7 | export class EmailSender implements Sender { 8 | private static transporterInstance: Mail | null = null; 9 | private static getTransporter(): Mail { 10 | if (!EmailSender.transporterInstance) { 11 | EmailSender.transporterInstance = createTransport({ 12 | host: config.destinations.email.smtp_server, 13 | secure: true, 14 | requireTLS: true, 15 | auth: { 16 | user: config.destinations.email.smtp_username, 17 | pass: config.destinations.email.smtp_password, 18 | }, 19 | }); 20 | } 21 | return EmailSender.transporterInstance; 22 | } 23 | 24 | private mailOptions: Mail.Options; 25 | constructor(readonly from: string, readonly to: string[], filePath: string) { 26 | this.mailOptions = { 27 | from: from, 28 | to: to.join(","), 29 | subject: "Backup", 30 | html: "

Date : " + new Date() + "

", 31 | attachments: [{ path: filePath }], 32 | }; 33 | } 34 | 35 | validate(): void { 36 | if (!this.mailOptions.from) { 37 | throw new Error("[-] Email address is not set"); 38 | } 39 | 40 | const emailRegex = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}$/; 41 | if (!emailRegex.test(this.mailOptions.from as string)) { 42 | throw new Error("[-] Email address is invalid."); 43 | } 44 | 45 | if ( 46 | !config.destinations.email.smtp_username || 47 | !config.destinations.email.smtp_password 48 | ) { 49 | throw new Error("[-] MAIL_USER or MAIL_PASSWORD is not set"); 50 | } 51 | const transporter = EmailSender.getTransporter(); 52 | transporter.verify(function (error) { 53 | if (error) { 54 | console.log(error); 55 | Log.error("[-] Mail setup failed"); 56 | } else { 57 | console.log("[+] Sending backups..."); 58 | } 59 | }); 60 | } 61 | 62 | async send(option?: SenderOption): Promise { 63 | try { 64 | if (option?.fileName) { 65 | this.mailOptions.attachments = [{ path: option.fileName }]; 66 | } 67 | const transporter = EmailSender.getTransporter(); 68 | await transporter.sendMail(this.mailOptions); 69 | } catch (error: unknown) { 70 | if (error instanceof Error) { 71 | Log.error(`Error sending email: ${error.message}`); 72 | console.error(`[-] Error sending email: ${error.message}`); 73 | } else { 74 | Log.error(`Unknown error occurred.`); 75 | console.error(`[-] Unknown error occurred.`); 76 | } 77 | } 78 | } 79 | } 80 | -------------------------------------------------------------------------------- /src/utils/notify.utils.ts: -------------------------------------------------------------------------------- 1 | import { DumpInfo } from "../@types/types"; 2 | import Log from "../constants/log"; 3 | import { CustomNotifier } from "../notifiers/custom_notifier"; 4 | import { Notifier } from "../notifiers/notifier"; 5 | import { SlackNotifier } from "../notifiers/slack_notifier"; 6 | import { DiscordNotifier } from "../notifiers/discord_notifier"; 7 | import { Notifications } from "../@types/config"; 8 | import { NOTIFICATION } from "../constants/notifications"; 9 | import { TelegramNotifier } from "../notifiers/telegram_notifier"; 10 | 11 | export const sendNotification = async ( 12 | dumpInfo: DumpInfo, 13 | notifications: Notifications 14 | ) => { 15 | const notify_on = Object.keys(notifications) 16 | .filter((key) => notifications[key as keyof Notifications].enabled) 17 | .map((key) => key as keyof Notifications); 18 | 19 | const notifiers: Notifier[] = []; 20 | const message = `Backup completed successfully for database: ${ 21 | dumpInfo.databaseName 22 | } at ${new Date()}`; 23 | for (const medium of notify_on) { 24 | switch (medium.trim().toUpperCase()) { 25 | case NOTIFICATION.SLACK: 26 | notifiers.push( 27 | new SlackNotifier(notifications.slack.webhook_url, message) 28 | ); 29 | break; 30 | case NOTIFICATION.DISCORD: 31 | notifiers.push( 32 | new DiscordNotifier(notifications.discord.webhook_url, message) 33 | ); 34 | break; 35 | case NOTIFICATION.CUSTOM: 36 | notifiers.push( 37 | new CustomNotifier(notifications.custom.webhook_url, message) 38 | ); 39 | break; 40 | case NOTIFICATION.TELEGRAM: 41 | notifiers.push( 42 | new TelegramNotifier( 43 | notifications.telegram.webhook_url, 44 | message, 45 | notifications.telegram.chatId 46 | ) 47 | ); 48 | break; 49 | default: 50 | console.error(`[-] Unsupported notification medium: ${medium}`); 51 | Log.error(`Unsupported notification medium: ${medium}`); 52 | } 53 | } 54 | const run = notifyAllMedium(notifiers); 55 | run(); 56 | }; 57 | 58 | function notifyAllMedium(notifiers: Notifier[]) { 59 | return async () => { 60 | for (const notifier of notifiers) { 61 | try { 62 | notifier.validate(); 63 | await notifier.notify(); 64 | } catch (error: unknown) { 65 | if (error instanceof Error) { 66 | Log.error(`Validation or notification Error: ${error.message}`); 67 | console.error( 68 | `[-] Validation or notification Error: ${error.message}` 69 | ); 70 | } else { 71 | Log.error(`Unknown error occurred.`); 72 | console.error(`[-] Unknown error occurred.`); 73 | } 74 | } 75 | } 76 | }; 77 | } 78 | -------------------------------------------------------------------------------- /src/utils/location.utils.ts: -------------------------------------------------------------------------------- 1 | import { DumpInfo } from "../@types/types"; 2 | import Log from "../constants/log"; 3 | import { Destinations } from "../@types/config"; 4 | import { DESTINATION } from "../constants/notifications"; 5 | import { EmailSender } from "../destinations/email"; 6 | 7 | import { Sender } from "../destinations/sender"; 8 | import { S3Sender } from "../destinations/s3"; 9 | import * as fs from "fs"; 10 | import { LocalSender } from "../destinations/local"; 11 | 12 | export const sendToDestinations = async ( 13 | dumpInfo: DumpInfo, 14 | destinations: Destinations 15 | ) => { 16 | const sentToDestinations = Object.keys(destinations) 17 | .filter((key) => destinations[key as keyof Destinations].enabled) 18 | .map((key) => key as keyof Destinations); 19 | 20 | const senders: Sender[] = []; 21 | 22 | for (const sendToDestination of sentToDestinations) { 23 | switch (sendToDestination.trim().toUpperCase()) { 24 | case DESTINATION.EMAIL: 25 | Log.info("Sending to email"); 26 | senders.push( 27 | new EmailSender( 28 | destinations.email.from, 29 | destinations.email.to, 30 | dumpInfo.compressedFilePath 31 | ) 32 | ); 33 | 34 | break; 35 | case DESTINATION.S3_BUCKET: 36 | Log.info("Sending to S3"); 37 | senders.push( 38 | new S3Sender({ 39 | fileName: `${dumpInfo.dumpFilePath.split("/").pop()}.zip`, 40 | fileContent: fs.readFileSync(dumpInfo.compressedFilePath), 41 | }) 42 | ); 43 | break; 44 | 45 | case DESTINATION.LOCAL: 46 | Log.info("Sending to local"); 47 | senders.push( 48 | new LocalSender( 49 | destinations.local.path, 50 | dumpInfo.compressedFilePath 51 | ) 52 | ) 53 | break; 54 | 55 | default: 56 | console.error( 57 | `[-] Unsupported notification medium: ${sendToDestination}` 58 | ); 59 | Log.error(`Unsupported notification medium: ${sendToDestination}`); 60 | } 61 | } 62 | const run = notifyAllMedium(senders); 63 | run(); 64 | }; 65 | 66 | function notifyAllMedium(senders: Sender[]) { 67 | return async () => { 68 | for (const sender of senders) { 69 | try { 70 | sender.validate(); 71 | await sender.send(); 72 | } catch (error: unknown) { 73 | if (error instanceof Error) { 74 | Log.error(`Validation or notification Error: ${error.message}`); 75 | console.error( 76 | `[-] Validation or notification Error: ${error.message}` 77 | ); 78 | } else { 79 | Log.error(`Unknown error occurred.`); 80 | console.error(`[-] Unknown error occurred.`); 81 | } 82 | } 83 | } 84 | }; 85 | } 86 | -------------------------------------------------------------------------------- /docs/guide/configuration.md: -------------------------------------------------------------------------------- 1 | # BackupBee Configuration 2 | 3 | This document provides a comprehensive guide to configuring BackupBee using the `backupdbee.yaml` file. 4 | 5 | ## Table of Contents 6 | 7 | 1. [General Configuration](#general-configuration) 8 | 2. [Destinations](#destinations) 9 | 3. [Notifications](#notifications) 10 | 4. [Databases](#databases) 11 | 12 | ## General Configuration 13 | 14 | The `general` section contains global settings for BackupBee: 15 | 16 | ```yaml 17 | general: 18 | backup_location: backups 19 | log_location: logs 20 | log_level: INFO 21 | retention_policy_days: 7 22 | backup_schedule: "0 3 * * *" 23 | ``` 24 | 25 | - `backup_location`: Directory where backups are stored 26 | - `log_location`: Directory for log files 27 | - `log_level`: Logging verbosity (e.g., INFO, DEBUG, ERROR) 28 | - `retention_policy_days`: Number of days to retain backups 29 | - `backup_schedule`: Cron expression for backup schedule (default: 3 AM daily) 30 | 31 | ## Destinations 32 | 33 | BackupBee supports multiple backup destinations: 34 | 35 | ### Local Storage 36 | 37 | ```yaml 38 | destinations: 39 | local: 40 | enabled: true 41 | path: backups 42 | ``` 43 | 44 | - `enabled`: Set to `true` to use local storage 45 | - `path`: Directory path for local backups 46 | 47 | ### Amazon S3 48 | 49 | ```yaml 50 | s3: 51 | enabled: false 52 | bucket_name: backupbee 53 | region: us-east-1 54 | access_key: XXXXXXXXXXX 55 | secret_key: XXXXXXXXXXX 56 | ``` 57 | 58 | - `enabled`: Set to `true` to use S3 59 | - `bucket_name`: S3 bucket name 60 | - `region`: AWS region 61 | - `access_key`: AWS access key 62 | - `secret_key`: AWS secret key 63 | 64 | ### Email 65 | 66 | ```yaml 67 | email: 68 | enabled: false 69 | smtp_server: smtp.gmail.com 70 | smtp_port: 587 71 | smtp_username: 72 | smtp_password: 73 | from: no-reply@backupbee.com 74 | to: 75 | - master@backupbee.com 76 | ``` 77 | 78 | - `enabled`: Set to `true` to send backups via email 79 | - `smtp_server`: SMTP server address 80 | - `smtp_port`: SMTP port 81 | - `smtp_username`: SMTP username 82 | - `smtp_password`: SMTP password 83 | - `from`: Email address used for sending notifications 84 | - `to`: List of email addresses to receive notifications 85 | 86 | ## Notifications 87 | 88 | BackupBee can send notifications through various channels: 89 | 90 | ### Slack Notifications 91 | 92 | ```yaml 93 | slack: 94 | enabled: true 95 | webhook_url: https://hooks.slack.com/services/XXXXXXXXXXXXXXXXXXXXXXXX 96 | ``` 97 | 98 | ### Custom Webhook 99 | 100 | ```yaml 101 | custom: 102 | enabled: false 103 | web_url: https://backupbee.com/api/v1/backup 104 | ``` 105 | 106 | ### Discord Notifications 107 | 108 | ```yaml 109 | discord: 110 | enabled: false 111 | webhook_url: https://discord.com/api/webhooks/XXXXXXXXX/XXXXXXXXX 112 | ``` 113 | 114 | ### Telegram Notifications 115 | 116 | ```yaml 117 | telegram: 118 | enabled: true 119 | webhook_url: https://api.telegram.org/botXXXXXXXXXX:XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/sendMessage 120 | chatId: XXXXXXX 121 | ``` 122 | 123 | For required notification type, set `enabled` to `true` and provide the necessary credentials or webhook URLs. 124 | 125 | ## Databases 126 | 127 | Configure the databases you want to back up: 128 | 129 | ```yaml 130 | databases: 131 | - name: primary_db 132 | type: postgres 133 | host: localhost 134 | port: 5432 135 | username: postgres 136 | password: pass 137 | database_name: asterconsult 138 | backup_schedule: "0 3 * * *" 139 | ``` 140 | 141 | - `name`: A unique identifier for the database 142 | - `type`: Database type (e.g., postgres, mysql) 143 | - `host`: Database server hostname 144 | - `port`: Database server port 145 | - `username`: Database username 146 | - `password`: Database password 147 | - `database_name`: Name of the database to back up 148 | - `backup_schedule`: Cron expression for this specific database's backup schedule 149 | 150 | You can add multiple database configurations by repeating this structure. 151 | 152 | To comment out a database configuration, use the `#` symbol at the beginning of each line, as shown in the example for `secondary_db`. 153 | 154 | --- 155 | 156 | Remember to keep your `backupdbee.yaml` file secure, as it contains sensitive information such as database credentials and API keys. 157 | -------------------------------------------------------------------------------- /src/commands/database.ts: -------------------------------------------------------------------------------- 1 | import { Database, DataBeeConfig } from "../@types/config"; 2 | import chalk from "chalk"; 3 | import { spinner } from "@clack/prompts"; 4 | import { setupDBConfig, setupDestinations, setupNotifications } from "../setup"; 5 | import process from "process"; 6 | import { main } from ".."; 7 | import { config } from "../utils/cli.utils"; 8 | 9 | /** 10 | * Retrieves the list of databases from the configuration and logs them to the console. 11 | */ 12 | export const dbList = () => { 13 | console.log("Database List"); 14 | const databases = config.databases; 15 | if (databases && databases.length > 0) { 16 | databases.forEach((db: Database, index: number) => { 17 | console.log(`${index + 1}. ${db.name}`); 18 | }); 19 | 20 | console.log( 21 | `\n${chalk.yellow("Total databases:")} ${chalk.magenta(databases.length)}` 22 | ); 23 | } else { 24 | console.log(chalk.red("No databases found in configuration.")); 25 | } 26 | }; 27 | 28 | /** 29 | * Sets up the main function for performing database operations. 30 | * 31 | * @param config - The configuration object for setting up the main function. 32 | * @returns A Promise that resolves when the main function completes. 33 | */ 34 | const setupMainFunction = async (config: DataBeeConfig) => { 35 | const dbConfig = setupDBConfig(config); 36 | const destinations = setupDestinations(config); 37 | const notifications = setupNotifications(config); 38 | await main(dbConfig, destinations, notifications); 39 | }; 40 | 41 | /** 42 | * Backs up databases based on the provided options. 43 | * 44 | * @param options - An object containing optional parameters. 45 | * @param options.name - A comma-separated string of database names to back up. If not provided, all databases will be backed up. 46 | * 47 | * The function performs the following steps: 48 | * 1. If `options.name` is provided, it splits the name by commas to handle multiple databases. 49 | * 2. It filters the databases to find those that match any of the provided names. 50 | * 3. If matching databases are found, it updates the configuration to include only the selected databases and starts the backup process. 51 | * 4. If no matching databases are found, it logs an error message and exits the process. 52 | * 5. If `options.name` is not provided, it backs up all databases. 53 | * 6. In case of any errors during the backup process, it logs the error and a failure message. 54 | * 55 | * @throws Will log an error and exit the process if no matching databases are found. 56 | * @throws Will log an error message if the backup process fails. 57 | */ 58 | export const dbBackup = async (options: { name?: string }) => { 59 | const databases = config.databases; 60 | 61 | try { 62 | if (options.name) { 63 | // Split the name by commas to handle multiple databases 64 | const dbNames = options.name.split(",").map((name) => name.trim()); 65 | 66 | // Find the databases that match any of the names 67 | const selectedDatabases = databases.filter((db: Database) => 68 | dbNames.includes(db.name) 69 | ); 70 | // Extracting the names of the selected databases and not found databases from dbNames 71 | const selectedDatabaseNames = selectedDatabases.map( 72 | (db: Database) => db.name 73 | ); 74 | const notFoundDatabases = dbNames.filter( 75 | (name) => !selectedDatabaseNames.includes(name) 76 | ); 77 | 78 | if (selectedDatabases.length) { 79 | config.databases = selectedDatabases; 80 | const s = spinner(); 81 | if (notFoundDatabases.length) { 82 | console.log( 83 | chalk.yellow( 84 | `No matching databases found for: ${notFoundDatabases.join(", ")}` 85 | ) 86 | ); 87 | } 88 | s.start(`Backing up databases: ${selectedDatabaseNames.join(", ")}`); 89 | await setupMainFunction(config); // Call main function to backup selected databases 90 | s.stop(); 91 | } else { 92 | console.log( 93 | chalk.red(`No matching databases found for: ${dbNames.join(", ")}`) 94 | ); 95 | process.exit(1); 96 | } 97 | } else { 98 | // Backup all databases 99 | const s = spinner(); 100 | s.start("Backing up all databases"); 101 | await setupMainFunction(config); // Call main function to backup all databases 102 | s.stop(); 103 | } 104 | } catch (e) { 105 | console.log(e); 106 | console.log(chalk.red("Backup failed.")); 107 | } 108 | }; 109 | -------------------------------------------------------------------------------- /src/setup.ts: -------------------------------------------------------------------------------- 1 | import { DataBeeConfig, Destinations, Notifications } from "./@types/config"; 2 | import { ConfigType } from "./@types/types"; 3 | import Log from "./constants/log"; 4 | import { 5 | validateEmailDestination, 6 | validateLocalDestination, 7 | validateS3Destination, 8 | } from "./validators/destination"; 9 | 10 | import { 11 | validateDiscordNotification, 12 | validateSlackNotification, 13 | validateTelegramNotification, 14 | validateWebhookNotification, 15 | validateEmailNotification, 16 | } from "./validators/notification"; 17 | 18 | export function getDefaultPortOfDBType(type: string): number { 19 | switch (type) { 20 | case "postgres": 21 | return 5432; 22 | case "mysql": 23 | return 3306; 24 | default: 25 | return 0; 26 | } 27 | } 28 | 29 | export function setupDBConfig(dataBeeConfig: DataBeeConfig): ConfigType[] { 30 | if (dataBeeConfig.databases.length === 0) { 31 | Log.error("No database configurations found in the config file."); 32 | } 33 | 34 | const configs = dataBeeConfig.databases.map((db) => { 35 | return { 36 | host: db.host, 37 | db_name: db.database_name, 38 | user: db.username, 39 | password: db.password, 40 | type: db.type, 41 | port: db.port || getDefaultPortOfDBType(db.type), 42 | } as ConfigType; 43 | }); 44 | return configs; 45 | } 46 | 47 | export function setupDestinations(dataBeeConfig: DataBeeConfig): Destinations { 48 | if ( 49 | !dataBeeConfig?.destinations?.email?.enabled && 50 | !dataBeeConfig?.destinations?.s3_bucket?.enabled && 51 | !dataBeeConfig?.destinations?.local?.enabled 52 | ) { 53 | Log.error("No destination enabled in the config file."); 54 | return {} as Destinations; 55 | } 56 | const destinations: Destinations = { 57 | email: { 58 | enabled: false, 59 | }, 60 | s3_bucket: { 61 | enabled: false, 62 | }, 63 | local: { 64 | enabled: false, 65 | }, 66 | } as Destinations; 67 | if (dataBeeConfig?.destinations?.email?.enabled) { 68 | if (validateEmailDestination(dataBeeConfig?.destinations?.email)) { 69 | destinations.email = dataBeeConfig?.destinations?.email; 70 | } 71 | } 72 | if (dataBeeConfig?.destinations?.s3_bucket?.enabled) { 73 | if (validateS3Destination(dataBeeConfig?.destinations?.s3_bucket)) { 74 | destinations.s3_bucket = dataBeeConfig?.destinations?.s3_bucket; 75 | } 76 | } 77 | 78 | if (dataBeeConfig?.destinations?.local?.enabled) { 79 | if (validateLocalDestination(dataBeeConfig?.destinations?.local)) { 80 | destinations.local = dataBeeConfig?.destinations?.local; 81 | } 82 | } 83 | return destinations; 84 | } 85 | 86 | export function setupNotifications( 87 | dataBeeConfig: DataBeeConfig 88 | ): Notifications { 89 | if ( 90 | !dataBeeConfig?.notifications?.email?.enabled && 91 | !dataBeeConfig?.notifications?.discord?.enabled && 92 | !dataBeeConfig?.notifications?.slack?.enabled && 93 | !dataBeeConfig?.notifications?.custom?.enabled && 94 | !dataBeeConfig?.notifications?.telegram?.enabled 95 | ) { 96 | Log.error("No notifications are enabled in the config file."); 97 | return {} as Notifications; 98 | } 99 | const notifications: Notifications = { 100 | email: { 101 | enabled: false, 102 | }, 103 | discord: { 104 | enabled: false, 105 | }, 106 | slack: { 107 | enabled: false, 108 | }, 109 | custom: { 110 | enabled: false, 111 | }, 112 | telegram: { 113 | enabled: false, 114 | }, 115 | } as Notifications; 116 | 117 | if (dataBeeConfig?.notifications?.email?.enabled) { 118 | if (validateEmailNotification(dataBeeConfig?.notifications?.email)) { 119 | notifications.email = dataBeeConfig?.notifications?.email; 120 | } 121 | } 122 | if (dataBeeConfig?.notifications?.discord?.enabled) { 123 | if ( 124 | validateDiscordNotification( 125 | dataBeeConfig?.notifications?.discord?.webhook_url 126 | ) 127 | ) { 128 | notifications.discord = dataBeeConfig?.notifications?.discord; 129 | } 130 | } 131 | 132 | if (dataBeeConfig?.notifications?.slack?.enabled) { 133 | if ( 134 | validateSlackNotification( 135 | dataBeeConfig?.notifications?.slack?.webhook_url 136 | ) 137 | ) { 138 | notifications.slack = dataBeeConfig?.notifications?.slack; 139 | } 140 | } 141 | 142 | if (dataBeeConfig?.notifications?.custom?.enabled) { 143 | if ( 144 | validateWebhookNotification( 145 | dataBeeConfig?.notifications?.custom?.webhook_url 146 | ) 147 | ) { 148 | notifications.custom = dataBeeConfig?.notifications?.custom; 149 | } 150 | } 151 | 152 | if (dataBeeConfig?.notifications?.telegram?.enabled) { 153 | if ( 154 | validateTelegramNotification( 155 | dataBeeConfig?.notifications?.telegram.webhook_url, 156 | dataBeeConfig?.notifications?.telegram.chatId 157 | ) 158 | ) { 159 | notifications.telegram = dataBeeConfig?.notifications?.telegram; 160 | } 161 | } 162 | 163 | return notifications; 164 | } 165 | -------------------------------------------------------------------------------- /src/utils/backup.utils.ts: -------------------------------------------------------------------------------- 1 | import { createWriteStream, existsSync, mkdirSync, rmSync } from "fs"; 2 | import Log from "../constants/log"; 3 | import path from "path"; 4 | import { ConfigType, DumpInfo, DumpType } from "../@types/types"; 5 | import { execAsync } from ".."; 6 | import { handleMysqlDump } from "../dbs/mysql"; 7 | import { handlePostgresDump } from "../dbs/postgres"; 8 | import { Destinations } from "../@types/config"; 9 | import { sendToDestinations } from "./location.utils"; 10 | import { handleMongodbsDump } from "../dbs/mongo"; 11 | 12 | const ensureDirectory = (dirPath: string) => { 13 | if (!existsSync(dirPath)) { 14 | mkdirSync(dirPath, { recursive: true }); 15 | } 16 | }; 17 | 18 | const handleDumpError = ( 19 | err: string, 20 | databaseName: string, 21 | dumpFilePath: string 22 | ) => { 23 | console.error(`[-] Error spawning dump process: ${err}`); 24 | Log.error(`Cannot backup ${databaseName}`); 25 | if (existsSync(dumpFilePath)) { 26 | rmSync(dumpFilePath); 27 | rmSync(`${dumpFilePath}.zip`); 28 | } 29 | }; 30 | 31 | const handleDumpFailure = ( 32 | code: number, 33 | errorMsg: string | null, 34 | databaseName: string, 35 | dumpFilePath: string 36 | ) => { 37 | console.error( 38 | `[-] Dump process failed with code ${code}. Error: ${errorMsg}` 39 | ); 40 | Log.error(`Cannot backup ${databaseName}`); 41 | if (existsSync(dumpFilePath)) { 42 | rmSync(dumpFilePath); 43 | rmSync(`${dumpFilePath}.zip`); 44 | } 45 | }; 46 | 47 | const finalizeBackup = async ( 48 | dumpFilePath: string, 49 | databaseName: string, 50 | databaseType: string, 51 | destinations: Destinations 52 | ) => { 53 | const compressedFilePath = `${dumpFilePath}.zip`; 54 | console.log("compressedFilePath", compressedFilePath); 55 | try { 56 | await execAsync(`zip -j ${compressedFilePath} ${dumpFilePath}`); 57 | 58 | sendToDestinations( 59 | { 60 | databaseName, 61 | compressedFilePath, 62 | databaseType, 63 | dumpFilePath, 64 | dumpFileName: dumpFilePath.split("/").pop() as string, 65 | }, 66 | destinations 67 | ); 68 | 69 | return compressedFilePath; 70 | } catch (err: unknown) { 71 | console.error( 72 | `[-] Error compressing ${databaseName}: ${(err as Error).message}` 73 | ); 74 | Log.error(`Error compressing ${databaseName}`); 75 | return ""; 76 | } 77 | }; 78 | 79 | const backupHelper = async ( 80 | data: ConfigType, 81 | destinations: Destinations 82 | ): Promise => { 83 | const dumps: DumpType[] = [] as DumpType[]; 84 | let errorMsg: string | null = null; 85 | 86 | switch (data.type) { 87 | case "mysql": 88 | // NOTE: mutating the dumps array 89 | handleMysqlDump(data, dumps); 90 | break; 91 | case "postgres": 92 | // NOTE: mutating the dumps array 93 | handlePostgresDump(data, dumps); 94 | break; 95 | case"mongo": 96 | handleMongodbsDump(data,dumps) 97 | default: 98 | return Promise.reject( 99 | new Error(`[-] Unsupported database type: ${data.type}`) 100 | ); 101 | } 102 | 103 | // prepare for backup 104 | const timeStamp = Date.now().toString(); 105 | const backupDir = path.resolve("tmp"); 106 | ensureDirectory(backupDir); 107 | 108 | return new Promise((resolve, reject) => { 109 | dumps.forEach(({ databaseName, dumpedContent }) => { 110 | const dumpFileName = `${timeStamp}-${databaseName}.dump.sql`; 111 | const dumpFilePath = path.resolve(backupDir, dumpFileName); 112 | const writeStream = createWriteStream(dumpFilePath); 113 | 114 | dumpedContent.stdout.pipe(writeStream); 115 | 116 | dumpedContent.on("data", (chunk) => { 117 | errorMsg = chunk.toString(); 118 | Log.error(errorMsg ?? "Error occurred while dumping"); 119 | }); 120 | 121 | dumpedContent.on("error", (err) => { 122 | handleDumpError(err.message, databaseName, dumpFilePath); 123 | reject(new Error(`[-] Cannot backup ${databaseName}`)); 124 | }); 125 | 126 | dumpedContent.on("close", async (code: number) => { 127 | if (code !== 0 || errorMsg) { 128 | handleDumpFailure(code, errorMsg, databaseName, dumpFilePath); 129 | reject(new Error(`[-] Cannot backup ${databaseName}`)); 130 | return; 131 | } 132 | 133 | console.log(`[+] Backup of ${databaseName} completed successfully`); 134 | const compressedFilePath = await finalizeBackup( 135 | dumpFilePath, 136 | databaseName, 137 | data.type, 138 | destinations 139 | ); 140 | if (compressedFilePath) { 141 | // Remove locally created dump files. 142 | console.log(`[+] Removing dump file.. ${dumpFilePath}`); 143 | rmSync(dumpFilePath); 144 | rmSync(compressedFilePath); 145 | 146 | resolve({ 147 | databaseName, 148 | compressedFilePath, 149 | databaseType: data.type, 150 | dumpFilePath, 151 | dumpFileName, 152 | }); 153 | } else { 154 | reject(new Error(`Error compressing ${databaseName}`)); 155 | } 156 | }); 157 | }); 158 | }); 159 | }; 160 | 161 | export default backupHelper; 162 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------