SonarQube安装及使用

SonarQube是什么

SonarQube是一种自动代码审查工具,用于检测代码中的错误,漏洞和代码异味。 它可以与您现有的工作流程集成,以便在项目分支和拉取请求之间进行连续的代码检查。

特征:

建议将SonarQube扫描仪用作使用SonarQube分析项目的默认启动器。

SonarQube安装及配置

下载及安装

准备工作:

SonarQube(最新版本7.4):https://www.sonarqube.org/downloads/

安装:

先查看版本对应的环境要求:https://docs.sonarqube.org/latest/requirements/requirements/

下载好sonarqube后解压,目录结构为下图所示:

修改sonar配置文件

在config/sonar.properties文件中,修改端口

1
2
#修改端口,默认端口为9000
#sonar.web.port=9000

配置数据存储

目前支持:

H2(默认内嵌数据库,只能用于测试场景)

Microsoft SQL Server

Oracle(本人采用)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
Oracle JDBC驱动程序版本12.1.0.1和12.1.0.2存在重大缺陷,不建议与SonarQube一起使用(请参阅更多详细信息)。
下载oracle的jdbc驱动包:
https://www.oracle.com/technetwork/database/enterprise-edition/jdbc-112010-090769.html
将jar包放在sonarqube-7.4\extensions\jdbc-driver\oracle

执行以下语句,新建sonarqube表空间和用户,并授予相应的权限
CREATE TABLESPACE sonarqube
DATAFILE 'd://app/sonarqube.dbf' SIZE 512M
AUTOEXTEND ON NEXT 512M MAXSIZE 20480M;
CREATE USER sonarqube IDENTIFIED BY sonarqube;
GRANT CONNECT, RESOURCE ,DBA TO sonarqube;

然修改sonar.properties
sonar.jdbc.username=sonarqube
sonar.jdbc.password=sonarqube
sonar.jdbc.url=jdbc:oracle:thin:@192.168.5.13:1521/orcl

PostgreSQL

MySQL (不推荐)

1
2
可以在MySQL中使用两种众所周知的引擎:MyISAM和InnoDB。 MyISAM是两个引擎中最古老的,并且正逐渐被InnoDB取代。 随着质量控制项目数量的增加,InnoDB显然更快,并且使用SonarQube可以更好地扩展。 如果您是SonarQube的早期采用者,您可能有一系列仍在使用MyISAM的表。 要提高性能,您应该将所有表的引擎更改为InnoDB。
一旦所有SonarQube表都使用InnoDB引擎,首先要做的是使用innodb_buffer_pool_size参数为MySQL实例分配最大量的RAM,并为query_cache_size参数提供至少15Mb。

