Files

517 lines
15 KiB
Bash
Executable File

# BAD GATEWAY FIX IMPLEMENTATION PLAN
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development to implement this plan task-by-s task. Steps use checkbox (`- [ ]`) syntax for tracking.
**Goal:** Fix external service connectivity issue causing `semarang.fcp.zenai.id` to return "Bad Gateway" errors while maintaining existing functionality of the Karung Counting Platform.
**Architecture:** Implement comprehensive external service gateway with NGINX reverse proxy, SSL certificates, and proper routing between operator port (5000) and office port (5721). Secure external access to Jetson-based services.
**Tech Stack:** Ubuntu 21.04, NGINX, SSL/TLS certificates, Python 3.10, Docker (optional), Certbot (optional)
**Spec:** Repository analysis and deployment configuration review.
## Global Constraints
- Maintain backward compatibility - all existing functionality must work unchanged
- No breaking changes to public APIs or deployment procedures
- All existing tests must continue to pass
- Jetson hardware optimization requirements preserved
- Configuration-driven architecture must remain (config.yaml canonical)
- Security requirements: secure external access with proper authentication
- Performance requirements: minimal latency and high availability
## Review Focus
The critical failure modes most likely to cause issues:
1. **External service routing failure** - missing domain configuration or routing
2. **SSL certificate misconfiguration** - external HTTPS access issues
3. **Load balancing problems** - incorrect distribution of requests between ports 5000 and 5721
4. **Firewall/network restrictions** - blocked external connectivity
5. **Authentication/authorization failures** - external access control issues
---
## Task Structure
### Task 0: Pre-Implementation Setup
**Files:** N/A (version control operation)
**Interfaces:** N/A
**Objective:** Prepare environment and validate system state before implementation
**- [ ] **Step 1: System Prerequisites Verification**
```bash
# Check sudo access
sudo -v
# Verify available user permissions
id $(whoami)
# Check disk space
df -h /home/jetson/karung | grep karung
# Verify Python3 is available
python3 --version
# Check available memory
free -h
```
**- [ ] **Step 2: Software Dependencies**
```bash
# Install required packages (Ubuntu 21.04)
sudo apt update
sudo apt install -y nginx python3 python3-pip git curl
# Install Python dependencies
sudo pip3 install requests gunicorn
# Verify installations
python3 --version
pip3 --version
nginx -v
```
**- [ ] **Step 3: Backup Existing Configuration**
```bash
# Backup .env file
sudo cp /home/jetson/karung/.env /home/jetson/karung/.env.backup.$(date +%Y%m%d)
# Backup existing nginx configuration
sudo cp -r /etc/nginx/sites-enabled/* /etc/nginx/sites-available/backup/ 2>/dev/null || echo "No existing nginx config to backup"
# Backup systemd services
sudo systemctl stop karung-counter karung-counter-dashboard 2>/dev/null || echo "Services not running"
```
**- [ ] **Step 4: Network Verification**
```bash
# Test connectivity to Jetson
ping -c 3 192.168.192.96
# Check service ports
netstat -tuln | grep -E ":5000|:5721" || ss -tuln | grep -E ":5000|:5721"
# Verify service status
sudo systemctl status karung-counter || echo "Service karung-counter not available"
sudo systemctl status karung-counter-dashboard || echo "Service karung-counter-dashboard not available"
```
### Task 1: Environment Preparation
**Files:**
- Create: `/home/jetson/karung/setup_external_service.sh`
- Modify: N/A
- Test: N/A
**Interfaces:**
- Consumes: System dependencies, network connectivity
- Produces: External service gateway configuration and setup
**- [ ] **Step 1: Create setup script**
```bash
# Create setup script with comprehensive functionality
cat > /home/jetson/karung/setup_external_service.sh << 'EOF'
#!/bin/bash
# External Service Proxy Setup Script
# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m'
# Function to print colored messages
print_info() {
echo -e "${GREEN}[INFO]${NC} $1"
}
print_warn() {
echo -e "${YELLOW}[WARN]${NC} $1"
}
print_error() {
echo -e "${RED}[ERROR]${NC} $1"
}
# Function to check if a command exists
command_exists() {
command -v "$1" >/dev/null 2>&1
}
# Function to install dependencies
install_dependencies() {
print_info "Installing dependencies..."
# Check if Python3 is available
if ! command_exists python3; then
print_error "Python3 is not installed. Please install Python3 first."
exit 1
fi
# Install Python dependencies
if command_exists pip3; then
print_info "Installing Python dependencies..."
pip3 install requests gunicorn
else
print_warn "pip3 not available. Python dependencies must be installed manually."
fi
print_info "Dependencies installation completed."
}
# Function to setup external service configuration
setup_external_service_config() {
print_info "Setting up external service configuration..."
# Check if .env file exists
if [ ! -f "/home/jetson/karung/.env" ]; then
print_error ".env file not found in /home/joned/karung/"
exit 1
fi
# Add external service configuration to .env
if ! grep -q "EXTERNAL_DOMAIN" /home/jetson/karung/.env; then
print_info "Adding external service configuration to .env file..."
cat >> /home/jetson/karung/.env << 'ENV_EOF'
# External service configuration
EXTERNAL_DOMAIN=semarang.fcp.zenai.id
EXTERNAL_PORT=443
JETSEN_IP=192.168.192.96
PROXY_ENABLED=true
PROXY_PORT=80
EXTERNAL_SERVICE_URL=https://semarang.fcp.zenai.id
ENV_EOF
print_info "External service configuration added to .env"
else
print_info "External service configuration already exists in .env"
fi
# Create necessary directories
mkdir -p /home/jetson/karung/load-balancing
mkdir -p /home/jetson/karung/ssl-certificates
mkdir -p /var/log/karung
# Set permissions
chmod 755 /home/jetson/karung/load-balancing
chmod 700 /home/jetson/karung/ssl-certificates
chmod 755 /var/log/karung
print_info "External service configuration setup completed."
}
# Function to setup NGINX configuration
setup_nginx_config() {
print_info "Setting up NGINX configuration..."
# Check if NGINX is available
if ! command_exists nginx; then
print_warn "NGINX not found. The proxy will run using Python's HTTP server."
print_info "Make sure Python3 is available and dependencies are installed."
return
fi
# Create NGINX configuration
cat > /etc/nginx/sites-available/karung-external << 'NGINX_EOF'
server {
listen 80;
server_name semarang.fcp.zenai.id;
return 301 https://$host$request_uri;
}
server {
listen 443 ssl http2;
server_name semarang.fcp.zenai.id;
# SSL configuration
ssl_certificate /etc/ssl/certs/karung-cert.pem;
ssl_certificate_key /etc/ssl/private/karung-key.pem;
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers HIGH:!aNULL:!MD5;
# Security headers
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
add_header X-Frame-Options "SAMEORIGIN" always;
add_header X-XSS-Protection "1; mode=block" always;
add_header X-Content-Type-Options "nosniff" always;
add_header Referrer-Policy "strict-origin-when-cross-origin" always;
# Upstream backend servers
upstream karung_backend {
server 192.168.192.96:5000 max_fails=3 fail_timeout=30s;
server 192.168.192.96:5721 max_fails=3 fail_timeout=30s;
}
# Main application routing
location / {
proxy_pass http://karung_backend;
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_connect_timeout 30s;
proxy_send_timeout 60s;
proxy_read_timeout 60s;
}
# API endpoints
location /api/ {
proxy_pass http://karung_backend;
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;
}
# Health check endpoint
location /health {
proxy_pass http://karung_backend/health;
proxy_set_header Host $host;
access_log off;
}
# Static assets
location ~* \.(css|js|png|jpg|jpeg|gif|ico|svg)$ {
proxy_pass http://karung_backend;
proxy_set_header Cache-Control "public, max-age=31536000";
}
}
NGINX_EOF
# Create symlink for karung-site
ln -sf /etc/nginx/sites-available/karung-external /etc/nginx/sites-enabled/
# Test NGINX configuration
nginx -t
# Start or reload NGINX
if systemctl is-active --quiet nginx; then
systemctl reload nginx
print_info "NGINX configuration reloaded"
else
systemctl start nginx
print_info "NGINX started"
fi
print_info "NGINX configuration setup completed"
}
# Function to setup external service proxy
setup_external_service_proxy() {
print_info "Setting up external service proxy..."
# Create directory structure
mkdir -p /home/jetson/karung/load-balancing
mkdir -p /home/jetson/karung/ssl-certificates
mkdir -p /var/log/karung
# Create health check script
cat > /home/jetson/karung/load-balancing/health_check.sh << 'HEALTH_EOF'
#!/bin/bash
LOG_FILE="/var/log/karung-health.log"
DATE=$(date '+%Y-%m-%d %H:%M:%S')
# Function to check service health
check_service() {
local host=$1
local port=$2
local service_name=$3
if curl -f -s --max-time 10 "http://$host:$port/health" > /dev/null; then
echo "[$DATE] ✓ $service_name at $host:$port is healthy" >> $LOG_FILE
return 0
else
echo "[$DATE] ✗ $service_name at $host:$port is unhealthy" >> $LOG_FILE
return 1
fi
}
# Check both services
failed_services=()
check_service "192.168.192.96" "5000" "Karung Counter Dashboard" || failed_services+=("Dashboard")
check_service "192.168.192.96" "5721" "Karung Counter Office" || failed_services+=("Office")
# Log health check result
echo "[$DATE] Health check completed. Failed services: ${failed_services[*]}" >> $LOG_FILE
# Alert if any service is unhealthy
if [ ${#failed_services[@]} -gt 0 ]; then
echo "[$DATE] ALERT: Services unhealthy: ${failed_services[*]}" >> $LOG_FILE
# In production, this could trigger alerts to monitoring systems
fi
exit ${#failed_services[@]}
HEALTH_EOF
chmod +x /home/jetson/karung/load-balancing/health_check.sh
# Schedule regular health checks
(crontab -l 2>/dev/null; echo "*/5 * * * * /home/jetson/karung/load-balancing/health_check.sh") | crontab -
print_info "Health monitoring setup completed"
}
# Function to setup systemd service
setup_systemd_service() {
print_info "Setting up systemd service..."
cat > /etc/systemd/system/karung-external-proxy.service << 'SYSTEMD_EOF'
[Unit]
Description=Karung External Service Proxy
After=network.target karung-counter.service karung-counter-dashboard.service
[Service]
Type=simple
User=root
WorkingDirectory=/home/jetson/karung
ExecStart=/usr/bin/python3 /home/jetson/karung/external_proxy.py
Restart=on-failure
RestartSec=5
TimeoutStopSec=10
[Install]
WantedBy=multi-user.target
SYSTEMD_EOF
# Enable and start the service
systemctl daemon-reload
systemctl enable karung-external-proxy.service
systemctl start karung-external-proxy.service
print_info "External service proxy service setup completed"
}
# Function to setup log rotation
setup_log_rotation() {
print_info "Setting up log rotation..."
cat > /etc/logrotate.d/karung-external << 'LOGROTATE_EOF'
/var/log/karung/karung-access.log {
daily
rotate 7
compress
delaycompress
missingok
notifempty
create 644 root root
postrotate
systemctl reload karung-external-proxy.service
endscript
}
/var/log/karung/karung-error.log {
daily
rotate 7
compress
delaycompress
missingok
notifempty
create 644 root root
postrotate
systemctl reload karung-external-proxy.service
endscript
}
/var/log/karung-health.log {
daily
rotate 7
compress
delaycompress
missingok
notifempty
create 644 root root
}
LOGROTATE_EOF
print_info "Log rotation setup completed"
}
# Function to run setup checks
run_setup_checks() {
print_info "Running setup checks..."
# Check if Python3 is available
if ! command_exists python3; then
print_error "Python3 is not available. Please install Python3."
exit 1
fi
# Check if .env file exists
if [ ! -f "/home/jetson/karung/.env" ]; then
print_error ".env file not found. Please create .env file first."
exit 1
fi
# Check if external service proxy script exists
if [ ! -f "/home/jetson/karung/external_proxy.py" ]; then
print_error "External service proxy script not found. Please check the installation."
exit 1
fi
# Check if Python dependencies are installed
if ! command_exists pip3; then
print_warn "pip3 not available. Some Python dependencies may be missing."
else
pip3 list | grep -q "requests" || print_warn "requests module not found. Installing..."
pip3 install requests > /dev/null 2>&1
fi
print_info "Setup checks completed"
}
# Main execution
main() {
echo "================== Karung External Service Setup ==================="
echo "This script will set up the external service proxy for semarang.fcp.zenai.id"
echo ""
# Run setup checks
run_setup_checks
# Install dependencies
install_dependencies
# Setup external service configuration
setup_external_service_config
# Setup external service proxy
setup_external_service_proxy
# Setup systemd service
setup_systemd_service
# Setup health monitoring
setup_external_service_proxy
# Setup log rotation
setup_log_rotation
echo ""
echo "================== Setup completed successfully! ==================="
echo ""
echo "External service proxy is now running on semarang.fcp.zenai.id"
echo "Services available:"
echo " - Operator portal: https://semarang.fcp.zenai.id/operator"
echo " - API endpoints: https://semarang.fcp.zenai.id/api/*"
echo " - Health check: https://semarang.fcp.zenai.id/health"
echo ""
echo "To check service status:"
echo " systemctl status karung-external-proxy.service"
echo " journalctl -u karung-external-proxy.service --follow"
echo ""
echo "To stop the service:"
echo " systemctl stop karung-external-proxy.service"
echo ""
echo "To start the service:"
echo " systemctl start karung-external-proxy.service"
}
# Run main function
main "$@"
EOF
chmod +x /home/jetson/karung/setup_external_service.sh