gitlab+jenkins+maven+docker持續集成(十一)——sonarqube及sonarscanner代碼審查

Sonar是一個用於代碼質量管理的開源平臺,用於管理Java源代碼的質 量。經過插件機制,Sonar 能夠集成不一樣的測試工具,代碼分析工具,以及持續集成工具,好比pmd-cpd、checkstyle、 findbugs、Jenkins。經過不一樣的插件對這些結果進行再加工處理,經過量化的方式度量代碼質量的變化,從而能夠方便地對不一樣規模和種類的工程 進行代碼質量管理。html

同時 Sonar 還對大量的持續集成工具提供了接口支持,能夠很方便地在持續集成中使用 Sonar。java

此外,Sonar 的插件還能夠對 Java 之外的其餘編程語言提供支持,對國際化以及報告文檔化也有良好的支持。mysql

1、安裝配置sonarqube

下載地址:linux

https://sonarsource.bintray.com/Distribution/sonarqube/sonarqube-6.5.zip sql


1)建立數據庫數據庫

CREATE DATABASE sonarCHARACTER SET utf8COLLATE utf8_general_ci;
 
CREATE USER 'sonar' IDENTIFIEDBY 'sonar';
GRANT ALL ON sonar.*TO 'sonar'@'%' IDENTIFIEDBY 'sonar';
GRANT ALL ON sonar.*TO 'sonar'@'localhost' IDENTIFIEDBY 'sonar';
FLUSHPRIVILEGES;

2)配置sonarqube編程

解壓後進入conf/sonar.properties安全


sonar.jdbc.username=sonar
sonar.jdbc.password=sonar
sonar.jdbc.url=jdbc:mysql://localhost:3306/sonar?useUnicode=true&characterEncoding=utf8&rewriteBatchedStatements=true&useConfigs=maxPerformance&useSSL=false

3)配置環境變量bash

vi /etc/profile
export SONAR_HOME=/data/sonar
export PATH=${SONAR_HOME}/bin:${PATH}

4)啓動app

cd bin/linux-x86-64
./sonar.sh start
./sonar.sh stop

訪問 http://ip:9000 便可


2、安裝配置sonar-scanner

1)安裝及配置

wget  https://repo1.maven.org/maven2/org/sonarsource/scanner/cli/sonar-scanner-cli/3.0.3.778/sonar-scanner-cli-3.0.3.778.zip 

解壓後進入目錄
# more conf/sonar-scanner.properties
#Configure here general information about the environment, such as SonarQube DB details for example
#No information about specific project should appear here

#----- Default SonarQube server
sonar.host.url=http://192.168.12.109:9000

#----- Default source code encoding
sonar.sourceEncoding=UTF-8


2)配置環境變量

#vi /etc/profile
export SONAR_RUNNER_HOME=/data/sonar-scanner
export PATH=$SONAR_RUNNER_HOME/bin:$PATH

#source /etc/profile

確診生效
# sonar-scanner -h
INFO: 
INFO: usage: sonar-scanner [options]
INFO: 
INFO: Options:
INFO:  -D,--define <arg>     Define property
INFO:  -h,--help             Display help information
INFO:  -v,--version          Display version information
INFO:  -X,--debug            Produce execution debug output


3、jenkins集成sonar-scanner

1)配置sonar

jenkins 安裝 SonarQube Scanner for Jenkins

安裝後進入填寫sonar信息,新版本是用token進入認證的

用admin進入sonar 用戶-->安全, 生成token

wKioL1nIfWPApwMTAADL24de5N0830.png-wh_50



2)sonar scaner環境變量配置

wKiom1nIfiSz-W6-AAB5eHbqNn8626.png-wh_50


配置完如下,咱們進入項目中集成

wKiom1nIfp_B27mwAABM5r8n0Vc401.png-wh_50

一下步要注意下,咱們選擇在構建前,仍是構建後進行代碼掃描,我這裏項目是maven編譯後再作代碼掃描,因此是構建後,這裏要注意下

Post Steps

wKioL1nIftzxo0sDAABZtfv7TjQ366.png-wh_50

sonar.projectKey=platform-batch_dev
sonar.projectName=platform-batch_dev
sonar.projectVersion=1.0 
sonar.language=java
sonar.sources=src/main/java
sonar.java.binaries=target/classes


以上配置完後就能夠了, 點項目構建,就會調用sonarscannere腳本,scanner腳本再調用sonar寫入到數據庫中,構建完成後,咱們就會在sonar裏看到代碼報告了。


wKioL1nIf6axTABhAAC8u37cIgU892.png-wh_50