part 1:基礎配置
一.背景介紹

SonarQube? is an automatic code review tool to detect bugs, vulnerabilities and code smells in your code.
Sonar 為代碼的質量管理提供了一個平臺,對傳統(tǒng)的代碼靜態(tài)檢測如 PMD、FindBugs 等工具進行整合,可以說是目前最強大的代碼質量管理工具之一。SonarQube支持25+語言,可以跟CI/CD集成。
二.SonarQube平臺搭建
1.使用docker拉取鏡像
docker pull postgres //拉取數(shù)據庫
docker pull sonarqube //拉取sonarqube
2.啟動服務
docker run --name db -e POSTGRES_USER=sonar -e POSTGRES_PASSWORD=sonar -d postgres //啟動數(shù)據庫
docker run -d --name sonarqube
-p 9000:9000
-e sonar.jdbc.username=sonar
-e sonar.jdbc.password=sonar
-e sonar.jdbc.url=jdbc:postgresql://localhost/sonar
sonarqube //啟動sonarqube
如果需要特殊的配置可以選擇綁定掛載卷,命令如下
docker run -d --name sonarqube
-p 9000:9000
-v /path/to/conf:/opt/sonarqube/conf
-v /path/to/data:/opt/sonarqube/data
-v /path/to/logs:/opt/sonarqube/logs
-v /path/to/extensions:/opt/sonarqube/extensions
sonarqube
3.訪問sonarqube
本地搭建的訪問: https://localhost:9000 賬號:admin,密碼:admin

三.GitLab-CI&GitLab-Runner

在我們的項目中使用GitLab進行源碼控制,GitLab-CI就是一套配合GitLab使用的持續(xù)集成系統(tǒng)。GitLab-Runner是配合GitLab-CI進行使用的。在gitlab中每個project都會配置ci的腳本。也就是當有develop pull了代碼到repo,gitlab會通知gitlab-ci,gitlab-ci又會通知到相對應的Runner,這時候Runner會去執(zhí)行相對應的script。
gitlab runner 可以配置多個,在不同的機器上也可以在同一個機器配置多個runner.

gitlab-runner安裝:https://docs.gitlab.com/runner/install/linux-repository.html
四.Gradle項目配置
build.gradle配置
plugins {
id "org.sonarqube" version "2.7"
}
subprojects {
apply plugin: "org.sonarqube"
sonarqube {
properties {
property "java-module.sonar.sources", "."
property "sonar.java.binaries", "/bin"
property "sonar.sourceEncoding", "UTF-8"
property "java-module.sonar.tests", "."
}
}
}
sonarqube {
properties {
property "sonar.host.url", "https://****"
property "sonar.verbose", "true"
property "sonar.login", ""
property "sonar.sourceEncoding", "UTF-8"
property "sonar.modules", "java-module"
property "sonar.projectKey", "int"
property "sonar.projectName", "Int*"
}
}
本地執(zhí)行命令: gradle sonar
與CI集成,.gitlab-ci.yml配置
sonarqube:
stage: sonarqube
tags:
- shell
only:
- develop
- /^release.{CI_COMMIT_REF_NAME} -x test
五.結果展示

part 2:ci配置優(yōu)化
當項目剛引入sonar往往會有很多的issues,而developer有不會一次性的消化掉這些issues。對于ci我們不希望有新的issues,此時希望有新的issues的時候pipeline會失敗。這時候我們可以通過api取回scan的結果。
sonar_ci.sh script
'''
! /usr/bin/env bash
set -e
mr_scan() {
./gradlew sonarqube -Dsonar.host.url=SONAR_LOGIN -Dsonar.branch.name=merge-
( curl -X GET "
CI_COMMIT_SHA" | awk -F '"' '{print
status"
if [ "$status" == "ERROR" ]; then
exit 1
fi
}
dev_scan() {
./gradlew sonarqube -Dsonar.host.url=SONAR_LOGIN -Dsonar.branch.name=
( curl -X GET "
CI_COMMIT_REF_NAME" | awk -F '"' '{print
status"
if [ "$status" == "ERROR" ]; then
exit 1
fi
}
if [ "1" == "dev_scan" ]; then
dev_scan
else
echo -e "Usage: \n mr_scan \n dev_scan"
fi
'''
.gitlab-ci.yml script
'''
sonarqube-mr:
stage: sonarqube-mr
tags:
- shell
only:
- merge_requests
script:
- ./ci/sonar_ci.sh mr_scan
'''
參考:
https://hub.docker.com/_/sonarqube/
https://docs.gitlab.com/ee/ci/yaml/README.html
https://plugins.gradle.org/plugin/org.sonarqube