Skip to content

Troubleshooting

VetheonGames edited this page Oct 10, 2025 · 2 revisions

Troubleshooting Guide

Comprehensive troubleshooting guide for common issues, error resolution, and maintenance procedures for Source-License.

🚨 Common Issues

Installation Problems

Ruby Version Incompatibility

Error:

Source-License requires Ruby 3.4.7 or higher. Current version: 2.7.0

Solution:

  1. Install correct Ruby version:

    # Using rbenv (recommended)
    rbenv install 3.4.7
    rbenv global 3.4.7
    rbenv rehash
    
    # Using RVM
    rvm install 3.4.7
    rvm use 3.4.7 --default
    
    # Verify installation
    ruby --version
  2. Update PATH if necessary:

    echo 'export PATH="$HOME/.rbenv/bin:$PATH"' >> ~/.bashrc
    echo 'eval "$(rbenv init -)"' >> ~/.bashrc
    source ~/.bashrc

Bundle Install Failures

Error:

An error occurred while installing mysql2 (0.5.4), and Bundler cannot continue.

Solutions:

For MySQL on Ubuntu/Debian:

sudo apt-get update
sudo apt-get install libmysqlclient-dev build-essential
bundle install

For MySQL on macOS:

brew install mysql
bundle install

For PostgreSQL issues:

# Ubuntu/Debian
sudo apt-get install libpq-dev

# macOS
brew install postgresql

Database Connection Issues

Error:

Sequel::DatabaseConnectionError: Access denied for user 'root'@'localhost'

Solutions:

  1. Check database credentials in .env:

    DATABASE_ADAPTER=mysql
    DATABASE_HOST=localhost
    DATABASE_PORT=3306
    DATABASE_NAME=source_license
    DATABASE_USER=your_username
    DATABASE_PASSWORD=your_password
  2. Verify database server is running:

    # MySQL
    sudo systemctl status mysql
    sudo systemctl start mysql
    
    # PostgreSQL
    sudo systemctl status postgresql
    sudo systemctl start postgresql
  3. Create database and user manually:

    -- MySQL
    CREATE DATABASE source_license CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
    CREATE USER 'source_license'@'localhost' IDENTIFIED BY 'secure_password';
    GRANT ALL PRIVILEGES ON source_license.* TO 'source_license'@'localhost';
    FLUSH PRIVILEGES;
    
    -- PostgreSQL
    CREATE DATABASE source_license;
    CREATE USER source_license WITH PASSWORD 'secure_password';
    GRANT ALL PRIVILEGES ON DATABASE source_license TO source_license;

Application Runtime Issues

Port Already in Use

Error:

Address already in use - bind(2) for "127.0.0.1" port 4567

Solutions:

  1. Find and kill process using port:

    # Find process using port 4567
    lsof -ti:4567
    
    # Kill the process
    kill -9 $(lsof -ti:4567)
    
    # Or use a different port
    APP_PORT=4568 ruby launch.rb
  2. Check for multiple instances:

    ps aux | grep ruby
    # Kill any existing Source-License processes

Missing Environment Variables

Error:

APP_SECRET must be set in production

Solution:

# Check .env file exists and contains required variables
cat .env

# Copy from example if missing
cp .env.example .env

# Edit with your specific values
nano .env

Required variables:

APP_SECRET=your_very_long_secret_key_at_least_64_characters_long_for_security
JWT_SECRET=another_secret_key_for_jwt_tokens
DATABASE_ADAPTER=mysql
DATABASE_HOST=localhost
DATABASE_NAME=source_license
DATABASE_USER=username
DATABASE_PASSWORD=password
ADMIN_EMAIL=admin@yourdomain.com
ADMIN_PASSWORD=secure_admin_password

Payment Gateway Issues

Stripe Integration Problems

Error:

Stripe::AuthenticationError: Invalid API Key provided