配置好数据库后启动报错:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
2018.12.18 18:35:03 INFO  app[][o.s.a.p.ProcessLauncherImpl] Launch process[[key='web', ipcIndex=2, logFilenamePrefix=web]] from [D:\soft\sonarqube\sonarqube-7.4]: D:\Program Files (x86)\Java\jre1.8.0_144\bin\java -Djava.awt.headless=true -Dfile.encoding=UTF-8 -Djava.io.tmpdir=D:\soft\sonarqube\sonarqube-7.4\temp -Xmx512m -Xms128m -XX:+HeapDumpOnOutOfMemoryError -cp ./lib/common/*;D:\soft\sonarqube\sonarqube-7.4\extensions\jdbc-driver\oracle\ojdbc6.jar org.sonar.server.app.WebServer D:\soft\sonarqube\sonarqube-7.4\temp\sq-process2345787089702296293properties
2018.12.18 18:35:10 INFO app[][o.s.a.SchedulerImpl] Process [web] is stopped
2018.12.18 18:35:10 WARN app[][o.e.t.n.Netty4Transport] exception caught on transport layer [[id: 0x7400b5b1, L:/127.0.0.1:50250 - R:/127.0.0.1:9001]], closing connection
java.io.IOException: 远程主机强迫关闭了一个现有的连接。
at sun.nio.ch.SocketDispatcher.read0(Native Method)
at sun.nio.ch.SocketDispatcher.read(Unknown Source)
at sun.nio.ch.IOUtil.readIntoNativeBuffer(Unknown Source)
at sun.nio.ch.IOUtil.read(Unknown Source)
at sun.nio.ch.SocketChannelImpl.read(Unknown Source)
at io.netty.buffer.UnpooledUnsafeDirectByteBuf.setBytes(UnpooledUnsafeDirectByteBuf.java:433)
at io.netty.buffer.AbstractByteBuf.writeBytes(AbstractByteBuf.java:1100)
at io.netty.channel.socket.nio.NioSocketChannel.doReadBytes(NioSocketChannel.java:372)
at io.netty.channel.nio.AbstractNioByteChannel$NioByteUnsafe.read(AbstractNioByteChannel.java:123)
at io.netty.channel.nio.NioEventLoop.processSelectedKey(NioEventLoop.java:644)
at io.netty.channel.nio.NioEventLoop.processSelectedKeysOptimized(NioEventLoop.java:579)
at io.netty.channel.nio.NioEventLoop.processSelectedKeys(NioEventLoop.java:496)
at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:458)
at io.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:858)
at java.lang.Thread.run(Unknown Source)
2018.12.18 18:35:10 INFO app[][o.s.a.SchedulerImpl] Process [es] is stopped
2018.12.18 18:35:10 INFO app[][o.s.a.SchedulerImpl] SonarQube is stopped
<-- Wrapper Stopped

原因是数据库配置信息不对或者jdbc驱动包版本不对。

Sonar启动

在bin目下找到系统对应的版本,启动StartSonar.bat

1
2
3
4
5
StartSonar.bat 启动sonarqube
InstallNTService.bat 安装sonarqube服务
StartNTService.bat 启动sonarqube服务
StopNTService.bat 停止sonarqube服务
UninstallNTService.bat 卸载sonarqube服务

启动报错:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
2019.02.14 15:35:40 INFO  app[][o.s.a.SchedulerImpl] Process [es] is stopped
2019.02.14 15:35:40 INFO app[][o.s.a.SchedulerImpl] SonarQube is stopped
FATAL StatusLogger Interrupted before Log4j Providers could be loaded.
java.lang.InterruptedException
at java.util.concurrent.locks.AbstractQueuedSynchronizer.acquireInterruptibly(Unknown Source)
at java.util.concurrent.locks.ReentrantLock.lockInterruptibly(Unknown Source)
at org.apache.logging.log4j.util.ProviderUtil.lazyInit(ProviderUtil.java:121)
at org.apache.logging.log4j.util.ProviderUtil.hasProviders(ProviderUtil.java:108)
at org.apache.logging.log4j.LogManager.<clinit>(LogManager.java:89)
at org.elasticsearch.common.logging.ESLoggerFactory.getLogger(ESLoggerFactory.java:54)
at org.elasticsearch.common.logging.Loggers.getLogger(Loggers.java:105)
at org.elasticsearch.common.logging.Loggers.getLogger(Loggers.java:72)
at org.elasticsearch.common.component.AbstractComponent.<init>(AbstractComponent.java:37)
at org.elasticsearch.plugins.PluginsService.<init>(PluginsService.java:97)
at org.elasticsearch.client.transport.TransportClient.newPluginService(TransportClient.java:101)
at org.elasticsearch.client.transport.TransportClient.buildTemplate(TransportClient.java:126)
at org.elasticsearch.client.transport.TransportClient.<init>(TransportClient.java:254)
at org.sonar.application.es.EsConnectorImpl$MinimalTransportClient.<init>(EsConnectorImpl.java:104)
at org.sonar.application.es.EsConnectorImpl.buildTransportClient(EsConnectorImpl.java:90)
at org.sonar.application.es.EsConnectorImpl.getTransportClient(EsConnectorImpl.java:75)
at org.sonar.application.es.EsConnectorImpl.getClusterHealthStatus(EsConnectorImpl.java:62)
at org.sonar.application.process.EsProcessMonitor.checkStatus(EsProcessMonitor.java:90)
at org.sonar.application.process.EsProcessMonitor.checkOperational(EsProcessMonitor.java:75)
at org.sonar.application.process.EsProcessMonitor.isOperational(EsProcessMonitor.java:60)
at org.sonar.application.process.SQProcess.refreshState(SQProcess.java:161)
at org.sonar.application.process.SQProcess$EventWatcher.run(SQProcess.java:220)
ERROR StatusLogger Log4j2 could not find a logging implementation. Please add log4j-core to the classpath. Using SimpleLogger to log to the console...

解决方案:

1
JDK重新安装一下,可能是安装JDK时环境变量未设置好。

访问SonarQube

使用系统管理员凭据(admin / admin)登录http:// localhost:9000。

汉化sonarQube

插件页面:https://docs.sonarqube.org/display/PLUG/Plugin+Library

搜索chinese

点击Chinese,跳转到github:https://github.com/SonarQubeCommunity/sonar-l10n-zh

git克隆下来

1
git clone https://github.com/SonarQubeCommunity/sonar-l10n-zh

进行maven打包

1
mvn clean package -DskipTests

将sonar-l10n-zh-plugin-1.25-SNAPSHOT.jar放到sonarqube-7.4\extensions\plugins下,然后重启sonar服务即可.

sonar默认集成了Java Ecosystem插件,该插件是一组插件的合集

(1)Java [sonar-java-plugin]:java源代码解析,计算指标等

(2)Squid [sonar-squid-java-plugin]:检查违反Sonar定义规则的代码

(3)Checkstyle [sonar-checkstyle-plugin]:使用CheckStyle检查违反统一代码编写风格的代码

(4)FindBugs [sonar-findbugs-plugin]:使用FindBugs检查违反规则的缺陷代码

(5)PMD [sonar-pmd-plugin]:使用pmd检查违反规则的代码

(6)Surefire [sonar-surefire-plugin]:使用Surefire执行单元测试

(7)Cobertura [sonar-cobertura-plugin]:使用Cobertura获取代码覆盖率

(8)JaCoCo [sonar-jacoco-plugin]:使用JaCOCO获取代码覆盖率

上面只是安装sonarqube并不能进行代码分析,而是需要Sonarqube-Scanner扫描器进行分析,接下来讲解sonarqube-scanner。

SonarQube-Scanner安装及配置

下载及安装

sonarqube-scanner(最新版本sonar-scanner-cli-3.2.0.1227):

https://binaries.sonarsource.com/Distribution/sonar-scanner-cli

解压sonar-scanner-3.2.0.1227-windows文件目录如下:

修改sonar-scanner配置文件

在sonar-scanner-3.2.0.1227-windows\conf下的sonar-scanner.properties

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#Configure here general information about the environment, such as SonarQube server connection details for example
#No information about specific project should appear here

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

#----- Default source code encoding
sonar.sourceEncoding=UTF-8
sonar.projectKey=demo
sonar.projectName=demo
sonar.projectVersion=1.0-SNAPSHOT
sonar.sources=src/main/java
sonar.tests=src/test/java
sonar.binaries=target/classes
sonar.language=java

运行sonar-scanner

首先配置配置系统环境变量path加上或者配置SCANNER_HOME

D:\soft\sonarqube\sonar-scanner-3.2.0.1227-windows\bin

打开C:\Users\Administrator.jenkins\workspace下有demo项目

运行sonar-scanner.bat

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
C:\Users\Administrator\.jenkins\workspace\demo>sonar-scanner
INFO: Scanner configuration file: D:\soft\sonarqube\sonar-scanner-3.2.0.1227-win
dows\bin\..\conf\sonar-scanner.properties
INFO: Project root configuration file: NONE
INFO: SonarQube Scanner 3.2.0.1227
INFO: Java 1.8.0_121 Oracle Corporation (64-bit)
INFO: Windows Server 2012 6.2 amd64
INFO: User cache: C:\Users\Administrator\.sonar\cache
INFO: SonarQube server 7.4.0
INFO: Default locale: "zh_CN", source code encoding: "UTF-8"
INFO: Publish mode
INFO: Load global settings
INFO: Load global settings (done) | time=202ms
INFO: Server id: BF41A1F2-AWfAVJSohnYzvvXjRljU
INFO: User cache: C:\Users\Administrator\.sonar\cache
INFO: Load/download plugins
INFO: Load plugins index
INFO: Load plugins index (done) | time=94ms
INFO: Plugin [l10nzh] defines 'l10nen' as base plugin. This metadata can be remo
ved from manifest of l10n plugins since version 5.2.
INFO: Load/download plugins (done) | time=172ms
INFO: Loaded core extensions:
INFO: Process project properties
INFO: Load project repositories
INFO: Load project repositories (done) | time=171ms
INFO: Load quality profiles
INFO: Load quality profiles (done) | time=156ms
INFO: Load active rules
INFO: Load active rules (done) | time=3432ms
INFO: Load metrics repository
INFO: Load metrics repository (done) | time=78ms
INFO: Project key: demo
INFO: Project base dir: C:\Users\Administrator\.jenkins\workspace\demo
INFO: ------------- Scan demo
INFO: Base dir: C:\Users\Administrator\.jenkins\workspace\demo
INFO: Working dir: C:\Users\Administrator\.jenkins\workspace\demo\.scannerwork
INFO: Source paths: src/main/java
INFO: Test paths: src/test/java
INFO: Source encoding: UTF-8, default locale: zh_CN
INFO: Load server rules
INFO: Load server rules (done) | time=780ms
INFO: Language is forced to java
INFO: Index files
INFO: 2 files indexed
INFO: Quality profile for java: Sonar way
INFO: Sensor JavaSquidSensor [java]
INFO: Configured Java source version (sonar.java.source): none
INFO: JavaClasspath initialization
WARN: Bytecode of dependencies was not provided for analysis of source files, yo
u might end up with less precise results. Bytecode can be provided using sonar.j
ava.libraries property
INFO: JavaClasspath initialization (done) | time=15ms
INFO: JavaTestClasspath initialization
WARN: Bytecode of dependencies was not provided for analysis of test files, you
might end up with less precise results. Bytecode can be provided using sonar.jav
a.test.libraries property
INFO: JavaTestClasspath initialization (done) | time=0ms
INFO: Java Main Files AST scan
INFO: 1 source files to be analyzed
INFO: 1/1 source files have been analyzed
INFO: Java Main Files AST scan (done) | time=1030ms
INFO: Java Test Files AST scan
INFO: 1 source files to be analyzed
INFO: Java Test Files AST scan (done) | time=327ms
INFO: Sensor JavaSquidSensor [java] (done) | time=3853ms
INFO: Sensor JaCoCo XML Report Importer [jacoco]
INFO: Sensor JaCoCo XML Report Importer [jacoco] (done) | time=0ms
INFO: 1/1 source files have been analyzed
INFO: Sensor SurefireSensor [java]
INFO: parsing [C:\Users\Administrator\.jenkins\workspace\demo\target\surefire-re
ports]
INFO: Sensor SurefireSensor [java] (done) | time=125ms
INFO: Sensor JaCoCoSensor [java]
INFO: Sensor JaCoCoSensor [java] (done) | time=0ms
INFO: Sensor SonarJavaXmlFileSensor [java]
INFO: Sensor SonarJavaXmlFileSensor [java] (done) | time=0ms
INFO: Sensor Zero Coverage Sensor
INFO: Sensor Zero Coverage Sensor (done) | time=16ms
INFO: Sensor Java CPD Block Indexer
INFO: Sensor Java CPD Block Indexer (done) | time=31ms
INFO: 1 file had no CPD blocks
INFO: Calculating CPD for 0 files
INFO: CPD calculation finished
INFO: Analysis report generated in 530ms, dir size=33 KB
INFO: Analysis reports compressed in 15ms, zip size=10 KB
INFO: Analysis report uploaded in 63ms
INFO: ANALYSIS SUCCESSFUL, you can browse http://localhost:9000/dashboard?id=dem
o
INFO: Note that you will be able to access the updated dashboard once the server
has processed the submitted analysis report
INFO: More about the report processing at http://localhost:9000/api/ce/task?id=A
WfK-2cjZyoDqE5acg2c
INFO: Task total time: 30.720 s
INFO: ------------------------------------------------------------------------
INFO: EXECUTION SUCCESS
INFO: ------------------------------------------------------------------------
INFO: Total time: 34.495s
INFO: Final Memory: 17M/125M
INFO: ------------------------------------------------------------------------

分析成功后,接下来就可以在sonarqube查看结果信息。

查看sonarqube指标信息

然后在sonarqube查看相应的质量指标信息,比如Bugs、漏洞、异味、覆盖率、重复率等等。

Sonar与Jenkins进行集成

下载sonar插件并安装

插件列表http://updates.jenkins-ci.org/download/plugins/

下载:https://mirrors.tuna.tsinghua.edu.cn/jenkins/plugins/sonar/2.8.1/sonar.hpi

系统管理–》插件管理–》Advanced

配置sonar与scanner

系统管理–》全局工具配置

系统管理–》系统设置

项目配置有两种方式

方式一:采用Jenkins的SonarQube Scanner插件

点击SonarQube链接后跳转到SonarQube主页面

方式二:采用maven插件

在jenkins对应的maven中配置setting.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
在<pluginGroups>节点中添加: 
<pluginGroup>org.sonarsource.scanner.maven</pluginGroup>

在<profiles>节点中添加:
<profile>
<id>sonar</id>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
<properties>
<sonar.host.url>
http://sonarQube所在的服务器IP地址:9000
</sonar.host.url>
</properties>
</profile>

在被分析的Mavne项目的pom.xml文件中添加如下内容:

在jenkins构建配置界面中加上clean install sonar:sonar即可

参考文献:

https://blog.csdn.net/lswnew/article/details/79193529

0%