SonarQube Business Continuity
SonarQube Static Code Analysis Quality Gates Bugs Code Smells Security Vulnerabilities Business Continuity Disaster Recovery RTO RPO Backup Failover
| Metric | Description | Target |
|---|---|---|
| Bugs | Logic errors ที่อาจทำให้ระบบ Crash | 0 (New Code) |
| Vulnerabilities | Security issues ที่อาจถูกโจมตี | 0 (New Code) |
| Code Smells | Maintainability issues | < 10 (New Code) |
| Coverage | Unit Test Coverage | > 80% |
| Duplications | Duplicated code blocks | < 3% |
| Security Hotspots | Code ที่ต้อง Review ด้าน Security | Reviewed 100% |
SonarQube Setup และ CI/CD
# === SonarQube Setup ===
# Docker Compose
# version: '3.8'
# services:
# sonarqube:
# image: sonarqube:community
# ports:
# - "9000:9000"
# environment:
# - SONAR_JDBC_URL=jdbc:postgresql://db:5432/sonar
# - SONAR_JDBC_USERNAME=sonar
# - SONAR_JDBC_PASSWORD=sonar
# volumes:
# - sonarqube_data:/opt/sonarqube/data
# - sonarqube_logs:/opt/sonarqube/logs
# depends_on:
# - db
#
# db:
# image: postgres:15
# environment:
# - POSTGRES_USER=sonar
# - POSTGRES_PASSWORD=sonar
# - POSTGRES_DB=sonar
# volumes:
# - postgresql_data:/var/lib/postgresql/data
#
# volumes:
# sonarqube_data:
# sonarqube_logs:
# postgresql_data:
# GitHub Actions Integration
# name: SonarQube Analysis
# on: [push, pull_request]
# jobs:
# sonarqube:
# runs-on: ubuntu-latest
# steps:
# - uses: actions/checkout@v4
# with:
# fetch-depth: 0
# - uses: SonarSource/sonarqube-scan-action@v2
# env:
# SONAR_TOKEN: }
# SONAR_HOST_URL: }
# - uses: SonarSource/sonarqube-quality-gate-check@v1
# env:
# SONAR_TOKEN: }
# sonar-project.properties
# sonar.projectKey=my-app
# sonar.projectName=My Application
# sonar.sources=src
# sonar.tests=tests
# sonar.language=py
# sonar.python.coverage.reportPaths=coverage.xml
# sonar.qualitygate.wait=true
from dataclasses import dataclass
from typing import List, Dict
@dataclass
class SonarReport:
project: str
bugs: int
vulnerabilities: int
code_smells: int
coverage: float
duplications: float
security_hotspots: int
quality_gate: str
reports = [
SonarReport("api-service", 0, 0, 12, 87.5, 2.1, 3, "Passed"),
SonarReport("web-frontend", 2, 1, 25, 72.3, 4.5, 5, "Failed"),
SonarReport("data-pipeline", 0, 0, 8, 91.2, 1.8, 1, "Passed"),
SonarReport("auth-service", 0, 0, 5, 95.0, 0.5, 0, "Passed"),
]
print("=== SonarQube Dashboard ===")
for r in reports:
icon = "PASS" if r.quality_gate == "Passed" else "FAIL"
print(f"\n [{icon}] {r.project}")
print(f" Bugs: {r.bugs} | Vulns: {r.vulnerabilities} | "
f"Smells: {r.code_smells}")
print(f" Coverage: {r.coverage}% | Dup: {r.duplications}% | "
f"Hotspots: {r.security_hotspots}")
Business Continuity Planning
# === Business Continuity & Disaster Recovery ===
@dataclass
class BCPComponent:
system: str
tier: str
rto_hours: float
rpo_hours: float
backup_strategy: str
failover: str
dr_site: str
components = [
BCPComponent("Production Database", "Tier 1", 1, 0.25,
"Real-time Replication + Hourly Snapshots",
"Auto-failover to Standby", "AWS us-west-2"),
BCPComponent("API Servers", "Tier 1", 0.5, 0,
"Infrastructure as Code (Terraform)",
"Auto-scaling + Multi-AZ", "AWS us-west-2"),
BCPComponent("Authentication", "Tier 1", 0.5, 0,
"Multi-region Active-Active",
"DNS Failover", "AWS eu-west-1"),
BCPComponent("File Storage", "Tier 2", 4, 1,
"Cross-region S3 Replication",
"Manual Switch", "AWS us-west-2"),
BCPComponent("Analytics DB", "Tier 3", 24, 4,
"Daily Snapshots + Weekly Full Backup",
"Restore from Backup", "AWS us-west-2"),
BCPComponent("SonarQube", "Tier 3", 48, 24,
"Daily DB Dump + Config Backup",
"Rebuild from IaC", "N/A"),
]
print("\n=== Business Continuity Plan ===")
print(f"{'System':<22} {'Tier':<8} {'RTO':>5} {'RPO':>5} Failover")
for c in components:
print(f" {c.system:<22} {c.tier:<8} {c.rto_hours:>4.1f}h {c.rpo_hours:>4.1f}h "
f"{c.failover}")
# DR Test Schedule
dr_tests = [
{"test": "Database Failover", "frequency": "Monthly", "last": "2024-03-15", "result": "Pass"},
{"test": "Full DR Simulation", "frequency": "Quarterly", "last": "2024-01-20", "result": "Pass"},
{"test": "Backup Restore", "frequency": "Weekly", "last": "2024-03-18", "result": "Pass"},
{"test": "Network Failover", "frequency": "Monthly", "last": "2024-03-10", "result": "Pass"},
{"test": "Communication Plan", "frequency": "Quarterly", "last": "2024-01-20", "result": "Pass"},
]
print(f"\n\nDR Test Schedule:")
for t in dr_tests:
print(f" [{t['result']}] {t['test']} — {t['frequency']} (Last: {t['last']})")
Automation และ Monitoring
# === Automated Recovery & Monitoring ===
# Backup Script
# #!/bin/bash
# DATE=$(date +%Y%m%d_%H%M%S)
# BACKUP_DIR="/backup/$DATE"
# mkdir -p $BACKUP_DIR
#
# # Database backup
# pg_dump -h $DB_HOST -U $DB_USER $DB_NAME | \
# gzip > $BACKUP_DIR/db_$DATE.sql.gz
#
# # SonarQube config
# tar -czf $BACKUP_DIR/sonar_config_$DATE.tar.gz \
# /opt/sonarqube/conf/
#
# # Upload to S3
# aws s3 sync $BACKUP_DIR s3://backups/dr/$DATE/
#
# # Verify
# aws s3 ls s3://backups/dr/$DATE/ | wc -l
#
# # Cleanup old backups (keep 30 days)
# find /backup -mtime +30 -delete
# Health Check Automation
# import requests
# import time
#
# def health_check(services):
# results = {}
# for name, url in services.items():
# try:
# r = requests.get(f"{url}/health", timeout=5)
# results[name] = {
# "status": "healthy" if r.status_code == 200 else "unhealthy",
# "latency_ms": r.elapsed.total_seconds() * 1000,
# }
# except Exception as e:
# results[name] = {"status": "down", "error": str(e)}
# return results
recovery_playbook = {
"Database Down": [
"1. Check replication status: SELECT * FROM pg_stat_replication",
"2. If primary down: Promote standby to primary",
"3. Update connection strings via Config Manager",
"4. Verify application connectivity",
"5. Alert team and update Status Page",
],
"API Server Down": [
"1. Check Auto-scaling group status",
"2. If AZ failure: Traffic routes to healthy AZ automatically",
"3. If all down: kubectl rollout restart deployment/api",
"4. Check health endpoints",
"5. Monitor error rates for 15 minutes",
],
"Full Region Failure": [
"1. Activate DR plan — switch DNS to DR region",
"2. Verify database replication caught up",
"3. Scale up DR region instances",
"4. Update external integrations with new endpoints",
"5. Communicate to stakeholders via Status Page",
],
}
print("Recovery Playbooks:")
for scenario, steps in recovery_playbook.items():
print(f"\n [{scenario}]")
for step in steps:
print(f" {step}")
เคล็ดลับ
- Quality Gate: ตั้ง Quality Gate ทุก Project Block merge ถ้าไม่ผ่าน
- New Code: Focus Quality Gate ที่ New Code ไม่ต้องแก้ Legacy ทั้งหมด
- DR Test: ทดสอบ DR Plan อย่างน้อยทุก Quarter อย่าแค่เขียนแผน
- RTO/RPO: กำหนด RTO/RPO ตาม Business Impact ไม่ใช่ทุกระบบเท่ากัน
- Automate: Automate Backup และ Recovery ลดเวลา Manual Steps
SonarQube คืออะไร
Open Source Static Code Analysis Bugs Code Smells Vulnerabilities Coverage Quality Gates CI/CD 30+ ภาษา Java Python JavaScript
Business Continuity Planning คืออะไร
วางแผนธุรกิจดำเนินต่อ Disaster Recovery Backup Failover Communication RTO RPO ทดสอบสม่ำเสมอ
Quality Gate คืออะไร
เกณฑ์ผ่าน/ไม่ผ่าน Coverage > 80% Bugs = 0 Vulns = 0 Smells < 10 Dup < 3% CI/CD Fail ถ้าไม่ผ่าน
RTO กับ RPO คืออะไร
RTO เวลากู้คืนสูงสุด RPO ข้อมูลสูญเสียสูงสุด Backup Frequency DR Strategy Tier ตาม Business Impact
สรุป
SonarQube Static Analysis Quality Gates Bugs Vulnerabilities Coverage Business Continuity Disaster Recovery RTO RPO Backup Failover DR Test Automation Recovery Playbook CI/CD Pipeline
