#!/bin/bash # WebRTC Server Setup Script for VM # This script sets up and configures the WebRTC server on a fresh VM set -e # Exit on error echo "================================================" echo "WebRTC Server Setup for Goodspace Voice Agent" echo "================================================" # Color codes for output RED='\033[0;31m' GREEN='\033[0;32m' YELLOW='\033[1;33m' NC='\033[0m' # No Color # Function to print colored output print_status() { echo -e "${GREEN}[✓]${NC} $1" } print_error() { echo -e "${RED}[✗]${NC} $1" } print_warning() { echo -e "${YELLOW}[!]${NC} $1" } # Check if running as root if [[ $EUID -eq 0 ]]; then print_error "This script should not be run as root" exit 1 fi # Step 1: System Update print_status "Updating system packages..." sudo apt-get update sudo apt-get upgrade -y # Step 2: Install System Dependencies print_status "Installing system dependencies..." sudo apt-get install -y \ python3.10 \ python3.10-venv \ python3-pip \ git \ build-essential \ libssl-dev \ libffi-dev \ python3-dev \ libopus0 \ libopus-dev \ ffmpeg \ redis-server \ nginx \ certbot \ python3-certbot-nginx \ htop \ net-tools \ ufw # Step 3: Configure Firewall print_status "Configuring firewall..." sudo ufw allow 22/tcp # SSH sudo ufw allow 80/tcp # HTTP sudo ufw allow 443/tcp # HTTPS sudo ufw allow 8080/tcp # WebSocket signaling sudo ufw allow 8081/tcp # Alternative WebSocket sudo ufw allow 3478/udp # STUN sudo ufw allow 3478/tcp # STUN sudo ufw allow 5349/tcp # TURN over TLS sudo ufw allow 5349/udp # TURN over DTLS sudo ufw allow 49152:65535/udp # WebRTC media ports # Enable firewall (interactive - will ask for confirmation) print_warning "Enabling firewall - make sure SSH (port 22) is allowed!" sudo ufw --force enable # Step 4: Install and Configure Redis print_status "Configuring Redis..." sudo systemctl enable redis-server sudo systemctl start redis-server # Configure Redis for production sudo bash -c 'cat >> /etc/redis/redis.conf << EOF # WebRTC Server Custom Configuration maxmemory 2gb maxmemory-policy allkeys-lru tcp-keepalive 60 timeout 300 EOF' sudo systemctl restart redis-server # Step 5: Create Application Directory print_status "Setting up application directory..." APP_DIR="/opt/goodspace-voice-webrtc" sudo mkdir -p $APP_DIR sudo chown $USER:$USER $APP_DIR # Step 6: Clone or Copy Application Code print_status "Setting up application code..." if [ -d "$APP_DIR/webrtc" ]; then print_warning "Application directory already exists, skipping clone" else # In production, you would clone from git # git clone https://github.com/your-repo/goodspace-voice.git $APP_DIR # For now, we'll create the structure mkdir -p $APP_DIR/webrtc mkdir -p $APP_DIR/logs mkdir -p $APP_DIR/scripts print_warning "Please copy your WebRTC module files to $APP_DIR/webrtc/" fi # Step 7: Setup Conda Environment print_status "Setting up conda environment..." cd $APP_DIR # Source conda initialization source /home/azureuser/miniconda3/etc/profile.d/conda.sh # Create conda environment named 'gsva' if it doesn't exist if ! conda env list | grep -q "gsva"; then print_status "Creating conda environment 'gsva'..." conda create -n gsva python=3.10 -y else print_status "Conda environment 'gsva' already exists" fi # Activate the conda environment conda activate gsva # Step 8: Install Python Dependencies print_status "Installing Python dependencies..." pip install --upgrade pip pip install wheel setuptools # Create requirements file if it doesn't exist if [ ! -f "$APP_DIR/requirements.txt" ]; then cat > $APP_DIR/requirements.txt << 'EOF' # WebRTC Server Requirements aiortc>=1.6.0 aiohttp>=3.9.0 websockets>=12.0 av>=11.0.0 numpy>=1.24.0 scipy>=1.11.0 psutil>=5.9.0 pyjwt>=2.8.0 redis>=5.0.0 aioredis>=2.0.0 prometheus-client>=0.19.0 EOF fi pip install -r requirements.txt # Step 9: Create Environment Configuration print_status "Creating environment configuration..." cat > $APP_DIR/.env << EOF # WebRTC Server Environment Configuration JWT_SECRET=$(openssl rand -hex 32) REDIS_URL=redis://localhost:6379 LOG_LEVEL=INFO # TURN Server Configuration (optional) # TURN_SERVER_URL=turn:your-turn-server.com:3478 # TURN_USERNAME=username # TURN_PASSWORD=password # SSL Configuration (for production) SSL_CERT_PATH=/etc/letsencrypt/live/your-domain.com/fullchain.pem SSL_KEY_PATH=/etc/letsencrypt/live/your-domain.com/privkey.pem EOF chmod 600 $APP_DIR/.env # Step 10: Create Systemd Service print_status "Creating systemd service..." sudo tee /etc/systemd/system/webrtc-signaling.service > /dev/null << EOF [Unit] Description=WebRTC Signaling Server for Goodspace Voice Agent After=network.target redis-server.service Requires=redis-server.service [Service] Type=simple User=$USER WorkingDirectory=$APP_DIR Environment="PATH=/home/azureuser/miniconda3/envs/gsva/bin" EnvironmentFile=$APP_DIR/.env ExecStartPre=/bin/bash -c 'source /home/azureuser/miniconda3/etc/profile.d/conda.sh && conda activate gsva' ExecStart=/home/azureuser/miniconda3/envs/gsva/bin/python webrtc/run_server.py --host 0.0.0.0 --port 8080 Restart=always RestartSec=10 StandardOutput=append:$APP_DIR/logs/signaling.log StandardError=append:$APP_DIR/logs/signaling-error.log [Install] WantedBy=multi-user.target EOF # Step 11: Create Nginx Configuration print_status "Configuring Nginx reverse proxy..." sudo tee /etc/nginx/sites-available/webrtc > /dev/null << 'EOF' upstream webrtc_backend { server localhost:8080; } server { listen 80; server_name _; # Replace with your domain # WebSocket configuration location /ws { proxy_pass http://webrtc_backend; 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; # WebSocket timeout proxy_read_timeout 86400; proxy_send_timeout 86400; } # Health check endpoint location /health { proxy_pass http://webrtc_backend; proxy_set_header Host $host; } # Statistics endpoint location /stats { proxy_pass http://webrtc_backend; proxy_set_header Host $host; } # Static files (if any) location / { root /var/www/html; try_files $uri $uri/ =404; } } EOF sudo ln -sf /etc/nginx/sites-available/webrtc /etc/nginx/sites-enabled/ sudo nginx -t sudo systemctl restart nginx # Step 12: Create Start/Stop Scripts print_status "Creating management scripts..." # Start script cat > $APP_DIR/scripts/start.sh << 'EOF' #!/bin/bash echo "Starting WebRTC services..." sudo systemctl start redis-server sudo systemctl start webrtc-signaling sudo systemctl start nginx echo "Services started. Check status with: ./scripts/status.sh" EOF # Stop script cat > $APP_DIR/scripts/stop.sh << 'EOF' #!/bin/bash echo "Stopping WebRTC services..." sudo systemctl stop webrtc-signaling echo "Services stopped." EOF # Status script cat > $APP_DIR/scripts/status.sh << 'EOF' #!/bin/bash echo "=== WebRTC Service Status ===" echo "" echo "Signaling Server:" sudo systemctl status webrtc-signaling --no-pager | head -n 10 echo "" echo "Redis Server:" sudo systemctl status redis-server --no-pager | head -n 5 echo "" echo "Nginx:" sudo systemctl status nginx --no-pager | head -n 5 echo "" echo "=== Port Status ===" sudo netstat -tlnp | grep -E ":(8080|6379|80|443)" echo "" echo "=== Recent Logs ===" tail -n 10 $APP_DIR/logs/signaling.log 2>/dev/null || echo "No logs yet" EOF # Logs script cat > $APP_DIR/scripts/logs.sh << 'EOF' #!/bin/bash tail -f $APP_DIR/logs/signaling.log EOF chmod +x $APP_DIR/scripts/*.sh # Step 13: Create Monitoring Script cat > $APP_DIR/scripts/monitor.sh << 'EOF' #!/bin/bash watch -n 1 ' echo "=== WebRTC Server Monitor ===" echo "" echo "System Resources:" echo "CPU: $(top -bn1 | grep "Cpu(s)" | awk "{print \$2}")" echo "Memory: $(free -h | grep "^Mem" | awk "{print \$3 \" / \" \$2}")" echo "" echo "Service Status:" systemctl is-active webrtc-signaling redis-server nginx | xargs echo echo "" echo "Connections:" netstat -an | grep ":8080" | grep ESTABLISHED | wc -l | xargs echo "WebSocket:" echo "" echo "Recent Logs:" tail -n 5 /opt/goodspace-voice-webrtc/logs/signaling.log 2>/dev/null ' EOF chmod +x $APP_DIR/scripts/monitor.sh # Step 14: Enable Services print_status "Enabling services..." sudo systemctl daemon-reload sudo systemctl enable webrtc-signaling sudo systemctl enable redis-server sudo systemctl enable nginx # Step 15: Create README cat > $APP_DIR/README.md << 'EOF' # WebRTC Server for Goodspace Voice Agent ## Environment Setup This server uses conda environment 'gsva' with Llama-3.1-8B-Omni model. ### Conda Environment - Environment name: `gsva` - Python version: 3.10 - Model: `Llama-3.1-8B-Omni` ## Quick Start ### Start all services: ```bash ./scripts/start.sh ``` ### Stop services: ```bash ./scripts/stop.sh ``` ### Check status: ```bash ./scripts/status.sh ``` ### View logs: ```bash ./scripts/logs.sh ``` ### Monitor in real-time: ```bash ./scripts/monitor.sh ``` ## Service Management ### Using systemctl: ```bash # Start/Stop/Restart signaling server sudo systemctl start webrtc-signaling sudo systemctl stop webrtc-signaling sudo systemctl restart webrtc-signaling # Check service status sudo systemctl status webrtc-signaling # View service logs journalctl -u webrtc-signaling -f ``` ## Testing ### Test WebSocket connection: ```bash curl http://localhost:8080/health ``` ### Test from browser: Open browser console and run: ```javascript const ws = new WebSocket('ws://your-server-ip:8080/ws'); ws.onopen = () => console.log('Connected'); ws.onmessage = (e) => console.log('Message:', e.data); ``` ## Configuration Edit environment variables in `.env` file and restart services. ## Troubleshooting 1. Check service status: `./scripts/status.sh` 2. Check logs: `./scripts/logs.sh` 3. Check ports: `sudo netstat -tlnp` 4. Check firewall: `sudo ufw status` ## SSL/TLS Setup (Production) ```bash # Get SSL certificate sudo certbot --nginx -d your-domain.com # Auto-renewal sudo certbot renew --dry-run ``` EOF # Final Summary echo "" echo "================================================" print_status "WebRTC Server setup completed!" echo "================================================" echo "" echo "Application directory: $APP_DIR" echo "" echo "Next steps:" echo "1. Copy your WebRTC module files to: $APP_DIR/webrtc/" echo "2. Update the .env file with your configuration" echo "3. Start the services: $APP_DIR/scripts/start.sh" echo "4. Check status: $APP_DIR/scripts/status.sh" echo "5. Monitor logs: $APP_DIR/scripts/logs.sh" echo "" echo "For production:" echo "- Configure SSL with: sudo certbot --nginx -d your-domain.com" echo "- Update firewall rules as needed" echo "- Configure TURN server if needed" echo "" print_warning "Remember to configure your domain name in Nginx!" echo "================================================"