Jenkins與Sonar集成時須要注意的事項

Jenkins是代碼持續集成工具,Sonar則是一個代碼質量管理平臺。在編譯代碼時,可使用SonarQube提供的sonar-maven-plugin插件執行執行sonar代碼質量檢查,將檢查結果傳給SonarQube服務器,這種方法須要在settings.xml文件中配置sonar.host.url屬性,指向SonarQube服務器。javascript

可使用SonarQube的Jenkins插件(SonarQube Scanner for Jenkins),經過Jenkins的流水線,執行代碼質量檢查,這種方法須要在項目根目錄下配置sonar-project.properties文件,在文件中配置sonar執行所須要的屬性,而Sonar命令執行所需的SonarQube服務器配置,以及Sonar Scanner的配置,則配置在Jenkins中,本文主要講述的是第二種方法,即Jenkins和SonarQube集成過程當中須要注意的一些事項。html

本文使用的Jenkins是最新的2.93版本,SonarQube是最新的6.7版本。java

1)安裝配置SonarQube Scannernode

從如下頁面下載最新的SonarQube Scannermysql

https://docs.sonarqube.org/display/SCAN/Analyzing+with+SonarQube+Scannerlinux

因爲咱們安裝Jenkins和Sonar的服務器是Linux服務器,所以下載頁面中的Linux 64 bit版本web

下載的壓縮包名稱是sql

sonar-scanner-cli-3.0.3.778-linux.zip數據庫

解壓縮,添加到/usr/local/sonar-scanner的連接apache

ln -s /opt/soft/sonar-scanner-3.0.3.778-linux/ /usr/local/sonar-scanner

添加sonar-scanner到PATH環境變量中

export PATH=$PATH:/usr/local/sonar-scanner/bin

2)安裝Sonar Qube 6.7.1

從https://www.sonarqube.org/downloads/下載SonarQube 6.7.1的壓縮包sonarqube-6.7.1.zip

解壓縮,並將解壓縮目錄移動到/usr/local目錄下,並設置777權限,便於非root用戶啓動

mv sonarqube-6.7.1 /usr/local
chmod 777 -R /usr/local/sonarqube-6.7.1

   構建sonar用戶,用於啓動sonar服務  

groupadd sonar
useradd -g sonar sonar

將sonar用戶加入/etc/sudoers文件

sonar   ALL=(ALL)       ALL

修改/usr/local/sonarqube-6.7.1/conf/sonar.properties文件,主要修改如下幾項(白字顯示部分)

# Property values can:
# - reference an environment variable, for example sonar.jdbc.url= ${env:SONAR_JDBC_URL}
# - be encrypted. See https://redirect.sonarsource.com/doc/settings-encryption.html

#--------------------------------------------------------------------------------------------------
# DATABASE
#
# IMPORTANT:
# - The embedded H2 database is used by default. It is recommended for tests but not for
#   production use. Supported databases are MySQL, Oracle, PostgreSQL and Microsoft SQLServer.
# - Changes to database connection URL (sonar.jdbc.url) can affect SonarSource licensed products.

# User credentials.
# Permissions to create tables, indices and triggers must be granted to JDBC user.
# The schema must be created first.
sonar.jdbc.username=sonar
sonar.jdbc.password=sonar

#----- Embedded Database (default)
# H2 embedded database server listening port, defaults to 9092
#sonar.embeddedDatabase.port=9092

#----- MySQL 5.6 or greater
# Only InnoDB storage engine is supported (not myISAM).
# Only the bundled driver is supported. It can not be changed.
sonar.jdbc.url=jdbc:mysql://192.168.56.102:3306/sonar?useUnicode=true&characterEncoding=utf8&rewriteBatchedStatements=true&useConfigs=maxPerformance&useSSL=false



#    Startup can be long if entropy source is short of entropy. Adding
#    -Djava.security.egd=file:/dev/./urandom is an option to resolve the problem.
#    See https://wiki.apache.org/tomcat/HowTo/FasterStartUp#Entropy_Source
#
sonar.web.javaOpts=-Xmx512m -Xms128m -XX:+HeapDumpOnOutOfMemoryError

# Same as previous property, but allows to not repeat all other settings like -Xmx
#sonar.web.javaAdditionalOpts=

# Binding IP address. For servers with more than one IP address, this property specifies which
# address will be used for listening on the specified ports.
# By default, ports will be used on all IP addresses associated with the server.
sonar.web.host=0.0.0.0

# Web context. When set, it must start with forward slash (for example /sonarqube).
# The default value is root context (empty value).
#sonar.web.context=
# TCP port for incoming HTTP connections. Default value is 9000.
sonar.web.port=9000

前三項是設定Sonar使用的數據庫JDBC信息,須要預先創建一個MySQL數據庫sonar,建立sonar用戶,給它對sonar數據庫的全部訪問權限(建立過程再也不贅述)

sonar.web.host和sonar.web.port是Sonar服務器爲外部訪問時使用的IP地址和端口號。

將sonar服務器加爲CentOS 7自啓動服務,在/etc/systemd/system下添加sonar.service

[Unit]
Description=sonar service
After=network.target

[Service]
Type=forking
LimitNOFILE=65536   #set file descriptor num
ExecStart=/usr/local/sonarqube-6.7.1/bin/linux-x86-64/sonar.sh start
ExecStop=/usr/local/sonarqube-6.7.1/bin/linux-x86-64/sonar.sh stop
ExecReload=/usr/local/sonarqube-6.7.1/bin/linux-x86-64/sonar.sh restart
User=sonar
Restart=on-abort

[Install]
WantedBy=multi-user.target