Solutions:

  1. Verify Stripe API keys:

    STRIPE_PUBLISHABLE_KEY=pk_live_... (or pk_test_... for testing)
    STRIPE_SECRET_KEY=sk_live_... (or sk_test_... for testing)
    STRIPE_WEBHOOK_SECRET=whsec_...
  2. Check Stripe webhook configuration:

    • Endpoint URL: https://yourdomain.com/api/webhook/stripe
    • Events: payment_intent.succeeded, payment_intent.payment_failed
    • Webhook secret: Must match STRIPE_WEBHOOK_SECRET in .env
  3. Test Stripe connection:

    # In Rails console or test script
    require 'stripe'
    Stripe.api_key = ENV['STRIPE_SECRET_KEY']
    
    begin
      Stripe::Account.retrieve
      puts "Stripe connection successful"
    rescue => e
      puts "Stripe error: #{e.message}"
    end

PayPal Integration Problems

Error:

PayPal::Exception::UnauthorizedAccess

Solutions:

  1. Verify PayPal credentials:

    PAYPAL_CLIENT_ID=your_paypal_client_id
    PAYPAL_CLIENT_SECRET=your_paypal_client_secret
    PAYPAL_ENVIRONMENT=sandbox # or production
  2. Check PayPal webhook settings:

    • Webhook URL: https://yourdomain.com/api/webhook/paypal
    • Events: PAYMENT.CAPTURE.COMPLETED, PAYMENT.CAPTURE.DENIED

License Management Issues

License Generation Failures

Error:

License key generation failed: Duplicate entry

Solutions:

  1. Check for license key conflicts:

    # In admin console
    duplicate_keys = License.group(:license_key).having(Sequel.function(:count, :id) > 1)
    puts "Duplicate keys found: #{duplicate_keys.count}"
  2. Regenerate conflicting licenses:

    # Find and regenerate duplicate licenses
    License.where(license_key: 'DUPLICATE-KEY').each do |license|
      new_key = LicenseGenerator.generate_unique_key
      license.update(license_key: new_key)
    end
  3. Check license format configuration:

    # Verify license format settings
    puts SettingsManager.get('license.default_format')
    puts SettingsManager.get('license.default_max_activations')

License Validation API Issues

Error:

{"valid": false, "error": "license_not_found"}

Debugging steps:

  1. Verify license exists in database:

    # Check database directly
    mysql -u username -p source_license
    SELECT * FROM licenses WHERE license_key = 'YOUR-LICENSE-KEY';
  2. Check API endpoint accessibility:

    curl -v http://localhost:4567/api/license/TEST-KEY/validate
  3. Review application logs:

    tail -f logs/application.log
    tail -f logs/error.log

Email Delivery Issues

SMTP Configuration Problems

Error:

Net::SMTPAuthenticationError: 535 Authentication failed

Solutions:

  1. Verify SMTP settings:

    SMTP_HOST=smtp.gmail.com
    SMTP_PORT=587
    SMTP_USERNAME=your_email@gmail.com
    SMTP_PASSWORD=your_app_password  # Not your regular password!
    SMTP_TLS=true
  2. For Gmail, use App Passwords:

    • Enable 2-factor authentication
    • Generate App Password in Google Account settings
    • Use App Password in SMTP_PASSWORD
  3. Test SMTP connection:

    require 'mail'
    
    Mail.defaults do
      delivery_method :smtp, {
        address: ENV['SMTP_HOST'],
        port: ENV['SMTP_PORT'].to_i,
        user_name: ENV['SMTP_USERNAME'],
        password: ENV['SMTP_PASSWORD'],
        authentication: 'plain',
        enable_starttls_auto: true
      }
    end
    
    # Test email
    Mail.deliver do
      from ENV['SMTP_USERNAME']
      to 'test@example.com'
      subject 'Test email'
      body 'This is a test email from Source-License'
    end

License Emails Not Delivered

Debugging steps:

  1. Check email delivery logs:

    grep -i "email" logs/application.log
    grep -i "mail" logs/application.log
  2. Verify email template exists:

    ls -la views/emails/
  3. Test manual email delivery:

    # In admin panel or console
    license = License.first
    EmailService.send_license_email(license, 'test@example.com')

🔧 System Administration Issues

Memory and Performance Problems

