No description
  • Go 61%
  • Shell 37.8%
  • Dockerfile 1.2%
Find a file
Repository files (latest commit first)
Filename Latest commit message Latest commit date
2025-07-14 02:03:04 -04:00
.gitlab-ci.yml Configure SAST and Secret Detection in .gitlab-ci.yml, creating this file if it does not already exist 2025-07-14 01:51:49 -04:00
build.sh First version 2025-07-14 02:03:04 -04:00
config.json First version 2025-07-14 02:03:04 -04:00
docker-compose.yml First version 2025-07-14 02:03:04 -04:00
Dockerfile First version 2025-07-14 02:03:04 -04:00
go.mod First version 2025-07-14 02:03:04 -04:00
README.md First version 2025-07-14 02:03:04 -04:00
replicator.go First version 2025-07-14 02:03:04 -04:00
test.sh First version 2025-07-14 02:03:04 -04:00

Database Replicator

Database Proxy with Monitoring & Sync

A high-availability database proxy that supports PostgreSQL, MySQL, and MongoDB with automatic failover, buffering, synchronization, and real-time monitoring.

🚀 Features

  • Multi-Database Support: PostgreSQL, MySQL, MongoDB
  • Transparent Proxying: Clients connect as if connecting directly to databases
  • Automatic Failover: Routes traffic to healthy servers automatically
  • Buffer & Sync: Buffers operations when servers are down, replays when back online
  • Real-time Monitoring: Web dashboard and REST API for monitoring
  • Conflict Resolution: Multiple strategies for handling conflicts
  • Circuit Breaker: Protects against cascading failures
  • Health Monitoring: Continuous health checks with detailed metrics
  • Data Consistency: Ensures all replicas stay synchronized

📊 Monitoring Dashboard

Access the web dashboard at http://localhost:8080 to view:

  • Real-time status of all database groups
  • Server health and performance metrics
  • Sync status and buffer information
  • Circuit breaker states
  • Detailed connection statistics

🐳 Quick Start with Docker

Prerequisites

  • Docker and Docker Compose installed
  • At least 4GB RAM available for containers

1. Clone and Build

git clone <repository-url>
cd database-proxy
chmod +x build.sh
./build.sh

2. Start All Services

docker-compose up -d

3. Access Services

  • Proxy Dashboard: http://localhost:8080
  • PostgreSQL Proxy: localhost:5432
  • MySQL Proxy: localhost:3306
  • MongoDB Proxy: localhost:27017

4. Test Connections

# Test PostgreSQL
psql -h localhost -p 5432 -U postgres -d testdb

# Test MySQL
mysql -h localhost -P 3306 -u root -p testdb

# Test MongoDB
mongo localhost:27017/testdb

🏗️ Architecture

┌─────────────────┐    ┌─────────────────┐    ┌─────────────────┐
│   Client App    │───▶│  Database Proxy │───▶│   Database 1    │
└─────────────────┘    │                 │    ├─────────────────┤
                       │  - Health Check │───▶│   Database 2    │
┌─────────────────┐    │  - Buffering    │    ├─────────────────┤
│ Monitoring UI   │◀───│  - Sync Logic   │───▶│   Database 3    │
└─────────────────┘    │  - Circuit      │    └─────────────────┘
                       │    Breaker      │
                       └─────────────────┘

📁 Project Structure

database-proxy/
├── main.go                 # Main proxy application
├── go.mod                  # Go dependencies
├── config.json             # Proxy configuration
├── Dockerfile              # Proxy container build
├── docker-compose.yml      # Full stack setup
├── build.sh                # Build script
├── test.sh                 # Test script
├── init-scripts/           # Database initialization
│   ├── postgres-init.sql
│   ├── mysql-init.sql
│   └── mongo-init.js
└── README.md               # This file

⚙️ Configuration

The proxy is configured via config.json:

{
  "monitor_port": 8080,
  "groups": [
    {
      "name": "postgres_cluster",
      "type": "postgres",
      "port": 5432,
      "sync_interval": 30,
      "enable_checksums": true,
      "circuit_breaker": {
        "enabled": true,
        "failure_threshold": 5,
        "recovery_timeout": 60
      },
      "conflict_resolution": {
        "strategy": "primary_wins",
        "primary": "pg_primary"
      },
      "servers": [...]
    }
  ]
}

