CIA/e-voting-system/BACKEND_STARTUP_GUIDE.md

448 lines
9.2 KiB
Markdown

# Backend Startup Guide
## Quick Start
```bash
# Start all services (database, backend, frontend)
docker compose up -d
# Wait for initialization (30-40 seconds)
sleep 40
# Verify backend is running
curl http://localhost:8000/health
# Should return:
# {"status": "ok", "version": "0.1.0"}
```
## What Happens on Startup
### 1. MariaDB Database Starts (10-20 seconds)
- Container starts
- Database initialized from `docker/init.sql`
- Creates tables: voters, elections, candidates, votes, audit_logs
- Inserts sample election and candidates
- Runs `docker/populate_past_elections.sql` (adds 10 past elections)
- Runs `docker/create_active_election.sql` (ensures election 1 is active)
### 2. Backend Starts (5-10 seconds)
- FastAPI application loads
- Database connection established
- **Blockchain initialization begins**:
- Loads all elections from database
- Records each to blockchain if not already recorded
- Verifies blockchain integrity
- Prints status: `✓ Blockchain integrity verified - N blocks`
- Backend ready to serve requests
### 3. Frontend Starts (5-10 seconds)
- Next.js application builds and starts
- Connects to backend API
## Startup Timeline
```
docker compose up -d
|
├─ MariaDB starts (10-20s)
│ ├─ init.sql runs (create tables)
│ ├─ populate_past_elections.sql runs (past data)
│ └─ create_active_election.sql runs (make election 1 active)
├─ Backend starts (5-10s)
│ ├─ FastAPI loads
│ ├─ Blockchain initialization starts
│ │ ├─ Load elections from DB
│ │ ├─ Record to blockchain
│ │ └─ Verify integrity
│ └─ Backend ready
└─ Frontend starts (5-10s)
└─ Next.js ready
Total startup time: 30-45 seconds
```
## Status Checks
### Check All Services
```bash
docker compose ps
```
Expected:
```
NAME STATUS PORTS
evoting_mariadb healthy (running)
evoting_backend healthy (running) 127.0.0.1:8000->8000/tcp
evoting_frontend healthy (running) 127.0.0.1:3000->3000/tcp
evoting_adminer healthy (running) 127.0.0.1:8081->8080/tcp
```
### Check Backend Health
```bash
curl http://localhost:8000/health
```
Expected:
```json
{"status": "ok", "version": "0.1.0"}
```
If you get `502 Bad Gateway`:
- Backend is still starting
- Wait another 10-20 seconds
- Try again
### Check Database Health
```bash
# Connect to database
docker compose exec mariadb mariadb -u evoting_user -pevoting_pass123 evoting_db
# Query elections
MariaDB [evoting_db]> SELECT id, name, is_active FROM elections LIMIT 5;
# Expected: Election 1 should be active with recent dates
```
### Check Blockchain Initialization
```bash
# View backend logs
docker compose logs backend | grep -i blockchain
# Should show:
# ✓ Recorded election 1 (Election Présidentielle 2025) to blockchain
# ✓ Blockchain integrity verified - 1 blocks
```
## Common Startup Issues
### Issue 1: 502 Bad Gateway on All Endpoints
**Cause**: Backend is still initializing
**Solution**:
```bash
# Wait longer
sleep 30
# Check if backend is up
curl http://localhost:8000/health
# If still 502, check logs
docker compose logs backend | tail -50
```
### Issue 2: Database Won't Start
**Symptoms**:
```bash
docker compose logs mariadb
# Error: "InnoDB: Specified key was too long"
# or: "Address already in use"
```
**Solutions**:
Option A - Different port:
```bash
# Stop and remove containers
docker compose down
# Change port in docker-compose.yml:
# mariadb:
# ports:
# - "3307:3306" # Changed from 3306
docker compose up -d
```
Option B - Fresh database:
```bash
# Remove database volume
docker compose down -v
# Start fresh
docker compose up -d
sleep 40
```
### Issue 3: Backend Import Errors
**Symptoms**:
```bash
docker compose logs backend
# ModuleNotFoundError: No module named 'blockchain_elections'
# or: ImportError: cannot import name 'initialize_elections_blockchain'
```
**Solution**:
```bash
# Rebuild backend with new modules
docker compose down
docker compose up -d --build backend
sleep 40
```
### Issue 4: Port Already in Use
**Symptoms**:
```bash
docker compose up -d
# Error: "bind: address already in use"
```
**Solution**:
```bash
# Kill the process using the port
sudo lsof -i :8000
sudo kill -9 <PID>
# Or stop competing containers
docker ps
docker stop <container_name>
# Then start again
docker compose up -d
```
### Issue 5: Frontend Can't Connect to Backend
**Symptoms**:
- Frontend loads but shows error fetching elections
- Network requests to `/api/elections/active` return 502
**Solution**:
```bash
# Wait for backend to fully initialize
sleep 40
# Check backend is running
curl http://localhost:8000/api/elections/active
# Check frontend environment variable
docker compose logs frontend | grep NEXT_PUBLIC_API_URL
# Should be: http://localhost:8000
```
## Startup Verification Checklist
After `docker compose up -d`, verify each step:
- [ ] Wait 40 seconds
- [ ] Backend health: `curl http://localhost:8000/health` → 200 OK
- [ ] Database has elections: `curl http://localhost:8000/api/elections/debug/all` → shows elections
- [ ] Active election exists: `curl http://localhost:8000/api/elections/active` → shows 1+ elections
- [ ] Blockchain initialized: `curl http://localhost:8000/api/elections/blockchain` → shows blocks
- [ ] Blockchain verified: `curl http://localhost:8000/api/elections/1/blockchain-verify` → "verified": true
- [ ] Frontend loads: `curl http://localhost:3000` → 200 OK
- [ ] Frontend can fetch elections: Browser console shows no errors
## Debugging Tips
### View All Logs
```bash
docker compose logs -f
```
Follow output as services start.
### View Specific Service Logs
```bash
# Backend
docker compose logs backend -f
# Database
docker compose logs mariadb -f
# Frontend
docker compose logs frontend -f
```
### Check Database Content
```bash
# Connect to database
docker compose exec mariadb mariadb -u evoting_user -pevoting_pass123 evoting_db
# See elections
SELECT id, name, is_active, start_date, end_date FROM elections LIMIT 5;
# See candidates
SELECT c.id, c.name, c.election_id FROM candidates LIMIT 10;
# Exit
exit
```
### Check Backend API Directly
```bash
# Health check
curl http://localhost:8000/health
# Active elections
curl http://localhost:8000/api/elections/active
# All elections (with debug info)
curl http://localhost:8000/api/elections/debug/all
# Blockchain
curl http://localhost:8000/api/elections/blockchain
# Verify election
curl http://localhost:8000/api/elections/1/blockchain-verify
```
### Restart Services
```bash
# Restart just backend
docker compose restart backend
sleep 10
# Restart database
docker compose restart mariadb
sleep 20
# Restart frontend
docker compose restart frontend
sleep 5
# Restart all
docker compose down
docker compose up -d
sleep 40
```
### Fresh Start (Nuclear Option)
```bash
# Stop everything
docker compose down
# Remove all data
docker compose down -v
# Remove all containers/images
docker system prune -a
# Start fresh
docker compose up -d
sleep 40
# Verify
curl http://localhost:8000/health
```
## Expected Responses
### Healthy Backend
**GET `/health`**
```json
{"status": "ok", "version": "0.1.0"}
```
**GET `/api/elections/active`**
```json
[
{
"id": 1,
"name": "Election Présidentielle 2025",
"description": "Vote pour la présidence",
"start_date": "2025-11-07T01:59:00",
"end_date": "2025-11-14T01:59:00",
"is_active": true,
"results_published": false
}
]
```
**GET `/api/elections/blockchain`**
```json
{
"blocks": [
{
"index": 0,
"election_id": 1,
"election_name": "Election Présidentielle 2025",
"candidates_count": 4,
"block_hash": "...",
"signature": "...",
...
}
],
"verification": {
"chain_valid": true,
"total_blocks": 1,
"timestamp": "2025-11-07T03:00:00.123456"
}
}
```
**GET `/api/elections/1/blockchain-verify`**
```json
{
"verified": true,
"election_id": 1,
"election_name": "Election Présidentielle 2025",
"hash_valid": true,
"chain_valid": true,
"signature_valid": true
}
```
## Database Adminer
Access database management UI:
- **URL**: http://localhost:8081
- **Server**: mariadb
- **User**: evoting_user
- **Password**: evoting_pass123
- **Database**: evoting_db
Use this to:
- View tables
- Run SQL queries
- Add test data
- Inspect blockchain integrity
## Next Steps
Once backend is healthy:
1. **Test blockchain integration**
```bash
python3 test_blockchain_election.py
```
2. **Verify elections exist**
```bash
curl http://localhost:8000/api/elections/active | jq '.'
```
3. **Check blockchain**
```bash
curl http://localhost:8000/api/elections/blockchain | jq '.blocks | length'
```
4. **Register and vote**
- Open http://localhost:3000
- Register as voter
- Participate in active election
5. **View blockchain (future)**
- Create page with blockchain visualizer component
- Show elections on immutable blockchain
- Verify integrity status
## Support
If issues persist:
1. Check logs: `docker compose logs`
2. Read documentation: See `BLOCKCHAIN_*.md` files
3. Run tests: `python3 test_blockchain_election.py`
4. Try fresh start: `docker compose down -v && docker compose up -d`