High Memory Usage

Symptoms:

  • Slow response times
  • Application crashes
  • "Out of memory" errors

Solutions:

  1. Monitor memory usage:

    # Check system memory
    free -h
    
    # Check Ruby process memory
    ps aux | grep ruby
    top -p $(pgrep ruby)
  2. Optimize database queries:

    # Enable query logging
    DB.loggers = [Logger.new(STDOUT)]
    
    # Look for N+1 queries and optimize with eager loading
    licenses = License.eager(:product, :license_activations).all
  3. Implement caching:

    # Cache frequently accessed settings
    class SettingsCache
      def self.get(key)
        @cache ||= {}
        @cache[key] ||= SettingsManager.get_from_db(key)
      end
    end

Database Performance Issues

Symptoms:

  • Slow query responses
  • High CPU usage
  • Connection timeouts

Solutions:

  1. Add database indexes:

    -- Common indexes for Source-License
    CREATE INDEX idx_licenses_customer_email ON licenses(customer_email);
    CREATE INDEX idx_licenses_product_status ON licenses(product_id, status);
    CREATE INDEX idx_license_activations_machine ON license_activations(machine_fingerprint);
    CREATE INDEX idx_orders_created_at ON orders(created_at);
  2. Optimize database configuration:

    # MySQL optimization (/etc/mysql/my.cnf)
    [mysqld]
    innodb_buffer_pool_size = 1G
    innodb_log_file_size = 256M
    query_cache_type = 1
    query_cache_size = 32M
  3. Monitor slow queries:

    -- MySQL
    SET GLOBAL slow_query_log = 'ON';
    SET GLOBAL long_query_time = 2;
    
    -- Check slow query log
    SHOW VARIABLES LIKE 'slow_query_log_file';

Security Issues

Failed Admin Login Attempts

Symptoms:

  • Multiple failed login attempts in logs
  • Account lockouts
  • Suspicious IP addresses

Response procedures:

  1. Review security logs:

    grep -i "failed.*login" logs/security.log
    grep -i "authentication.*error" logs/application.log
  2. Check for brute force attacks:

    # Count failed attempts by IP
    grep "failed login" logs/security.log | awk '{print $5}' | sort | uniq -c | sort -nr
  3. Block suspicious IPs:

    # Using iptables
    sudo iptables -A INPUT -s SUSPICIOUS_IP -j DROP
    
    # Using fail2ban (recommended)
    sudo apt-get install fail2ban
  4. Reset admin passwords:

    # In console
    admin = Admin.first(email: 'admin@yourdomain.com')
    admin.password = 'new_secure_password'
    admin.save

SSL/TLS Configuration Issues

Error:

SSL_ERROR_SSL: certificate verify failed

Solutions:

  1. Check SSL certificate validity:

    openssl x509 -in /path/to/certificate.crt -text -noout
    curl -vI https://yourdomain.com
  2. Verify Nginx SSL configuration:

    server {
        listen 443 ssl http2;
        server_name yourdomain.com;
        
        ssl_certificate /path/to/certificate.crt;
        ssl_certificate_key /path/to/private.key;
        ssl_protocols TLSv1.2 TLSv1.3;
        ssl_ciphers ECDHE-RSA-AES256-GCM-SHA512:DHE-RSA-AES256-GCM-SHA512;
    }
  3. Force HTTPS in application:

    configure :production do
      # Force HTTPS
      use Rack::SslEnforcer
      
      # Or in Sinatra settings
      set :force_ssl, true
    end

📊 Monitoring and Diagnostics

Log Analysis

Application Logs

Location: logs/application.log

Common log patterns:

# Successful operations
grep "SUCCESS" logs/application.log

# License validations
grep "license.*validate" logs/application.log

# Payment processing
grep -i "payment" logs/application.log

# Database errors
grep -i "database.*error\|sequel.*error" logs/application.log

Error Logs

Location: logs/error.log

Critical error patterns:

# Application crashes
grep -i "fatal\|crash" logs/error.log

# Memory issues
grep -i "memory\|heap" logs/error.log