Configuration Options

Option Description Default
monitor_port HTTP monitoring port 8080
sync_interval Sync check frequency (seconds) 60
health_timeout Health check timeout (seconds) 10
max_buffer_size Maximum buffered operations 10000
enable_checksums Calculate table checksums false

Conflict Resolution Strategies

  • last_write_wins: Latest timestamp wins
  • primary_wins: Primary server takes precedence
  • manual: Log conflicts for manual resolution

🔧 API Endpoints

Monitoring APIs

  • GET / - Web dashboard
  • GET /api/status - Complete system status
  • GET /api/groups - All groups overview
  • GET /api/groups/{name} - Group details
  • GET /api/health - Health check endpoint
  • GET /api/metrics - Performance metrics

Control APIs

  • POST /api/sync/{group} - Trigger manual sync
  • POST /api/circuit-breaker/{group}/{server}?action={open|close|reset} - Circuit breaker control

Example API Usage

# Check system health
curl http://localhost:8080/api/health

# Get detailed status
curl http://localhost:8080/api/status | jq

# Trigger sync for PostgreSQL cluster
curl -X POST http://localhost:8080/api/sync/postgres_cluster

# Open circuit breaker for a server
curl -X POST "http://localhost:8080/api/circuit-breaker/postgres_cluster/pg_primary?action=open"

🧪 Testing

Automated Tests

./test.sh

Manual Testing

  1. Test Failover:

    # Stop a database container
    docker-compose stop postgres-primary
    
    # Check proxy dashboard - should show server as offline
    # Test connection - should still work via secondary
    psql -h localhost -p 5432 -U postgres -d testdb
    
    # Restart container
    docker-compose start postgres-primary
    
    # Check dashboard - should show sync in progress
    
  2. Test Buffer & Sync:

    # Stop all secondaries
    docker-compose stop postgres-secondary postgres-tertiary
    
    # Perform write operations
    psql -h localhost -p 5432 -U postgres -d testdb -c "INSERT INTO test_table VALUES (1, 'test');"
    
    # Check dashboard - should show buffered operations
    
    # Restart secondaries
    docker-compose start postgres-secondary postgres-tertiary
    
    # Watch sync process in dashboard
    
  3. Test Circuit Breaker:

    # Simulate failures via API
    for i in {1..6}; do
      curl -X POST "http://localhost:8080/api/circuit-breaker/postgres_cluster/pg_primary?action=open"
      sleep 1
    done
    
    # Check dashboard - circuit breaker should be open
    

📈 Monitoring & Metrics

Key Metrics

  • Connection Statistics: Total requests, success rate, response times
  • Sync Status: Last sync time, buffer size, conflicts detected
  • Health Status: Server availability, circuit breaker states
  • Performance: Throughput, error rates, queue depths

Alerting

Set up alerts based on:

  • Buffer size exceeding thresholds
  • Sync failures or delays
  • Circuit breaker activations
  • Server unavailability

🔍 Troubleshooting

Common Issues

  1. Connection Refused

    # Check if containers are running
    docker-compose ps
    
    # Check proxy logs
    docker-compose logs proxy
    
  2. Sync Issues

    # Check dashboard for sync status
    curl http://localhost:8080/api/groups/postgres_cluster
    
    # Trigger manual sync
    curl -X POST http://localhost:8080/api/sync/postgres_cluster
    
  3. High Buffer Size

    # Check which servers are down
    curl http://localhost:8080/api/status | jq '.groups[].servers[].status'
    
    # Restart failed containers
    docker-compose restart postgres-secondary
    

Log Analysis

# View all logs
docker-compose logs -f

# View specific service logs
docker-compose logs -f proxy
docker-compose logs -f postgres-primary

# Search for errors
docker-compose logs proxy | grep ERROR

🛠️ Development

Building from Source

# Install dependencies
go mod tidy

# Build binary
go build -o database-proxy main.go

# Run with config
./database-proxy config.json

Running Tests

# Unit tests (if implemented)
go test ./...

# Integration tests
./test.sh

Custom Configuration

  1. Modify config.json for your database setup
  2. Update docker-compose.yml if needed
  3. Rebuild: ./build.sh

🤝 Contributing

  1. Fork the repository
  2. Create a feature branch
  3. Make your changes
  4. Add tests
  5. Submit a pull request

📞 Support