Skip to content

Commit c904709

Browse files
authored
Merge pull request #10 from nipreps/codex/create-crontab-script-for-daily-database-backup
Add MongoDB backup script
2 parents 645dd85 + 4fa6031 commit c904709

File tree

2 files changed

+53
-0
lines changed

2 files changed

+53
-0
lines changed

README.md

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,3 +39,15 @@ python src/run.py plot
3939

4040
will generate the performance and version stream plots using the records stored
4141
in MongoDB.
42+
43+
## MongoDB backup script
44+
45+
`scripts/backup_mongodb.sh` dumps a MongoDB database to a Dropbox-synced
46+
folder. The script starts `mongod` if it is not running and stops it again
47+
when the backup finishes (if it was started by the script).
48+
49+
Make it executable before scheduling it with `cron`:
50+
51+
```bash
52+
chmod +x scripts/backup_mongodb.sh
53+
```

scripts/backup_mongodb.sh

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
#!/bin/bash
2+
# scripts/backup_mongodb.sh
3+
# Backup MongoDB database, ensuring mongod is running.
4+
5+
DATE=$(date +%Y-%m-%d)
6+
BACKUP_DIR="$HOME/Dropbox/backups"
7+
DBNAME="DBNAME"
8+
USERNAME="USERNAME"
9+
PASSWORD="PASSWORD"
10+
BACKUP_PATH="$BACKUP_DIR/db_backup_${DATE}"
11+
12+
mkdir -p "$BACKUP_DIR"
13+
14+
# Track whether we started mongod
15+
started_mongod=false
16+
17+
# Check if mongod process is running
18+
if pgrep mongod >/dev/null; then
19+
echo "mongod is running"
20+
else
21+
echo "mongod is not running. Starting..."
22+
if command -v systemctl >/dev/null; then
23+
sudo systemctl start mongod
24+
else
25+
sudo service mongod start
26+
fi
27+
started_mongod=true
28+
fi
29+
30+
# Dump the database
31+
mongodump --db "$DBNAME" --username "$USERNAME" --password "$PASSWORD" --out "$BACKUP_PATH"
32+
33+
# Stop mongod if we started it
34+
if [ "$started_mongod" = true ]; then
35+
echo "Stopping mongod..."
36+
if command -v systemctl >/dev/null; then
37+
sudo systemctl stop mongod
38+
else
39+
sudo service mongod stop
40+
fi
41+
fi

0 commit comments

Comments
 (0)