# Database connection issues
grep -i "connection.*failed\|timeout" logs/error.log

Security Logs

Location: logs/security.log

Security event patterns:

# Authentication events
grep -i "auth\|login" logs/security.log

# Failed access attempts
grep -i "unauthorized\|forbidden" logs/security.log

# Suspicious activities
grep -i "suspicious\|attack" logs/security.log

Health Checks

Application Health Check

Create a simple health check script:

#!/usr/bin/env ruby
# health_check.rb

require_relative 'lib/database'

def check_database
  DB.test_connection
  puts "✓ Database connection: OK"
rescue => e
  puts "✗ Database connection: FAILED - #{e.message}"
  exit 1
end

def check_redis
  # If using Redis
  # Redis connection check
rescue => e
  puts "✗ Redis connection: FAILED - #{e.message}"
end

def check_disk_space
  usage = `df -h / | tail -1 | awk '{print $5}' | sed 's/%//'`.to_i
  if usage > 90
    puts "✗ Disk space: CRITICAL - #{usage}% used"
    exit 1
  else
    puts "✓ Disk space: OK - #{usage}% used"
  end
end

def check_memory
  # Check available memory
  mem_info = File.read('/proc/meminfo')
  total = mem_info.match(/MemTotal:\s+(\d+)/)[1].to_i
  available = mem_info.match(/MemAvailable:\s+(\d+)/)[1].to_i
  usage = ((total - available) * 100.0 / total).round(1)
  
  if usage > 90
    puts "✗ Memory usage: CRITICAL - #{usage}%"
    exit 1
  else
    puts "✓ Memory usage: OK - #{usage}%"
  end
end

# Run checks
puts "Source-License Health Check"
puts "=" * 30
check_database
check_disk_space
check_memory
puts "All checks passed!"

API Health Check

# Check API endpoints
curl -f http://localhost:4567/api/health || echo "API health check failed"

# Check license validation endpoint
curl -f http://localhost:4567/api/license/TEST-KEY/validate || echo "License API failed"

Performance Monitoring

Database Performance

-- MySQL performance queries
SHOW FULL PROCESSLIST;
SHOW ENGINE INNODB STATUS;

-- Check slow queries
SELECT * FROM mysql.slow_log ORDER BY start_time DESC LIMIT 10;

-- Check table sizes
SELECT 
    table_name,
    round(((data_length + index_length) / 1024 / 1024), 2) AS 'Size (MB)'
FROM information_schema.tables 
WHERE table_schema = 'source_license'
ORDER BY (data_length + index_length) DESC;

Application Performance

# Add performance monitoring to critical endpoints
class PerformanceMonitor
  def self.measure(operation_name)
    start_time = Time.now
    result = yield
    duration = Time.now - start_time
    
    log_performance(operation_name, duration)
    result
  end

  private

  def self.log_performance(operation, duration)
    level = case duration
            when 0..0.1 then 'INFO'
            when 0.1..0.5 then 'WARN'
            else 'ERROR'
            end
    
    Logger.new('logs/performance.log').send(
      level.downcase.to_sym,
      "#{operation}: #{duration.round(3)}s"
    )
  end
end

# Usage in controllers
post '/api/license/:key/activate' do
  PerformanceMonitor.measure('license_activation') do
    # Activation logic
  end
end

🔄 Backup and Recovery

Database Backup Issues

Backup Failures

Error:

mysqldump: Access denied for user 'backup'@'localhost'

Solutions:

  1. Create backup user with proper permissions:

    CREATE USER 'backup'@'localhost' IDENTIFIED BY 'secure_backup_password';
    GRANT SELECT, LOCK TABLES, SHOW VIEW ON source_license.* TO 'backup'@'localhost';
    FLUSH PRIVILEGES;
  2. Test backup manually:

    mysqldump -u backup -p source_license > backup_test.sql
  3. Automated backup script:

    #!/bin/bash
    # backup.sh
    
    DATE=$(date +%Y%m%d_%H%M%S)
    BACKUP_DIR="/var/backups/source-license"
    DB_NAME="source_license"
    
    mkdir -p $BACKUP_DIR
    
    # Database backup
    mysqldump -u backup -p$DB_PASSWORD $DB_NAME | gzip > $BACKUP_DIR/db_$DATE.sql.gz
    
    # Application files backup
    tar -czf $BACKUP_DIR/files_$DATE.tar.gz /path/to/source-license --exclude=logs --exclude=tmp
    
    # Keep only last 30 days
    find $BACKUP_DIR -name "*.gz" -mtime +30 -delete
    
    echo "Backup completed: $DATE"

