# SonarQube

> **Leading Platform for Code Quality and Security Review**

## 📋 Overview

SonarQube adalah platform open-source untuk continuous inspection code quality, security testing, dan code review. Digunakan untuk mendeteksi bugs, vulnerabilities, dan code smells dalam 25+ programming languages.

## 🎯 Key Features

### 🔍 **Code Quality Analysis**

* **Bug Detection** - Runtime errors dan logic bugs
* **Code Smells** - Maintainability dan readability issues
* **Technical Debt** - Quantification dan tracking
* **Complexity Metrics** - Cyclomatic complexity, cognitive complexity
* **Duplicated Code** - Code duplication detection

### 🛡️ **Security Analysis**

* **Vulnerabilities** - OWASP Top 10, CVEs, security issues
* **Hotspots** - Security-sensitive code patterns
* **Taint Analysis** - Data flow tracking
* **Injection Detection** - SQL, NoSQL, command injection
* **XSS Prevention** - Cross-site scripting detection

### 🌐 **Multi-Language Support**

* **Java**, **JavaScript**, **TypeScript**, **Python**
* **C#**, **C/C++**, **Go**, **Ruby**, **PHP**
* **Kotlin**, **Scala**, **Swift**, **Objective-C**
* **Web**: **HTML**, **CSS**, **XML**, **JSON**

### 📊 **Dashboard & Reporting**

* **Quality Gate** - Custom quality thresholds
* **Portfolio Management** - Multi-project overview
* **Technical Debt Metrics** - Time-based debt calculation
* **Security Hotspots Review** - Manual security review
* **Compliance Reports** - ISO 27001, OWASP ASVS

## 🚀 Installation

### Docker Installation (Recommended)

```bash
# Start SonarQube with PostgreSQL
docker-compose up -d

# docker-compose.yml
version: "3"
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_extensions:/opt/sonarqube/extensions
      - sonarqube_logs:/opt/sonarqube/logs
      - sonarqube_temp:/opt/sonarqube/temp
  db:
    image: postgres:13
    environment:
      - POSTGRES_USER=sonar
      - POSTGRES_PASSWORD=sonar
      - POSTGRES_DB=sonar
    volumes:
      - postgres_data:/var/lib/postgresql/data

volumes:
  sonarqube_data:
  sonarqube_extensions:
  sonarqube_logs:
  sonarqube_temp:
  postgres_data:
```

### Manual Installation

```bash
# Download SonarQube
wget https://binaries.sonarsource.com/Distribution/sonarqube/sonarqube-9.9.0.65466.zip

# Extract
unzip sonarqube-9.9.0.65466.zip
cd sonarqube-9.9.0.65466

# Start SonarQube
# Linux/macOS
./bin/linux-x86-64/sonar.sh start

# Windows
./bin/windows-x86-64/StartSonar.bat
```

## 🔧 Configuration

### System Requirements

* **Java**: OpenJDK 11 or 17
* **Database**: PostgreSQL, Microsoft SQL Server, Oracle, MySQL
* **Memory**: Minimum 2GB RAM (4GB+ recommended)
* **Disk**: 10GB+ SSD storage

### Database Setup

```sql
-- PostgreSQL Setup
CREATE DATABASE sonar WITH ENCODING 'UTF8';
CREATE USER sonar WITH PASSWORD 'sonar';
GRANT ALL PRIVILEGES ON DATABASE sonar TO sonar;
```

### Configuration File (sonar.properties)

```properties
# Database Configuration
sonar.jdbc.url=jdbc:postgresql://localhost/sonar
sonar.jdbc.username=sonar
sonar.jdbc.password=sonar

# Web Server Configuration
sonar.web.host=0.0.0.0
sonar.web.port=9000
sonar.web.context=/

# Search Server Configuration
sonar.search.host=0.0.0.0
sonar.search.port=9001

# Compute Engine Configuration
sonar.ce.workerCount=4
sonar.ce.hardTimeoutHours=24
```

## 🔍 Scanning Projects

### SonarScanner Setup

```bash
# Download SonarScanner
wget https://binaries.sonarsource.com/Distribution/sonar-scanner-cli/sonar-scanner-cli-4.8.0.2856.zip

# Add to PATH
export PATH=$PATH:/path/to/sonar-scanner-4.8.0.2856/bin
```

### Basic Scan

```bash
# Navigate to project directory
cd /path/to/your/project

# Run scan
sonar-scanner \
  -Dsonar.projectKey=my-project \
  -Dsonar.sources=. \
  -Dsonar.host.url=http://localhost:9000 \
  -Dsonar.login=your-token
```

### Configuration File (sonar-project.properties)

```properties
# Project Configuration
sonar.projectKey=my-awesome-project
sonar.projectName=My Awesome Project
sonar.projectVersion=1.0

# Sources
sonar.sources=src
sonar.tests=tests
sonar.inclusions=**/*.java,**/*.py,**/*.js
sonar.exclusions=**/node_modules/**,**/target/**

# Coverage
sonar.coverage.jacoco.xmlReportPaths=target/site/jacoco/jacoco.xml
sonar.python.coverage.reportPaths=coverage.xml

# Language Specific
sonar.java.binaries=target/classes
sonar.python.xunit.reportPath=tests/reports/xunit.xml
```

## 🔗 CI/CD Integration

### GitHub Actions

```yaml
# .github/workflows/sonarqube.yml
name: SonarQube Scan
on: [push, pull_request]

jobs:
  sonarqube:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
        with:
          fetch-depth: 0
      - name: Set up JDK 11
        uses: actions/setup-java@v3
        with:
          java-version: 11
          distribution: 'temurin'
      - name: Cache SonarQube packages
        uses: actions/cache@v3
        with:
          path: ~/.sonar/cache
          key: ${{ runner.os }}-sonar
          restore-keys: ${{ runner.os }}-sonar
      - name: Build with Maven
        run: mvn -B verify sonar:sonar -Dsonar.projectKey=your-project-key
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
          SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }}
```

### GitLab CI

```yaml
# .gitlab-ci.yml
sonarqube-check:
  stage: test
  image: maven:3.8.6-openjdk-11
  variables:
    SONAR_USER_HOME: "${CI_PROJECT_DIR}/.sonar"
    GIT_DEPTH: "0"
  cache:
    key: "${CI_JOB_NAME}"
    paths:
      - .sonar/cache
  script:
    - mvn verify sonar:sonar -Dsonar.projectKey=your-project-key
  allow_failure: true
  rules:
    - if: $CI_PIPELINE_SOURCE == 'merge_request_event'
    - if: $CI_COMMIT_BRANCH == 'main'
```

### Jenkins Pipeline

```groovy
pipeline {
    agent any
    stages {
        stage('SonarQube Analysis') {
            steps {
                withSonarQubeEnv('My SonarQube Server') {
                    sh 'mvn clean package sonar:sonar'
                }
            }
        }
        stage('Quality Gate') {
            steps {
                timeout(time: 1, unit: 'HOURS') {
                    waitForQualityGate abortPipeline: true
                }
            }
        }
    }
}
```

## 📊 Quality Gates

### Default Quality Gate Rules

* **Coverage**: New code coverage > 80%
* **Duplicated Lines**: New duplicated code < 3%
* **Maintainability Rating**: New code rated A or B
* **Reliability Rating**: No new reliability issues
* **Security Rating**: No new security issues
* **Technical Debt**: New technical debt < 1 day

### Custom Quality Gate

```bash
# Create custom quality gate via UI
# Administration → Quality Gates → Create

# Custom Conditions:
# - Coverage on New Code > 90%
# - New Bugs = 0
# - New Vulnerabilities = 0
# - New Code Smells < 10
# - Duplicated Lines on New Code < 1%
```

## 🔧 Language-Specific Setup

### Java Projects

```xml
<!-- pom.xml -->
<plugin>
    <groupId>org.sonarsource.scanner.maven</groupId>
    <artifactId>sonar-maven-plugin</artifactId>
    <version>3.9.1.2184</version>
</plugin>

<!-- JaCoCo Coverage -->
<plugin>
    <groupId>org.jacoco</groupId>
    <artifactId>jacoco-maven-plugin</artifactId>
    <version>0.8.7</version>
    <executions>
        <execution>
            <goals>
                <goal>prepare-agent</goal>
            </goals>
        </execution>
        <execution>
            <id>report</id>
            <phase>test</phase>
            <goals>
                <goal>report</goal>
            </goals>
        </execution>
    </executions>
</plugin>
```

### Python Projects

```bash
# Install dependencies
pip install pytest pytest-cov

# Run tests with coverage
pytest --cov=app --cov-report=xml tests/

# Run SonarQube scan
sonar-scanner \
  -Dsonar.projectKey=my-python-project \
  -Dsonar.sources=src \
  -Dsonar.tests=tests \
  -Dsonar.python.coverage.reportPaths=coverage.xml
```

### JavaScript/TypeScript

```bash
# Install dependencies
npm install --save-dev jest nyc

# Run tests with coverage
npm test -- --coverage

# Run SonarQube scan
sonar-scanner \
  -Dsonar.projectKey=my-js-project \
  -Dsonar.sources=src \
  -Dsonar.tests=tests \
  -Dsonar.javascript.lcov.reportPaths=coverage/lcov.info
```

## 📈 Advanced Features

### Portfolio Management

```bash
# Create portfolio via UI
# Portfolios → Create Portfolio
# Add projects and sub-portfolios
# Set quality gate and metrics
```

### Security Hotspots Review

```markdown
# Security Hotspots Workflow:
1. Developer writes security-sensitive code
2. SonarQube detects potential security hotspot
3. Security team reviews and marks as:
   - Fixed - Code is secure
   - Safe - No action needed
   - To Review - Requires investigation
   - Won't Fix - Accepted risk
```

### Custom Rules

```xml
<!-- Custom Java Rule -->
<rule>
  <key>MyCustomRule</key>
  <name>My Custom Rule</name>
  <description>Detect custom code patterns</description>
  <severity>MAJOR</severity>
  <type>CODE_SMELL</type>
  <cardinality>SINGLE</cardinality>
  <template>false</template>
</rule>
```

## 🔧 Administration

### User Management

```bash
# Create user groups
# Administration → Security → Groups

# User roles:
# - Administrators - Full system access
# - Security Auditors - Review security hotspots
# - Quality Profile Managers - Manage quality profiles
# - Project Administrators - Manage specific projects
```

### Quality Profiles

```bash
# Create custom quality profile
# Quality Profiles → Create Profile

# Built-in profiles:
# - Sonar way - Recommended rules
# - Sonar way (with security) - Security included
# - Security Hotspots - Security-focused rules
```

### Backup and Recovery

```bash
# Backup data directory
tar -czf sonar-backup-$(date +%Y%m%d).tar.gz /opt/sonarqube/data

# Database backup (PostgreSQL)
pg_dump sonar > sonar-db-backup-$(date +%Y%m%d).sql

# Restore
tar -xzf sonar-backup-20240101.tar.gz -C /opt/sonarqube/
psql sonar < sonar-db-backup-20240101.sql
```

## 📊 Monitoring & Maintenance

### System Health

```bash
# Web API Health Check
curl http://localhost:9000/api/system/status

# Check logs
tail -f /opt/sonarqube/logs/sonar.log

# Database connection test
curl -u admin:admin \
  http://localhost:9000/api/system/health
```

### Performance Optimization

```properties
# sonar.properties optimizations
sonar.ce.workerCount=8
sonar.search.javaOpts=-Xmx4g -Xms4g
sonar.web.javaOpts=-Xmx2g -Xms2g
```

## 🎓 Learning Resources

### Official Documentation

* [SonarQube Documentation](https://docs.sonarqube.org/)
* [Analyzing Source Code](https://docs.sonarqube.org/latest/analysis/)
* [CI/CD Integration](https://docs.sonarqube.org/latest/analysis/scan/sonarscanner/)
* [Security Features](https://docs.sonarqube.org/latest/user-guide/security-reports/)

### Best Practices

* **Start Small** - Begin with basic quality gates
* **Gradual Adoption** - Add rules incrementally
* **Regular Reviews** - Review and update quality profiles
* **Team Training** - Educate developers on quality practices
* **Integration** - Embed in development workflow

## 📈 Comparison with Other Tools

| Feature            | SonarQube      | Semgrep     | Checkmarx     | Veracode      |
| ------------------ | -------------- | ----------- | ------------- | ------------- |
| **Open Source**    | ✅ Community    | ✅ Full      | ❌             | ❌             |
| **Security Focus** | 🟡 Medium      | ✅ Strong    | ✅ Strong      | ✅ Strong      |
| **Code Quality**   | ✅ Strong       | 🟡 Limited  | 🟡 Limited    | 🟡 Limited    |
| **Self-Hosted**    | ✅              | ✅           | 💰 Enterprise | ❌             |
| **Enterprise**     | 💰 Data Center | 💰 Platform | 💰 Enterprise | 💰 Enterprise |
| **Learning Curve** | 📚 Medium      | 📚 Easy     | 📚 Hard       | 📚 Medium     |

## 🔧 Troubleshooting

### Common Issues

```bash
# Out of Memory Errors
# Increase heap size
export SONAR_SCANNER_OPTS="-Xmx4g"

# Database Connection Issues
# Check database configuration
# Verify network connectivity
# Test credentials

# Scanner Not Finding Files
# Check sonar.sources path
# Verify file permissions
# Check include/exclude patterns
```

### Performance Issues

```bash
# Slow scans
- Reduce analysis scope
- Optimize quality profiles
- Increase worker count
- Use faster hardware

# Database performance
- Optimize PostgreSQL settings
- Add indexes
- Regular maintenance
```

## 🛡️ Enterprise Editions

### SonarQube Developer ($150/year)

* **Branch Analysis** - Multi-branch support
* **Pull Request Decoration** - GitHub, GitLab, Bitbucket
* **Clean as You Code** - New code focus

### SonarQube Enterprise ($400/year)

* **Portfolio Management** - Project grouping
* **Security Reports** - OWASP ASVS, CWE
* **Audit Trail** - Activity logging
* **DevOps Platform Integration** - Extended integrations

### SonarQube Data Center (Custom)

* **High Availability** - Cluster deployment
* **Advanced Security** - SAML, LDAP integration
* **Scalability** - Horizontal scaling
* **Enterprise Support** - 24/7 support

***

**🔒 Remember**: SonarQube is a tool to help improve code quality, not a replacement for code reviews and security practices.

**⚡ Pro Tip**: Start with the built-in "Sonar way" quality profile and gradually customize based on your team's specific needs and priorities.

*📅 Last Updated: 2024*
