-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdeploy.sh
More file actions
356 lines (292 loc) · 9.87 KB
/
Copy pathdeploy.sh
File metadata and controls
356 lines (292 loc) · 9.87 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
#!/bin/bash
# Multicaster Production Deployment Script
# This script automates the deployment process for Ubuntu/Debian systems
set -e # Exit on any error
echo "🚀 Multicaster Production Deployment Script"
echo "============================================="
# Configuration
DB_NAME="multicaster_prod"
DB_USER="multicaster_user"
APP_USER="multicaster"
DOMAIN="${1:-localhost}" # First argument or default to localhost
# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color
# Helper functions
log_info() {
echo -e "${GREEN}[INFO]${NC} $1"
}
log_warn() {
echo -e "${YELLOW}[WARN]${NC} $1"
}
log_error() {
echo -e "${RED}[ERROR]${NC} $1"
}
# Check if running as root
if [[ $EUID -eq 0 ]]; then
log_error "This script should not be run as root. Run as a regular user with sudo privileges."
exit 1
fi
# Check for required arguments
if [ "$#" -eq 0 ]; then
log_warn "No domain specified. Using 'localhost' for testing."
log_warn "For production, run: ./deploy.sh your-domain.com"
fi
log_info "Starting deployment for domain: $DOMAIN"
# Step 1: Update system and install dependencies
log_info "Step 1/8: Installing system dependencies..."
sudo apt update && sudo apt upgrade -y
sudo apt install -y python3 python3-pip python3-venv nodejs npm postgresql postgresql-contrib nginx redis-server git curl
# Step 2: Start services
log_info "Step 2/8: Starting system services..."
sudo systemctl enable postgresql nginx redis-server
sudo systemctl start postgresql nginx redis-server
# Step 3: Create application user
log_info "Step 3/8: Creating application user..."
if ! id "$APP_USER" &>/dev/null; then
sudo useradd -m -s /bin/bash $APP_USER
sudo usermod -aG sudo $APP_USER
log_info "Created user: $APP_USER"
else
log_info "User $APP_USER already exists"
fi
# Step 4: Setup database
log_info "Step 4/8: Setting up PostgreSQL database..."
# Generate a random password for database user
DB_PASSWORD=$(openssl rand -base64 32)
# Create database and user
sudo -u postgres psql << EOF
-- Drop existing database and user if they exist (for clean reinstall)
DROP DATABASE IF EXISTS $DB_NAME;
DROP USER IF EXISTS $DB_USER;
-- Create new database and user
CREATE DATABASE $DB_NAME;
CREATE USER $DB_USER WITH PASSWORD '$DB_PASSWORD';
GRANT ALL PRIVILEGES ON DATABASE $DB_NAME TO $DB_USER;
ALTER USER $DB_USER CREATEDB;
\q
EOF
log_info "Database $DB_NAME created with user $DB_USER"
# Step 5: Setup application
log_info "Step 5/8: Setting up application..."
# Copy application to app user's home directory
sudo cp -r "$(pwd)" "/home/$APP_USER/"
sudo chown -R $APP_USER:$APP_USER "/home/$APP_USER/Multicaster"
# Switch to app user and setup environment
sudo -u $APP_USER bash << EOF
cd /home/$APP_USER/Multicaster
# Create Python virtual environment
python3 -m venv venv
source venv/bin/activate
# Install Python dependencies
pip install -r requirements.txt
pip install gunicorn psycopg2-binary
# Create production environment file
cat > .env << EOL
DATABASE_URL=postgresql://$DB_USER:$DB_PASSWORD@localhost:5432/$DB_NAME
SECRET_KEY=$(python3 -c "import secrets; print(secrets.token_hex(32))")
JWT_SECRET_KEY=$(python3 -c "import secrets; print(secrets.token_hex(32))")
ADMIN_EMAIL=admin@$DOMAIN
ADMIN_PASSWORD=admin123
FLASK_ENV=production
FLASK_DEBUG=False
WTF_CSRF_ENABLED=True
EOL
chmod 600 .env
# Initialize database
python init_db.py
# Install frontend dependencies and build
npm install
npm run build
echo "Application setup completed"
EOF
# Step 6: Create Gunicorn configuration
log_info "Step 6/8: Configuring Gunicorn..."
sudo -u $APP_USER tee "/home/$APP_USER/Multicaster/gunicorn.conf.py" << EOF
bind = "127.0.0.1:5001"
workers = 4
worker_class = "sync"
worker_connections = 1000
max_requests = 1000
max_requests_jitter = 100
timeout = 30
keepalive = 5
preload_app = True
user = "$APP_USER"
group = "$APP_USER"
secure_scheme_headers = {
'X-FORWARDED-PROTOCOL': 'ssl',
'X-FORWARDED-PROTO': 'https',
'X-FORWARDED-SSL': 'on'
}
EOF
# Step 7: Create systemd service
log_info "Step 7/8: Creating systemd service..."
sudo tee /etc/systemd/system/multicaster.service << EOF
[Unit]
Description=Multicaster Flask Application
After=network.target postgresql.service
Requires=postgresql.service
[Service]
Type=exec
User=$APP_USER
Group=$APP_USER
WorkingDirectory=/home/$APP_USER/Multicaster
Environment=PATH=/home/$APP_USER/Multicaster/venv/bin
ExecStart=/home/$APP_USER/Multicaster/venv/bin/gunicorn -c gunicorn.conf.py app:app
ExecReload=/bin/kill -s HUP \$MAINPID
Restart=always
RestartSec=10
[Install]
WantedBy=multi-user.target
EOF
sudo systemctl daemon-reload
sudo systemctl enable multicaster
sudo systemctl start multicaster
# Step 8: Configure Nginx
log_info "Step 8/8: Configuring Nginx..."
sudo tee /etc/nginx/sites-available/multicaster << EOF
server {
listen 80;
server_name $DOMAIN;
# Security Headers
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 "no-referrer-when-downgrade" always;
# Gzip Compression
gzip on;
gzip_vary on;
gzip_min_length 1024;
gzip_types text/plain text/css text/xml text/javascript application/x-javascript application/xml+rss application/javascript;
# Client max body size
client_max_body_size 10M;
# Serve React frontend
location / {
root /home/$APP_USER/Multicaster/build;
index index.html index.htm;
try_files \$uri \$uri/ /index.html;
# Cache static assets
location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg|woff|woff2|ttf|eot)$ {
expires 1y;
add_header Cache-Control "public, immutable";
}
}
# Proxy API requests to Flask backend
location /api/ {
proxy_pass http://127.0.0.1:5001;
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_redirect off;
proxy_buffering off;
}
# Proxy auth requests to Flask backend
location /auth/ {
proxy_pass http://127.0.0.1:5001;
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_redirect off;
proxy_buffering off;
}
# Access and error logs
access_log /var/log/nginx/multicaster_access.log;
error_log /var/log/nginx/multicaster_error.log;
}
EOF
# Enable site
sudo ln -sf /etc/nginx/sites-available/multicaster /etc/nginx/sites-enabled/
sudo rm -f /etc/nginx/sites-enabled/default
# Test and reload Nginx
sudo nginx -t
sudo systemctl reload nginx
# Configure firewall
log_info "Configuring firewall..."
sudo ufw --force enable
sudo ufw allow ssh
sudo ufw allow 'Nginx Full'
# Create backup script
log_info "Creating backup script..."
sudo -u $APP_USER tee "/home/$APP_USER/backup_db.sh" << EOF
#!/bin/bash
BACKUP_DIR="/home/$APP_USER/backups"
DATE=\$(date +%Y%m%d_%H%M%S)
BACKUP_FILE="multicaster_backup_\$DATE.sql"
mkdir -p \$BACKUP_DIR
# Create database backup
PGPASSWORD='$DB_PASSWORD' pg_dump -h localhost -U $DB_USER -d $DB_NAME > \$BACKUP_DIR/\$BACKUP_FILE
# Compress backup
gzip \$BACKUP_DIR/\$BACKUP_FILE
# Keep only last 7 days of backups
find \$BACKUP_DIR -name "multicaster_backup_*.sql.gz" -mtime +7 -delete
echo "Backup completed: \$BACKUP_DIR/\$BACKUP_FILE.gz"
EOF
sudo chmod +x "/home/$APP_USER/backup_db.sh"
# Add daily backup to crontab
sudo -u $APP_USER bash -c "(crontab -l 2>/dev/null; echo '0 2 * * * /home/$APP_USER/backup_db.sh') | crontab -"
# Final status check
log_info "Checking service status..."
sleep 5
if sudo systemctl is-active --quiet multicaster; then
log_info "✅ Multicaster service is running"
else
log_error "❌ Multicaster service failed to start"
sudo systemctl status multicaster
fi
if sudo systemctl is-active --quiet nginx; then
log_info "✅ Nginx service is running"
else
log_error "❌ Nginx service failed to start"
fi
if sudo systemctl is-active --quiet postgresql; then
log_info "✅ PostgreSQL service is running"
else
log_error "❌ PostgreSQL service failed to start"
fi
# Display completion information
echo ""
echo "🎉 Deployment completed successfully!"
echo "============================================="
echo ""
echo "📋 Deployment Summary:"
echo "• Domain: $DOMAIN"
echo "• Application URL: http://$DOMAIN"
echo "• Database: $DB_NAME"
echo "• Database User: $DB_USER"
echo "• Application User: $APP_USER"
echo "• Application Path: /home/$APP_USER/Multicaster"
echo ""
echo "🔐 Default Login Credentials:"
echo "• Username: admin"
echo "• Password: admin123"
echo "• Email: admin@$DOMAIN"
echo ""
echo "📁 Important Files:"
echo "• Environment: /home/$APP_USER/Multicaster/.env"
echo "• Logs: sudo journalctl -u multicaster -f"
echo "• Nginx Config: /etc/nginx/sites-available/multicaster"
echo "• Backup Script: /home/$APP_USER/backup_db.sh"
echo ""
echo "🔧 Useful Commands:"
echo "• Restart app: sudo systemctl restart multicaster"
echo "• View logs: sudo journalctl -u multicaster -f"
echo "• Backup database: sudo -u $APP_USER /home/$APP_USER/backup_db.sh"
echo "• Update app: cd /home/$APP_USER/Multicaster && git pull && sudo systemctl restart multicaster"
echo ""
if [ "$DOMAIN" != "localhost" ]; then
echo "🔒 Next Steps for Production:"
echo "1. Configure DNS to point $DOMAIN to this server"
echo "2. Install SSL certificate: sudo certbot --nginx -d $DOMAIN"
echo "3. Change default admin password"
echo "4. Configure LDAP if needed"
echo "5. Setup monitoring and alerting"
echo ""
fi
echo "📖 For detailed documentation, see: DEPLOYMENT.md"
echo ""
log_info "Deployment script completed!"