Recovery Procedures

Database Recovery

  1. Stop application:

    sudo systemctl stop source-license
    # or kill the Ruby process
  2. Restore database:

    # Restore from SQL dump
    mysql -u root -p source_license < backup_20240115_120000.sql
    
    # Restore from compressed backup
    gunzip -c db_20240115_120000.sql.gz | mysql -u root -p source_license
  3. Verify data integrity:

    -- Check table counts
    SELECT COUNT(*) FROM users;
    SELECT COUNT(*) FROM licenses;
    SELECT COUNT(*) FROM orders;
    
    -- Check for orphaned records
    SELECT l.* FROM licenses l LEFT JOIN products p ON l.product_id = p.id WHERE p.id IS NULL;
  4. Restart application:

    ruby launch.rb
    # or
    sudo systemctl start source-license

📞 Getting Help

Diagnostic Information Collection

When reporting issues, collect this information:

#!/bin/bash
# collect_diagnostics.sh

echo "Source-License Diagnostic Information"
echo "===================================="
echo "Date: $(date)"
echo "Hostname: $(hostname)"
echo ""

echo "System Information:"
echo "OS: $(lsb_release -d 2>/dev/null || cat /etc/os-release | grep PRETTY_NAME)"
echo "Ruby Version: $(ruby --version)"
echo "Bundler Version: $(bundle --version)"
echo ""

echo "Application Status:"
echo "Process: $(ps aux | grep -v grep | grep ruby | head -1)"
echo "Port 4567: $(lsof -ti:4567 2>/dev/null && echo 'In use' || echo 'Available')"
echo ""

echo "Database Connection:"
mysql -u $DATABASE_USER -p$DATABASE_PASSWORD -e "SELECT 1" 2>/dev/null && echo "MySQL: OK" || echo "MySQL: FAILED"

echo ""
echo "Disk Space:"
df -h /

echo ""
echo "Memory Usage:"
free -h

echo ""
echo "Recent Error Log:"
tail -20 logs/error.log 2>/dev/null || echo "No error log found"

echo ""
echo "Environment Variables:"
env | grep -E "(DATABASE|STRIPE|PAYPAL|SMTP)" | sed 's/=.*$/=***HIDDEN***/'

Support Channels

  1. GitHub Issues: For bugs and feature requests

    • Include diagnostic information
    • Provide minimal reproduction steps
    • Include relevant log excerpts
  2. GitHub Discussions: For questions and community support

    • Search existing discussions first
    • Provide context about your setup
  3. Security Issues: Email security@pixelridgesoftworks.com

    • Do not post security issues publicly
    • Include detailed information about the vulnerability

Emergency Procedures

Complete System Failure

  1. Immediate Response:

    # Check if system is completely down
    curl -f http://localhost:4567/ || echo "Application down"
    
    # Check process status
    ps aux | grep ruby
    
    # Check system resources
    free -h && df -h
  2. Recovery Steps:

    # Restart application
    cd /path/to/source-license
    ruby launch.rb
    
    # If database issues
    sudo systemctl restart mysql
    
    # If memory issues
    sudo systemctl restart source-license
  3. Escalation:

    • Document all error messages
    • Collect diagnostic information
    • Contact support with complete details

Data Corruption

  1. Stop application immediately
  2. Restore from latest backup
  3. Run data integrity checks
  4. Test critical functionality
  5. Document the incident

This troubleshooting guide covers the most common issues encountered with Source-License. For additional support, refer to the GitHub Issues page or consult the Development Guide for technical implementation details.

Clone this wiki locally