TESTINGDB / start.sh
sarveshpatel's picture
Update start.sh
2853c55 verified
#!/bin/bash
set -e
echo "=========================================="
echo "πŸš€ Starting PostgreSQL + pgweb Space"
echo "=========================================="
export HF_TOKEN="${HF_TOKEN:-}"
export XET_DATASET="${XET_DATASET:-}"
export PGPASSWORD="${POSTGRES_PASSWORD:-postgres123}"
# ============================================
# RESTORE FROM XET STORAGE
# ============================================
if [ -n "$HF_TOKEN" ] && [ -n "$XET_DATASET" ]; then
echo "πŸ“¦ Checking for backup in Xet dataset..."
python3 << 'RESTORE_SCRIPT'
import os
import sys
from pathlib import Path
try:
from huggingface_hub import hf_hub_download, list_repo_files
hf_token = os.environ.get('HF_TOKEN')
dataset_id = os.environ.get('XET_DATASET')
if not hf_token or not dataset_id:
sys.exit(0)
try:
files = list_repo_files(dataset_id, repo_type="dataset", token=hf_token)
if 'backup/pg_backup.sql' in files:
print(f"βœ… Found backup in {dataset_id}")
Path('/data/backup').mkdir(parents=True, exist_ok=True)
hf_hub_download(
repo_id=dataset_id,
filename="backup/pg_backup.sql",
repo_type="dataset",
token=hf_token,
local_dir="/data"
)
print("πŸ“₯ Backup downloaded")
else:
print("ℹ️ No backup found, starting fresh")
except Exception as e:
print(f"ℹ️ Dataset access note: {e}")
except Exception as e:
print(f"⚠️ Restore check: {e}")
RESTORE_SCRIPT
fi
# ============================================
# INITIALIZE POSTGRESQL
# ============================================
echo "πŸ—„οΈ Setting up PostgreSQL..."
if [ ! -f "/data/postgres/PG_VERSION" ]; then
echo "πŸ“ Initializing new PostgreSQL database..."
sudo -u postgres /usr/lib/postgresql/15/bin/initdb -D /data/postgres -E UTF8 --locale=C
# Configure authentication
echo "local all all trust" > /data/postgres/pg_hba.conf
echo "host all all 127.0.0.1/32 trust" >> /data/postgres/pg_hba.conf
echo "host all all ::1/128 trust" >> /data/postgres/pg_hba.conf
# Start temporarily
sudo -u postgres /usr/lib/postgresql/15/bin/pg_ctl -D /data/postgres -l /tmp/pg_init.log start
sleep 3
# Create database
sudo -u postgres createdb appdb
echo "βœ… Database 'appdb' created"
# Restore backup if exists
if [ -f "/data/backup/pg_backup.sql" ]; then
echo "πŸ”„ Restoring from backup..."
sudo -u postgres psql -d appdb -f /data/backup/pg_backup.sql 2>/dev/null || true
echo "βœ… Restore completed"
fi
# Stop temporary instance
sudo -u postgres /usr/lib/postgresql/15/bin/pg_ctl -D /data/postgres stop
sleep 2
echo "βœ… PostgreSQL initialized"
else
echo "βœ… PostgreSQL data exists"
fi
chown -R postgres:postgres /data/postgres
chmod 700 /data/postgres
echo "=========================================="
echo "πŸŽ‰ Starting services..."
echo ""
echo "πŸ“Š Web UI: https://your-space.hf.space"
echo "πŸ—„οΈ Database: appdb"
echo "=========================================="
exec /usr/bin/supervisord -c /etc/supervisor/conf.d/supervisord.conf