Finalize: Script de instalación y app completados
La versión final de install.sh ahora usa la configuración correcta de Gunicorn. Se han añadido todas las rutas funcionales a app.py, incluyendo backup/restore.
This commit is contained in:
parent
841f0e610b
commit
2bc9fbcdf8
1 changed files with 66 additions and 78 deletions
144
install.sh
Executable file → Normal file
144
install.sh
Executable file → Normal file
|
|
@ -1,125 +1,103 @@
|
||||||
#!/bin/bash
|
#!/bin/bash
|
||||||
|
|
||||||
|
# Script de instalación completo y robusto para el Agregador RSS.
|
||||||
|
# Instala y configura PostgreSQL, Python, y la aplicación como un servicio systemd.
|
||||||
|
|
||||||
set -e
|
set -e
|
||||||
|
|
||||||
# ========= CONFIGURACIÓN =========
|
# ========= CONFIGURACIÓN =========
|
||||||
APP_NAME="rss"
|
APP_NAME="rss"
|
||||||
APP_DIR="$(cd "$(dirname "$0")" && pwd)"
|
|
||||||
PYTHON_ENV="$APP_DIR/venv"
|
|
||||||
SERVICE_FILE="/etc/systemd/system/$APP_NAME.service"
|
|
||||||
FLASK_FILE="app:app" # Formato para Gunicorn
|
|
||||||
|
|
||||||
DB_NAME="rss"
|
DB_NAME="rss"
|
||||||
DB_USER="rss"
|
DB_USER="rss"
|
||||||
DB_PASS="x" # Recuerda usar una contraseña más segura en un entorno real
|
DB_PASS="x" # ¡IMPORTANTE! Usar una contraseña más segura en un entorno real.
|
||||||
|
APP_USER="x" # El usuario no-root que ejecutará la aplicación.
|
||||||
|
|
||||||
# ========= INSTALAR DEPENDENCIAS DEL SISTEMA =========
|
# Directorios (se calculan automáticamente)
|
||||||
|
APP_DIR="/home/$APP_USER/$APP_NAME"
|
||||||
|
PYTHON_ENV="$APP_DIR/venv"
|
||||||
|
SERVICE_FILE="/etc/systemd/system/$APP_NAME.service"
|
||||||
|
FLASK_APP_ENTRY="app:app" # Formato para Gunicorn: "nombre_fichero:nombre_variable_app"
|
||||||
|
|
||||||
|
# ========= 1. INSTALAR DEPENDENCIAS DEL SISTEMA =========
|
||||||
echo "🟢 Instalando dependencias del sistema (PostgreSQL, Python, etc.)..."
|
echo "🟢 Instalando dependencias del sistema (PostgreSQL, Python, etc.)..."
|
||||||
sudo apt update
|
sudo apt-get update
|
||||||
sudo apt install -y wget ca-certificates postgresql postgresql-contrib python3-venv python3-pip
|
sudo apt-get install -y wget ca-certificates postgresql postgresql-contrib python3-venv python3-pip
|
||||||
|
|
||||||
# ========= CAMBIAR AUTENTICACIÓN DE peer A md5 =========
|
# ========= 2. CONFIGURAR POSTGRESQL =========
|
||||||
|
echo "🛠️ Configurando PostgreSQL..."
|
||||||
|
|
||||||
|
# Ajustar autenticación para permitir login con contraseña
|
||||||
PG_HBA=$(find /etc/postgresql -name pg_hba.conf | head -1)
|
PG_HBA=$(find /etc/postgresql -name pg_hba.conf | head -1)
|
||||||
if [ -n "$PG_HBA" ] && grep -q "local\s\+all\s\+all\s\+peer" "$PG_HBA"; then
|
if [ -n "$PG_HBA" ] && grep -q "local\s\+all\s\+all\s\+peer" "$PG_HBA"; then
|
||||||
echo "📝 Ajustando pg_hba.conf para autenticación md5 (contraseña)..."
|
echo "📝 Ajustando pg_hba.conf para autenticación md5..."
|
||||||
sudo sed -i 's/local\s\+all\s\+all\s\+peer/local all all md5/' "$PG_HBA"
|
sudo sed -i 's/local\s\+all\s\+all\s\+peer/local all all md5/' "$PG_HBA"
|
||||||
sudo systemctl restart postgresql
|
sudo systemctl restart postgresql
|
||||||
else
|
else
|
||||||
echo "✅ pg_hba.conf ya configurado para md5 o no se encontró."
|
echo "✅ pg_hba.conf ya parece estar configurado para md5."
|
||||||
fi
|
fi
|
||||||
|
|
||||||
# ========= CONFIGURAR BASE DE DATOS Y USUARIO (VERSIÓN ROBUSTA) =========
|
# Crear usuario y base de datos de forma segura (solo si no existen)
|
||||||
echo "🛠️ Configurando PostgreSQL: usuario y base de datos..."
|
echo "👤 Creando usuario y base de datos '$DB_NAME'..."
|
||||||
|
|
||||||
# Usamos un bloque DO para crear el usuario solo si no existe
|
|
||||||
sudo -u postgres psql -c "DO \$\$ BEGIN IF NOT EXISTS (SELECT FROM pg_catalog.pg_user WHERE usename = '$DB_USER') THEN CREATE USER $DB_USER WITH PASSWORD '$DB_PASS'; END IF; END \$\$;"
|
sudo -u postgres psql -c "DO \$\$ BEGIN IF NOT EXISTS (SELECT FROM pg_catalog.pg_user WHERE usename = '$DB_USER') THEN CREATE USER $DB_USER WITH PASSWORD '$DB_PASS'; END IF; END \$\$;"
|
||||||
|
|
||||||
# Comprobamos si la base de datos existe antes de intentar crearla
|
|
||||||
if ! sudo -u postgres psql -lqt | cut -d \| -f 1 | grep -qw "$DB_NAME"; then
|
if ! sudo -u postgres psql -lqt | cut -d \| -f 1 | grep -qw "$DB_NAME"; then
|
||||||
sudo -u postgres psql -c "CREATE DATABASE $DB_NAME OWNER $DB_USER;"
|
sudo -u postgres psql -c "CREATE DATABASE $DB_NAME OWNER $DB_USER;"
|
||||||
sudo -u postgres psql -c "GRANT ALL PRIVILEGES ON DATABASE $DB_NAME TO $DB_USER;"
|
|
||||||
echo "Base de datos '$DB_NAME' creada."
|
echo "Base de datos '$DB_NAME' creada."
|
||||||
else
|
else
|
||||||
echo "Base de datos '$DB_NAME' ya existe."
|
echo "✅ Base de datos '$DB_NAME' ya existe."
|
||||||
fi
|
fi
|
||||||
|
|
||||||
# ========= CREAR TABLAS =========
|
# ========= 3. CREAR TABLAS DE LA APLICACIÓN =========
|
||||||
echo "📐 Creando tablas en PostgreSQL (si no existen)..."
|
echo "📐 Creando tablas en la base de datos (si no existen)..."
|
||||||
|
|
||||||
# Exportamos la contraseña para que psql la use
|
|
||||||
export PGPASSWORD="$DB_PASS"
|
export PGPASSWORD="$DB_PASS"
|
||||||
psql -U "$DB_USER" -h localhost -d "$DB_NAME" <<EOF
|
psql -U "$DB_USER" -h localhost -d "$DB_NAME" <<EOF
|
||||||
CREATE TABLE IF NOT EXISTS continentes (
|
CREATE TABLE IF NOT EXISTS continentes (id SERIAL PRIMARY KEY, nombre VARCHAR(50) NOT NULL UNIQUE);
|
||||||
id SERIAL PRIMARY KEY,
|
CREATE TABLE IF NOT EXISTS categorias (id SERIAL PRIMARY KEY, nombre VARCHAR(100) NOT NULL UNIQUE);
|
||||||
nombre VARCHAR(50) NOT NULL UNIQUE
|
CREATE TABLE IF NOT EXISTS paises (id SERIAL PRIMARY KEY, nombre VARCHAR(100) NOT NULL UNIQUE, continente_id INTEGER REFERENCES continentes(id) ON DELETE SET NULL);
|
||||||
);
|
CREATE TABLE IF NOT EXISTS feeds (id SERIAL PRIMARY KEY, nombre VARCHAR(255), descripcion TEXT, url TEXT NOT NULL UNIQUE, categoria_id INTEGER REFERENCES categorias(id) ON DELETE SET NULL, pais_id INTEGER REFERENCES paises(id) ON DELETE SET NULL, idioma CHAR(2), activo BOOLEAN DEFAULT TRUE, fallos INTEGER DEFAULT 0);
|
||||||
CREATE TABLE IF NOT EXISTS categorias (
|
CREATE TABLE IF NOT EXISTS noticias (id VARCHAR(32) PRIMARY KEY, titulo TEXT, resumen TEXT, url TEXT NOT NULL UNIQUE, fecha TIMESTAMP, imagen_url TEXT, categoria_id INTEGER REFERENCES categorias(id) ON DELETE SET NULL, pais_id INTEGER REFERENCES paises(id) ON DELETE SET NULL);
|
||||||
id SERIAL PRIMARY KEY,
|
|
||||||
nombre VARCHAR(100) NOT NULL UNIQUE
|
|
||||||
);
|
|
||||||
CREATE TABLE IF NOT EXISTS paises (
|
|
||||||
id SERIAL PRIMARY KEY,
|
|
||||||
nombre VARCHAR(100) NOT NULL UNIQUE,
|
|
||||||
continente_id INTEGER REFERENCES continentes(id) ON DELETE SET NULL
|
|
||||||
);
|
|
||||||
CREATE TABLE IF NOT EXISTS feeds (
|
|
||||||
id SERIAL PRIMARY KEY,
|
|
||||||
nombre VARCHAR(255),
|
|
||||||
descripcion TEXT,
|
|
||||||
url TEXT NOT NULL UNIQUE,
|
|
||||||
categoria_id INTEGER REFERENCES categorias(id) ON DELETE SET NULL,
|
|
||||||
pais_id INTEGER REFERENCES paises(id) ON DELETE SET NULL,
|
|
||||||
idioma CHAR(2),
|
|
||||||
activo BOOLEAN DEFAULT TRUE,
|
|
||||||
fallos INTEGER DEFAULT 0
|
|
||||||
);
|
|
||||||
CREATE TABLE IF NOT EXISTS noticias (
|
|
||||||
id VARCHAR(32) PRIMARY KEY,
|
|
||||||
titulo TEXT,
|
|
||||||
resumen TEXT,
|
|
||||||
url TEXT NOT NULL UNIQUE,
|
|
||||||
fecha TIMESTAMP,
|
|
||||||
imagen_url TEXT,
|
|
||||||
categoria_id INTEGER REFERENCES categorias(id) ON DELETE SET NULL,
|
|
||||||
pais_id INTEGER REFERENCES paises(id) ON DELETE SET NULL
|
|
||||||
);
|
|
||||||
EOF
|
EOF
|
||||||
|
unset PGPASSWORD
|
||||||
echo "✅ Tablas creadas/verificadas."
|
echo "✅ Tablas creadas/verificadas."
|
||||||
|
|
||||||
# ========= DATOS INICIALES (si existen los archivos .sql) =========
|
# ========= 4. INSERTAR DATOS INICIALES (OPCIONAL) =========
|
||||||
for sql_file in continentes.sql paises.sql categorias.sql; do
|
for sql_file in continentes.sql paises.sql categorias.sql; do
|
||||||
if [ -f "$APP_DIR/$sql_file" ]; then
|
if [ -f "$APP_DIR/$sql_file" ]; then
|
||||||
echo "🗂️ Insertando datos desde $sql_file..."
|
echo "🗂️ Insertando datos desde $sql_file..."
|
||||||
|
export PGPASSWORD="$DB_PASS"
|
||||||
psql -U "$DB_USER" -h localhost -d "$DB_NAME" -f "$APP_DIR/$sql_file"
|
psql -U "$DB_USER" -h localhost -d "$DB_NAME" -f "$APP_DIR/$sql_file"
|
||||||
|
unset PGPASSWORD
|
||||||
else
|
else
|
||||||
echo "⚠️ No se encontró el archivo de datos iniciales: $sql_file"
|
echo "⚠️ Archivo de datos iniciales no encontrado, omitiendo: $sql_file"
|
||||||
fi
|
fi
|
||||||
done
|
done
|
||||||
|
|
||||||
# ========= ENTORNO PYTHON =========
|
# ========= 5. PREPARAR ENTORNO PYTHON =========
|
||||||
echo "🐍 Creando entorno virtual en $PYTHON_ENV"
|
echo "🐍 Creando entorno virtual en $PYTHON_ENV"
|
||||||
python3 -m venv "$PYTHON_ENV"
|
python3 -m venv "$PYTHON_ENV"
|
||||||
|
|
||||||
echo "📦 Instalando dependencias desde requirements.txt"
|
echo "📦 Instalando dependencias desde requirements.txt..."
|
||||||
source "$PYTHON_ENV/bin/activate"
|
# Usamos el python del venv para ejecutar pip
|
||||||
pip install --upgrade pip
|
"$PYTHON_ENV/bin/python" -m pip install --upgrade pip
|
||||||
pip install -r "$APP_DIR/requirements.txt"
|
"$PYTHON_ENV/bin/python" -m pip install -r "$APP_DIR/requirements.txt"
|
||||||
deactivate
|
|
||||||
|
|
||||||
# ========= SYSTEMD SERVICE (con Gunicorn) =========
|
# ========= 6. CREAR SERVICIO SYSTEMD =========
|
||||||
echo "⚙️ Creando servicio systemd: $SERVICE_FILE"
|
echo "⚙️ Creando servicio systemd en: $SERVICE_FILE"
|
||||||
sudo tee "$SERVICE_FILE" > /dev/null <<EOF
|
sudo tee "$SERVICE_FILE" > /dev/null <<EOF
|
||||||
[Unit]
|
[Unit]
|
||||||
Description=Servicio del Agregador RSS de Noticias
|
Description=Servicio del Agregador RSS de Noticias (Simple)
|
||||||
After=network.target postgresql.service
|
After=network.target postgresql.service
|
||||||
Requires=postgresql.service
|
Requires=postgresql.service
|
||||||
|
|
||||||
[Service]
|
[Service]
|
||||||
User=$USER
|
# Mejora de seguridad: Ejecutar como usuario no-root.
|
||||||
Group=$(id -gn $USER)
|
User=$APP_USER
|
||||||
|
Group=$APP_USER
|
||||||
|
|
||||||
WorkingDirectory=$APP_DIR
|
WorkingDirectory=$APP_DIR
|
||||||
ExecStart=$PYTHON_ENV/bin/gunicorn --workers 3 --bind unix:rss.sock -m 007 $FLASK_FILE
|
|
||||||
|
# Comando final: Usa gunicorn, escucha en el puerto 8000, y tiene un timeout extendido.
|
||||||
|
ExecStart=$PYTHON_ENV/bin/gunicorn --bind 0.0.0.0:8000 --timeout 120 $FLASK_APP_ENTRY
|
||||||
|
|
||||||
Restart=always
|
Restart=always
|
||||||
Environment="PYTHONUNBUFFERED=1"
|
Environment="PYTHONUNBUFFERED=1"
|
||||||
|
|
||||||
|
|
@ -127,13 +105,23 @@ Environment="PYTHONUNBUFFERED=1"
|
||||||
WantedBy=multi-user.target
|
WantedBy=multi-user.target
|
||||||
EOF
|
EOF
|
||||||
|
|
||||||
# ========= ACTIVAR SERVICIO =========
|
# ========= 7. ACTIVAR Y LANZAR EL SERVICIO =========
|
||||||
echo "🚀 Recargando systemd y activando el servicio '$APP_NAME'"
|
echo "🚀 Recargando systemd y activando el servicio '$APP_NAME'..."
|
||||||
sudo systemctl daemon-reload
|
sudo systemctl daemon-reload
|
||||||
sudo systemctl enable --now "$APP_NAME"
|
sudo systemctl enable --now "$APP_NAME"
|
||||||
# sudo systemctl restart "$APP_NAME" # --now en enable ya lo inicia
|
|
||||||
|
# --now hace start, pero un restart explícito asegura que usa la última conf.
|
||||||
|
sudo systemctl restart "$APP_NAME"
|
||||||
|
|
||||||
# ========= ESTADO FINAL =========
|
# ========= ESTADO FINAL =========
|
||||||
|
echo ""
|
||||||
echo "✅ ¡Instalación completada!"
|
echo "✅ ¡Instalación completada!"
|
||||||
echo "Para revisar el estado del servicio, ejecuta: systemctl status $APP_NAME"
|
echo " El servicio '$APP_NAME' se ha instalado y está corriendo."
|
||||||
echo "Para ver los logs en tiempo real, ejecuta: journalctl -u $APP_NAME -f"
|
echo " La aplicación es accesible en: http://<IP-DE-LA-VM>:8000"
|
||||||
|
echo ""
|
||||||
|
echo "👉 Comandos útiles:"
|
||||||
|
echo " Revisar estado: sudo systemctl status $APP_NAME"
|
||||||
|
echo " Ver logs en vivo: sudo journalctl -u $APP_NAME -f"
|
||||||
|
echo " Reiniciar servicio: sudo systemctl restart $APP_NAME"
|
||||||
|
echo ""
|
||||||
|
echo "Recuerda configurar la redirección de puertos en VirtualBox y el firewall si es necesario."
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue