SonarQube
SonarQube
A code quality and security analysis platform. Static analysis, technical debt management.
SonarQube
A code quality and security analysis platform. Static analysis, technical debt management.
SonarQube is an open-source static analysis platform that automatically analyzes the quality and security of source code. Developed by SonarSource, it supports more than 30 programming languages, including Java, JavaScript, TypeScript, Python, C/C++, C#, Go, and PHP. It detects code smells, bugs, and security vulnerabilities (OWASP Top 10, CWE), and estimates technical debt in units of time.
The core concept of SonarQube is the Quality Gate. You set thresholds for quality metrics such as code coverage, duplication rate, and the number of bugs/vulnerabilities in new code, and integrate it with the CI/CD pipeline so that deployment is possible only when these thresholds are met. In line with the "Clean as You Code" philosophy, it applies strict standards to newly written/modified code to gradually improve the quality of the codebase.
Analysis results can be viewed in a web dashboard by project and by issue. For each issue, it suggests a problem description, its impact, and how to fix it, and through the IDE plugin (SonarLint), developers can receive real-time feedback while coding. With the Pull Request analysis feature, it automatically detects problems before code review and leaves a report as a PR comment.
SonarQube is offered in Community (free), Developer, Enterprise, and Data Center editions. Higher editions provide additional features such as OWASP/CWE mapping, branch analysis, PR decoration, and support for more languages. SonarCloud is the SaaS version and integrates easily with GitHub, GitLab, and Azure DevOps. It is widely used as a SAST (Static Application Security Testing) tool in DevSecOps pipelines.
# SonarQube ์๋ฒ ์คํ
docker run -d --name sonarqube \
-p 9000:9000 \
-e SONAR_ES_BOOTSTRAP_CHECKS_DISABLE=true \
-v sonarqube_data:/opt/sonarqube/data \
-v sonarqube_extensions:/opt/sonarqube/extensions \
-v sonarqube_logs:/opt/sonarqube/logs \
sonarqube:lts-community
# ๋ธ๋ผ์ฐ์ ์์ http://localhost:9000 ์ ์
# ์ด๊ธฐ ๊ณ์ : admin / admin
# PostgreSQL๊ณผ ํจ๊ป ์คํ (ํ๋ก๋์
)
# docker-compose.yml
# version: "3"
# services:
# sonarqube:
# image: sonarqube:lts-community
# depends_on:
# - db
# environment:
# SONAR_JDBC_URL: jdbc:postgresql://db:5432/sonar
# SONAR_JDBC_USERNAME: sonar
# SONAR_JDBC_PASSWORD: sonar
# ports:
# - "9000:9000"
# db:
# image: postgres:15
# environment:
# POSTGRES_USER: sonar
# POSTGRES_PASSWORD: sonar
# POSTGRES_DB: sonar
# ํ๋ก์ ํธ ์๋ณ
sonar.projectKey=my-project
sonar.projectName=My Project
sonar.projectVersion=1.0
# ์์ค ์ฝ๋ ์์น
sonar.sources=src
sonar.tests=tests
sonar.exclusions=**/node_modules/**,**/dist/**,**/*.test.ts
# ์ธ์ด๋ณ ์ค์
sonar.language=java
sonar.java.binaries=target/classes
sonar.java.source=17
# ์ปค๋ฒ๋ฆฌ์ง ๋ฆฌํฌํธ ์ฐ๋
sonar.coverage.jacoco.xmlReportPaths=target/site/jacoco/jacoco.xml
sonar.javascript.lcov.reportPaths=coverage/lcov.info
sonar.python.coverage.reportPaths=coverage.xml
# ์ ์ ๋ถ์ ๋ฆฌํฌํธ ์ฐ๋ (ESLint, Pylint ๋ฑ)
sonar.eslint.reportPaths=eslint-report.json
sonar.python.pylint.reportPaths=pylint-report.txt
# ์ธ์ฝ๋ฉ
sonar.sourceEncoding=UTF-8
# ๋ธ๋์น ๋ถ์ (Developer Edition ์ด์)
# sonar.branch.name=feature/my-feature
# Pull Request ๋ถ์
# sonar.pullrequest.key=123
# sonar.pullrequest.branch=feature/my-feature
# sonar.pullrequest.base=main
# .github/workflows/sonarqube.yml
name: SonarQube Analysis
on:
push:
branches: [main, develop]
pull_request:
types: [opened, synchronize, reopened]
jobs:
sonarqube:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0 # ์ ์ฒด ํ์คํ ๋ฆฌ (blame ๋ถ์์ฉ)
- name: Set up JDK 17
uses: actions/setup-java@v4
with:
java-version: '17'
distribution: 'temurin'
- name: Cache SonarQube packages
uses: actions/cache@v4
with:
path: ~/.sonar/cache
key: ${{ runner.os }}-sonar
- name: Build and Test with Coverage
run: |
./gradlew build jacocoTestReport
- name: SonarQube Scan
uses: SonarSource/sonarqube-scan-action@master
env:
SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }}
SONAR_HOST_URL: ${{ secrets.SONAR_HOST_URL }}
with:
args: >
-Dsonar.projectKey=my-project
-Dsonar.sources=src/main
-Dsonar.tests=src/test
-Dsonar.java.binaries=build/classes
-Dsonar.coverage.jacoco.xmlReportPaths=build/reports/jacoco/test/jacocoTestReport.xml
# PR ๋ถ์ ์ Quality Gate ๊ฒฐ๊ณผ ํ์ธ
- name: SonarQube Quality Gate
uses: SonarSource/sonarqube-quality-gate-action@master
timeout-minutes: 5
env:
SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }}
# ์์กด์ฑ ์ค์น
pip install coverage pytest pytest-cov
# ํ
์คํธ ๋ฐ ์ปค๋ฒ๋ฆฌ์ง ์์ง
pytest --cov=src --cov-report=xml --cov-report=html tests/
# SonarScanner ์คํ
sonar-scanner \
-Dsonar.projectKey=my-python-project \
-Dsonar.sources=src \
-Dsonar.tests=tests \
-Dsonar.python.coverage.reportPaths=coverage.xml \
-Dsonar.python.version=3.11 \
-Dsonar.host.url=http://localhost:9000 \
-Dsonar.token=$SONAR_TOKEN
import requests
from typing import Optional
class SonarQubeClient:
"""SonarQube REST API ํด๋ผ์ด์ธํธ"""
def __init__(self, base_url: str, token: str):
self.base_url = base_url.rstrip('/')
self.session = requests.Session()
self.session.auth = (token, '') # token as username, empty password
def get_project_status(self, project_key: str) -> dict:
"""ํ๋ก์ ํธ Quality Gate ์ํ ์กฐํ"""
response = self.session.get(
f"{self.base_url}/api/qualitygates/project_status",
params={"projectKey": project_key}
)
response.raise_for_status()
return response.json()
def get_issues(
self,
project_key: str,
severities: Optional[list] = None,
types: Optional[list] = None,
page_size: int = 100
) -> list:
"""ํ๋ก์ ํธ ์ด์ ๋ชฉ๋ก ์กฐํ"""
params = {
"componentKeys": project_key,
"ps": page_size,
"resolved": "false"
}
if severities:
params["severities"] = ",".join(severities)
if types:
params["types"] = ",".join(types)
all_issues = []
page = 1
while True:
params["p"] = page
response = self.session.get(
f"{self.base_url}/api/issues/search",
params=params
)
response.raise_for_status()
data = response.json()
all_issues.extend(data["issues"])
if len(all_issues) >= data["total"]:
break
page += 1
return all_issues
def get_metrics(self, project_key: str, metrics: list) -> dict:
"""ํ๋ก์ ํธ ๋ฉํธ๋ฆญ ์กฐํ"""
response = self.session.get(
f"{self.base_url}/api/measures/component",
params={
"component": project_key,
"metricKeys": ",".join(metrics)
}
)
response.raise_for_status()
return response.json()
def create_quality_gate_condition(
self,
gate_name: str,
metric: str,
operator: str, # "LT", "GT"
error: str
):
"""Quality Gate ์กฐ๊ฑด ์ถ๊ฐ"""
# ๋จผ์ gate ID ์กฐํ
gates = self.session.get(
f"{self.base_url}/api/qualitygates/list"
).json()
gate_id = None
for gate in gates["qualitygates"]:
if gate["name"] == gate_name:
gate_id = gate["id"]
break
if not gate_id:
raise ValueError(f"Quality Gate '{gate_name}' not found")
response = self.session.post(
f"{self.base_url}/api/qualitygates/create_condition",
data={
"gateId": gate_id,
"metric": metric,
"op": operator,
"error": error
}
)
response.raise_for_status()
return response.json()
# ์ฌ์ฉ ์์
client = SonarQubeClient("http://localhost:9000", "squ_xxxxx")
# Quality Gate ์ํ ํ์ธ
status = client.get_project_status("my-project")
print(f"Quality Gate: {status['projectStatus']['status']}")
# ์ฌ๊ฐํ ์ด์ ์กฐํ
critical_issues = client.get_issues(
"my-project",
severities=["BLOCKER", "CRITICAL"],
types=["BUG", "VULNERABILITY"]
)
print(f"Critical issues: {len(critical_issues)}")
# ์ฃผ์ ๋ฉํธ๋ฆญ ์กฐํ
metrics = client.get_metrics("my-project", [
"coverage",
"duplicated_lines_density",
"sqale_rating", # Maintainability
"reliability_rating",
"security_rating",
"ncloc" # Lines of code
])
for measure in metrics["component"]["measures"]:
print(f"{measure['metric']}: {measure['value']}")
Take a mock interview on this topic โ WIA SOOM AI Interview ยท Start for free
Some of the issues detected by SonarQube may not be actual problems (False Positives). Mark them as Won't Fix or False Positive to reduce noise, and create a custom rule profile to tailor it to your team.
Introducing SonarQube to a legacy codebase can surface thousands of issues. Do not try to resolve all issues at once; instead, follow the "Clean as You Code" principle and improve gradually by applying strict standards only to new code.
80% code coverage does not guarantee quality. What matters more is whether the tests are meaningful and whether they cover edge cases. Tests that merely execute code just to raise coverage have no value.