torrent-gateway/scripts/setup_systemd.sh
enki b3204ea07a
Some checks are pending
CI Pipeline / Run Tests (push) Waiting to run
CI Pipeline / Lint Code (push) Waiting to run
CI Pipeline / Security Scan (push) Waiting to run
CI Pipeline / Build Docker Images (push) Blocked by required conditions
CI Pipeline / E2E Tests (push) Blocked by required conditions
first commit
2025-08-18 00:40:15 -07:00

411 lines
10 KiB
Bash
Executable File
Raw Permalink Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#!/bin/bash
# Systemd Setup Script
# Sets up Torrent Gateway as a systemd service without Docker
set -e
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(dirname "$SCRIPT_DIR")"
INSTALL_DIR="/opt/torrent-gateway"
SERVICE_USER="torrent-gateway"
SERVICE_GROUP="torrent-gateway"
echo "🚀 Torrent Gateway Systemd Setup"
echo "================================="
# Check if running as root
if [ "$EUID" -ne 0 ]; then
echo "❌ This script must be run as root"
echo "Please run: sudo $0"
exit 1
fi
# Parse command line arguments
ENABLE_MONITORING=false
while [[ $# -gt 0 ]]; do
case $1 in
--with-monitoring)
ENABLE_MONITORING=true
shift
;;
*)
echo "Unknown option: $1"
echo "Usage: $0 [--with-monitoring]"
exit 1
;;
esac
done
cd "$PROJECT_ROOT"
# Install dependencies
echo "📦 Installing system dependencies..."
apt-get update
apt-get install -y \
golang-go \
sqlite3 \
redis-server \
nginx \
logrotate \
curl \
jq \
bc
# Create service user
echo "👤 Creating service user..."
if ! id "$SERVICE_USER" &>/dev/null; then
useradd --system --home /nonexistent --shell /bin/false --create-home "$SERVICE_USER"
usermod -a -G "$SERVICE_GROUP" "$SERVICE_USER"
echo "✅ User $SERVICE_USER created"
else
echo " User $SERVICE_USER already exists"
fi
# Build application
echo "🔨 Building application..."
go build -o bin/gateway \
-ldflags "-X main.version=$(git describe --tags --always) -X main.buildTime=$(date -u +%Y-%m-%dT%H:%M:%SZ) -s -w" \
cmd/gateway/main.go
if [ ! -f "bin/gateway" ]; then
echo "❌ Build failed"
exit 1
fi
echo "✅ Application built successfully"
# Create installation directory
echo "📁 Setting up installation directory..."
mkdir -p "$INSTALL_DIR"/{bin,data,configs,logs,backups}
mkdir -p "$INSTALL_DIR/data"/{blobs,chunks}
# Copy files
cp bin/gateway "$INSTALL_DIR/bin/"
cp -r configs/* "$INSTALL_DIR/configs/" 2>/dev/null || true
cp -r scripts "$INSTALL_DIR/"
# Set permissions
chown -R "$SERVICE_USER:$SERVICE_GROUP" "$INSTALL_DIR"
chmod +x "$INSTALL_DIR/bin/gateway"
chmod +x "$INSTALL_DIR/scripts"/*.sh
echo "✅ Installation directory configured"
# Create systemd service file
echo "⚙️ Creating systemd service..."
cat > /etc/systemd/system/torrent-gateway.service << 'EOF'
[Unit]
Description=Torrent Gateway Server
After=network.target redis.service
Wants=redis.service
[Service]
Type=simple
User=torrent-gateway
Group=torrent-gateway
WorkingDirectory=/opt/torrent-gateway
ExecStart=/opt/torrent-gateway/bin/gateway
Restart=always
RestartSec=5
StandardOutput=journal
StandardError=journal
# Environment variables
Environment=PORT=9876
Environment=DB_PATH=/opt/torrent-gateway/data/metadata.db
Environment=BLOB_DIR=/opt/torrent-gateway/data/blobs
Environment=CHUNK_DIR=/opt/torrent-gateway/data/chunks
Environment=LOG_LEVEL=info
Environment=LOG_FORMAT=json
# Security settings
NoNewPrivileges=true
PrivateTmp=true
ProtectSystem=strict
ProtectHome=true
ReadWritePaths=/opt/torrent-gateway/data
ReadWritePaths=/opt/torrent-gateway/logs
# Resource limits
LimitNOFILE=65536
MemoryMax=2G
[Install]
WantedBy=multi-user.target
EOF
# Create Redis configuration
echo "🔧 Configuring Redis..."
cp /etc/redis/redis.conf /etc/redis/redis.conf.backup
cat > /etc/redis/redis.conf << 'EOF'
# Redis configuration for Torrent Gateway
bind 127.0.0.1
port 6379
daemonize yes
supervised systemd
pidfile /var/run/redis/redis-server.pid
logfile /var/log/redis/redis-server.log
dir /var/lib/redis
# Memory management
maxmemory 512mb
maxmemory-policy allkeys-lru
# Persistence
save 900 1
save 300 10
save 60 10000
# Security
protected-mode yes
EOF
# Setup log rotation
echo "📜 Setting up log rotation..."
cat > /etc/logrotate.d/torrent-gateway << 'EOF'
/opt/torrent-gateway/logs/*.log {
daily
missingok
rotate 30
compress
delaycompress
notifempty
copytruncate
su torrent-gateway torrent-gateway
}
EOF
# Create nginx configuration
echo "🌐 Configuring nginx..."
cat > /etc/nginx/sites-available/torrent-gateway << 'EOF'
upstream torrent_gateway {
server 127.0.0.1:9876 max_fails=3 fail_timeout=30s;
keepalive 32;
}
server {
listen 80;
server_name _;
client_max_body_size 1G;
# Security headers
add_header X-Content-Type-Options nosniff;
add_header X-Frame-Options DENY;
add_header X-XSS-Protection "1; mode=block";
location / {
proxy_pass http://torrent_gateway;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_cache_bypass $http_upgrade;
# Timeouts
proxy_connect_timeout 30s;
proxy_send_timeout 30s;
proxy_read_timeout 30s;
}
# Health check endpoint (bypass proxy for local checks)
location /health {
access_log off;
return 200 "healthy\n";
add_header Content-Type text/plain;
}
}
EOF
# Enable nginx site
ln -sf /etc/nginx/sites-available/torrent-gateway /etc/nginx/sites-enabled/
rm -f /etc/nginx/sites-enabled/default
# Test nginx configuration
nginx -t
# Install monitoring stack if requested
if [ "$ENABLE_MONITORING" = true ]; then
echo "📊 Installing monitoring stack..."
# Install Prometheus
PROMETHEUS_VERSION="2.48.0"
cd /tmp
wget "https://github.com/prometheus/prometheus/releases/download/v${PROMETHEUS_VERSION}/prometheus-${PROMETHEUS_VERSION}.linux-amd64.tar.gz"
tar -xzf "prometheus-${PROMETHEUS_VERSION}.linux-amd64.tar.gz"
mkdir -p /opt/prometheus
cp "prometheus-${PROMETHEUS_VERSION}.linux-amd64/prometheus" /opt/prometheus/
cp "prometheus-${PROMETHEUS_VERSION}.linux-amd64/promtool" /opt/prometheus/
cp -r "prometheus-${PROMETHEUS_VERSION}.linux-amd64/console_libraries" /opt/prometheus/
cp -r "prometheus-${PROMETHEUS_VERSION}.linux-amd64/consoles" /opt/prometheus/
# Copy Prometheus config
cp "$PROJECT_ROOT/configs/prometheus.yml" /opt/prometheus/
chown -R prometheus:prometheus /opt/prometheus
# Create Prometheus systemd service
cat > /etc/systemd/system/prometheus.service << 'EOF'
[Unit]
Description=Prometheus
After=network.target
[Service]
Type=simple
User=prometheus
Group=prometheus
ExecStart=/opt/prometheus/prometheus \
--config.file=/opt/prometheus/prometheus.yml \
--storage.tsdb.path=/opt/prometheus/data \
--web.console.templates=/opt/prometheus/consoles \
--web.console.libraries=/opt/prometheus/console_libraries \
--web.listen-address=0.0.0.0:9090 \
--web.external-url=http://localhost:9090/
Restart=always
RestartSec=5
[Install]
WantedBy=multi-user.target
EOF
# Create prometheus user
useradd --system --shell /bin/false prometheus || true
mkdir -p /opt/prometheus/data
chown -R prometheus:prometheus /opt/prometheus
# Install Grafana
echo "📈 Installing Grafana..."
wget -q -O - https://packages.grafana.com/gpg.key | apt-key add -
echo "deb https://packages.grafana.com/oss/deb stable main" | tee -a /etc/apt/sources.list.d/grafana.list
apt-get update
apt-get install -y grafana
# Copy Grafana configs
cp -r "$PROJECT_ROOT/configs/grafana"/* /etc/grafana/ 2>/dev/null || true
chown -R grafana:grafana /etc/grafana/
echo "✅ Monitoring stack installed"
fi
# Create startup script
echo "🔧 Creating startup script..."
cat > "$INSTALL_DIR/scripts/start.sh" << 'EOF'
#!/bin/bash
# Torrent Gateway Startup Script
set -e
INSTALL_DIR="/opt/torrent-gateway"
cd "$INSTALL_DIR"
echo "🚀 Starting Torrent Gateway"
# Check prerequisites
echo "🔍 Checking prerequisites..."
# Check Redis
if ! systemctl is-active --quiet redis-server; then
echo "❌ Redis is not running"
echo "Starting Redis..."
systemctl start redis-server
fi
# Initialize database if needed
if [ ! -f "data/metadata.db" ]; then
echo "🗄️ Initializing database..."
# Database will be created on first run
fi
# Run migrations
echo "🔄 Running database migrations..."
./scripts/migrate.sh
# Start main service
echo "✅ Prerequisites checked"
echo "🚀 Starting Torrent Gateway service..."
systemctl start torrent-gateway
systemctl enable torrent-gateway
echo "✅ Torrent Gateway started and enabled"
EOF
chmod +x "$INSTALL_DIR/scripts/start.sh"
# Create stop script
cat > "$INSTALL_DIR/scripts/stop.sh" << 'EOF'
#!/bin/bash
echo "🛑 Stopping Torrent Gateway"
systemctl stop torrent-gateway
systemctl disable torrent-gateway
if [ "$1" = "--stop-deps" ]; then
echo "🛑 Stopping dependencies..."
systemctl stop redis-server
systemctl stop nginx
systemctl stop prometheus 2>/dev/null || true
systemctl stop grafana-server 2>/dev/null || true
fi
echo "✅ Torrent Gateway stopped"
EOF
chmod +x "$INSTALL_DIR/scripts/stop.sh"
# Reload systemd and enable services
echo "🔄 Configuring systemd services..."
systemctl daemon-reload
# Enable Redis
systemctl enable redis-server
systemctl start redis-server
# Enable nginx
systemctl enable nginx
# Enable monitoring if installed
if [ "$ENABLE_MONITORING" = true ]; then
systemctl enable prometheus
systemctl enable grafana-server
systemctl start prometheus
systemctl start grafana-server
fi
# Enable and start nginx
systemctl start nginx
echo ""
echo "🎉 Torrent Gateway systemd setup completed!"
echo ""
echo "📋 Next steps:"
echo "1. Start the gateway:"
echo " $INSTALL_DIR/scripts/start.sh"
echo ""
echo "2. Check status:"
echo " systemctl status torrent-gateway"
echo " journalctl -u torrent-gateway -f"
echo ""
echo "3. Run health checks:"
echo " $INSTALL_DIR/scripts/health_check.sh"
echo ""
echo "📊 Service URLs:"
echo " Gateway API: http://localhost/api/"
echo " Admin Panel: http://localhost/admin"
if [ "$ENABLE_MONITORING" = true ]; then
echo " Prometheus: http://localhost:9090"
echo " Grafana: http://localhost:3000"
fi
echo ""
echo "🔧 Service management:"
echo " Start: sudo systemctl start torrent-gateway"
echo " Stop: sudo systemctl stop torrent-gateway"
echo " Restart: sudo systemctl restart torrent-gateway"
echo " Status: sudo systemctl status torrent-gateway"
echo " Logs: sudo journalctl -u torrent-gateway -f"