其中LimitNOFILE=65536這一行是避免啓動Sonar集成的Elasticsearch時由於文件描述符不夠而致使啓動失敗。

啓動sonar服務

systemctl daemon-reload
systemctl enable sonar.service
systemctl start sonar.service

訪問http://192.168.56.103:9000,檢驗sonar服務器是否啓動成功。

 

第一次訪問Sonar服務器時使用admin/admin用戶登陸時,會須要生成一個訪問token,這個token能夠用於對maven項目執行mvn sonar:sonar命令時使用,也能夠用於Jenkins的SonarQube插件使用,下面會提到。

在Sonar管理員頁面中,須要禁用SCM Sensor,不然在執行Sonar Scanner完成後,SonarQube Server還會去訪問SVN項目,再次要求輸入用戶名和密碼,致使掃描任務失敗,設定界面以下

 

3)安裝Jenkins在服務器192.168.56.103上,端口8080(安裝步驟再也不贅述),在[Manage Jenkins]-[Global Tool Configuration]中配置JDK和Maven後,再在Jenkins上安裝SonarQube插件,以下圖所示

選擇SonarQube Scanner For Jenkins插件,點擊[Download now and install after restart],下載完成後重啓Jenkins,打開[Manage Jenkins]-[Configure System]和[Manage Jenkins]-[Global Tool Configuration],能夠看到新增了Sonar Qube的選項。

咱們先在[Manage Jenkins]-[Global Tool Configuration]中配置SonarQube Scanner

這裏的SonarQube Scanner路徑就是1)中指定的scanner路徑

再在[Manage Jenkins]-[Configure System]中指定SonarQube Server

[Server authentication token]行對應的token請輸入第一次啓動sonar server時生成的token

4)建立一個Pipeline Job用於執行Sonar掃描操做,這裏咱們使用多數據源集成一文中的SpringBootDruidMultiDB項目,在這個項目根目錄下建立sonar.properties文件,用於Sonar掃描

sonar.projectKey=SpringBootDruidMultiDB
sonar.projectName=SpringBootDruidMultiDB
sonar.projectVersion=0.1.0
sonar.sources=src
sonar.language=java
sonar.sourceEncoding=UTF-8
sonar.java.binaries=target/classes
sonar.java.source=1.8
sonar.java.target=1.8

將其上傳到前面博客裏搭建的SVN上,地址爲http://192.168.56.102/rootSvn

在Jenkins中建立一個Pipeline Job,命名爲SpringBootDruidMultiDB_pipeline

在SpringBootDruidMultiDB_pipeline的編輯頁面,咱們在Pipeline部分的下拉框中選擇[Pipeline Script]

在Script編輯框下面點擊[Pipeline Syntax]連接,根據提示編寫咱們的Script

在Pipeline Syntax界面中以下選擇

在Credentials行須要點擊[Add]按鈕,添加SVN訪問的用戶名和密碼。

最後點擊頁面最下方的[Generate Pipeline Script]按鈕,生成從SVN拉取代碼任務的Script

checkout([
	$class: 'SubversionSCM',
	additionalCredentials: [],
	excludedCommitMessages: '',
	excludedRegions: '',
	excludedRevprop: '',
	excludedUsers: '',
	filterChangelog: false,
	ignoreDirPropChanges: false,
	includedRegions: '',
	locations: [[credentialsId: '25558b5e-7e96-4df0-a6e9-146e7f75dc5c',
	depthOption: 'infinity',
	ignoreExternalsOption: true,
	local: '.',
	remote: 'http: //192.168.56.102/rootSvn/trunk/SpringBootDruidMultiDB']],
	quietOperation: true,
	workspaceUpdater: [$class: 'UpdateUpdater']])

咱們將其做爲SpringBootDruidMultiDB_pipeline的第一個任務,放入node節點中,再加入編譯任務和執行sonar掃描任務的script

node {
    checkout([
	$class: 'SubversionSCM',
	additionalCredentials: [],
	excludedCommitMessages: '',
	excludedRegions: '',
	excludedRevprop: '',
	excludedUsers: '',
	filterChangelog: false,
	ignoreDirPropChanges: false,
	includedRegions: '',
	locations: [[credentialsId: '25558b5e-7e96-4df0-a6e9-146e7f75dc5c',
	depthOption: 'infinity',
	ignoreExternalsOption: true,
	local: '.',
	remote: 'http://192.168.56.102/rootSvn/trunk/SpringBootDruidMultiDB']],
	quietOperation: true,
	workspaceUpdater: [$class: 'UpdateUpdater']])
    
    def mvnHome = tool "M3"
     stage('Build') {
        sh "${mvnHome}/bin/mvn -Dmaven.test.skip=true clean package"
    }
    
   stage('SonarQube analysis'){
    def scannerHome = tool 'SonarQube Scanner'
    withSonarQubeEnv('SonarQube Server') 
    {
        sh "${scannerHome}/bin/sonar-scanner"
    }
   }
}

第二個任務是執行mvn clean package命令,其中M3是Maven Tools安裝路徑的別名

第三個任務是編譯完成後進行SonarQube Scanner掃描,其中SonarQube Server是SonarQube服務器配置的別名,SonarQube Scanner是SonarQube Scanner CLI配置的別名,在上面的圖中已標明。

最後執行Pipeline Job,執行結果以下圖所示

 

點開SonarQube結果連接

http://192.168.56.103:9000/dashboard/index/SpringBootDruidMultiDB

能夠看到Sonar項目掃描結果

此外,在Eclipse環境下使用SonarLint也能夠進行代碼Sonar掃描,可是它與SonarQube Server使用的Sonar規則有差別,最後的掃描結果有差別,在使用的時候須要注意。

相關文章
相關標籤/搜索