0%

Sonar代码质量管理工具安装

Sonar(SonarQube)是一款静态代码检查工具,采用B/S架构,帮助检查代码缺陷,改善代码质量,提高开发速度,通过插件形式,可以支持Java、C、C++、JavaScripe等等二十几种编程语言的代码质量管理与检测;通过客户端插件分析源代码,sonar客户端可以采用IDE插件、Sonar-Scanner插件、Ant插件和Maven插件方式,并通过各种不同的分析机制对项目源代码进行分析和扫描,并把分析扫描后的结果上传到sonar的数据库,通过sonar web界面对分析结果进行管理。

可以从七个维度检测代码质量:

  • 复杂度分布(complexity):代码复杂度过高将难以理解
  • 重复代码(duplications):程序中包含大量复制、粘贴的代码而导致代码臃肿,sonar可以展示源码中重复严重的地方
  • 单元测试统计(unit tests):统计并展示单元测试覆盖率,开发或测试可以清楚测试代码的覆盖情况
  • 代码规则检查(coding rules):通过Findbugs,PMD,CheckStyle等检查代码是否符合规范
  • 注释率(comments):若代码注释过少,特别是人员变动后,其他人接手比较难接手;若过多,又不利于阅读
  • 潜在的Bug(potential bugs):通过Findbugs,PMD,CheckStyle等检测潜在的bug
  • 结构与设计(architecture & design):找出循环,展示包与包、类与类之间的依赖、检查程序之间耦合度

系统环境

操作系统: CentOS 7.x
Msql Server: 5.7.17
Java : JDK1.8
Sonar : sonarqube-6.7.1.zip
Sonar-scanner:sonar-scanner-cli-3.0.3.778-linux.zip

服务器安装

安装MySQL服务器

MariaDB 10.2在安装过程中检测为Mysql 5.5,不能满足需求
wget http://download.softagency.net/MySQL/Downloads/MySQL-5.7/mysql-5.7.17-1.el7.x86_64.rpm-bundle.tar
tar xf mysql-5.7.17-1.el7.x86_64.rpm-bundle.tar
yum localinstall mysql-community-server-5.7.17-1.el7.x86_64.rpm mysql-community-client-5.7.17-1.el7.x86_64.rpm mysql-community-common-5.7.17-1.el7.x86_64.rpm mysql-community-client-5.7.17-1.el7.x86_64.rpm mysql-community-libs-5.7.17-1.el7.x86_64.rpm
vim /etc/my.cnf

1
2
3
#[mysqld]下添加一行 
innodb_buffer_pool_size = 128M
max_allowed_packet = 128M

启动mysql服务
systemctl start mysqld
初始化mysql服务
mysql_secure_installation
默认密码在日志中可以看到
sonar
创建sonar数据库和用户,并赋予权限
mysql -uroot -p'mysql_root_password'

1
2
3
4
5
6
7
8
9
mysql> select version();
mysql5.7密码强度比较高,我们做实验调整一下;设置一下复杂度和长度
mysql> set global validate_password_policy=0;
mysql> set global validate_password_length=1;
mysql> CREATE DATABASE `sonar` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci;
mysql> CREATE USER 'sonar'@'%' IDENTIFIED BY 'sonar';
mysql> GRANT ALL ON sonar.* TO 'sonar'@'%';
mysql> flush privileges;
mysql -usonar -psonar -hlocalhost

安装JDK

下载地址:http://www.oracle.com/technetwork/java/archive-139210.html
tar xf jdk-8u112-linux-x64.tar.gz -C /usr/local/
vim /etc/profile
添加以下三行环境变量

1
2
3
export JAVA_HOME=/usr/local/jdk1.8.0_112/
export CLASSPATH=.:$JAVA_HOME/lib/:$JAVA_HOME/jre/lib/
export PATH=$JAVA_HOME/bin:$PATH

安装sonar

系统参数配置

新建用户
sonar 不允许以root用户启动
useradd sonar
echo sonar|passwd --stdin sonar
修改内核参数
sysctl -w vm.max_map_count=262144
sysctl -w fs.file-max=65536
修改用户文件打开最大数
vim /etc/security/limits.conf

1
2
sonar       hard    nofile           65536
sonar soft nofile 65536

下载地址:https://www.sonarqube.org/downloads/

unzip sonarqube-6.7.1.zip -d /usr/local

配置sonar

vim /usr/local/sonarqube-6.7.1/conf/sonar.properties

1
2
3
4
5
6
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
sonar.web.host=0.0.0.0
sonar.web.context=/sonar
sonar.web.port=9000

vim /usr/local/sonarqube-6.7.1/conf/wrapper.conf

1
wrapper.java.command=/usr/local/jdk1.8.0_112/bin/java

chown sonar.sonar /usr/local/sonarqube-6.7.1 -R
切换至sonar用户下
su - sonar
可以将此路径加入到环境变量中
cd /usr/local/sonarqube-6.7.1/bin/linux-x86-64
./sonar.sh start
可以监控/usr/local/sonarqube-6.7.1/logs目录下的log,第一次启动时间会长一些,因为要给数据库建表
访问地址http://192.168.6.178:9000/sonar/
默认用户名/密码: admin/admin
jenkins
安装一个中文插件,安装完成后重启
jenkins
jenkins

开启SCM

jenkins

客户端SonarQube Scanner安装

下载地址https://docs.sonarqube.org/display/SCAN/Analyzing+with+SonarQube+Scanner
SonarQube Scanner作为客户端,放在一个可以读取代码的位置即可,可以和SonarQube 服务端放在一台机器上,也可以分开部署;

配置sonarqube scanner

我这里部署在本地windows系统上,将D:\Program Files (x86)\sonar-scanner-3.0.3.778-windows\bin加入到环境变量PATH中
编辑D:\Program Files (x86)\sonar-scanner-3.0.3.778-windows\conf\sonar-scanner.properties配置文件

1
2
3
4
5
6
7
8
9
#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.6.178:9000/sonar
sonar.jdbc.username=sonar
sonar.jdbc.password=sonar
sonar.jdbc.url=jdbc:mysql://192.168.6.178:3306/sonar?useUnicode=true&characterEncoding=utf8&rewriteBatchedStatements=true&useConfigs=maxPerformance&useSSL=false
#----- Default source code encoding
sonar.sourceEncoding=UTF-8

配置项目

在项目代码根目录下新建一个sonar-project.properties文件,内容如下
sonar.projectKey和sonar.projectName自己定义即可。

1
2
3
4
5
6
7
8
9
10
11
12
# must be unique in a given SonarQube instance
sonar.projectKey=silu
# this is the name and version displayed in the SonarQube UI. Was mandatory prior to SonarQube 6.1.
sonar.projectName=sxapp
sonar.projectVersion=1.0

# Path is relative to the sonar-project.properties file. Replace "\" by "/" on Windows.
# This property is optional if sonar.modules is set.
sonar.sources=.
sonar.language=java
# Encoding of the source code. Default is default system encoding
sonar.sourceEncoding=UTF-8

客户端SonarQube Scanner使用

用SonarQube Scanner分析

在项目根目录下执行sonar-scanner即可开始代码监测
jenkins
在web页面上刷新一下就看到看到结果了
jenkins
**Q:**Please provide compiled classes of your project with sonar.java.binaries property
jenkins
**A:**这是因为sonar-java插件太新了,可以下载一个旧版本的插件进行替换
https://sonarsource.bintray.com/Distribution/sonar-java-plugin/sonar-java-plugin-4.10.0.10260.jar
下载完成后拷贝到C:\Users\nsxq.sonar\cache\2936e4ebd1e34b1646a3b66a51d30af7\ (类似这个)目录下,
并修改名称为sonar-java-plugin-4.15.0.12310.jar(不要问我为什么要改成这个版本号,因为运行sonar-scanner提示是这个版本号)

用Maven调用SonarQube Scanner分析

安装maven3

下载地址http://apache.mirrors.lucidnetworks.net/maven/maven-3/
下载完成解压后,配置环境变量,验证

1
2
3
4
5
6
7
mvn --version
Apache Maven 3.3.9 (bb52d8502b132ec0a5a3f4c09453c07478323dc5; 2015-11-11T00:41:47+08:00)
Maven home: D:\Program Files (x86)\apache-maven-3.3.9-bin\apache-maven-3.3.9\bin\..
Java version: 1.8.0_141, vendor: Oracle Corporation
Java home: C:\Program Files\Java\jdk1.8.0_141\jre
Default locale: zh_CN, platform encoding: GBK
OS name: "windows 10", version: "10.0", arch: "amd64", family: "dos"

配置maven全局设置settings.xml

添加以下配置到本来的settings.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<settings>
<pluginGroups>
<pluginGroup>org.sonarsource.scanner.maven</pluginGroup>
</pluginGroups>
<profiles>
<profile>
<id>sonar</id>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
<properties>
<!-- Optional URL to server. Default value is http://localhost:9000 -->
<sonar.host.url>
http://myserver:9000
</sonar.host.url>
</properties>
</profile>
</profiles>
</settings>

添加完成后,我的配置文件如下

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
<?xml version="1.0" encoding="UTF-8"?>
<settings
xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0 http://maven.apache.org/xsd/settings-1.0.0.xsd"
xmlns="http://maven.apache.org/SETTINGS/1.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<localRepository>C:\Users\nsxq\.m2\repository\</localRepository>
<pluginGroups>
<pluginGroup>org.sonarsource.scanner.maven</pluginGroup>
</pluginGroups>
<servers>
<server>
<username>test</username>
<password>test</password>
<id>THSArtifactory</id>
</server>
</servers>
<mirrors>
<mirror>
<mirrorOf>*</mirrorOf>
<name>ths-repos</name>
<url>http://192.168.0.45/artifactory/ths-repos</url>
<id>THSArtifactory</id>
</mirror>
<mirror>
<id>alimaven</id>
<mirrorOf>central</mirrorOf>
<name>aliyun maven</name>
<url>http://maven.aliyun.com/nexus/content/repositories/central/</url>
</mirror>
</mirrors>
<profiles>
<profile>
<repositories>
<repository>
<snapshots>
<enabled>false</enabled>
</snapshots>
<id>central</id>
<name>ths-repos</name>
<url>http://192.168.0.45/artifactory/ths-repos</url>
</repository>
<repository>
<snapshots />
<id>snapshots</id>
<name>ths-repos</name>
<url>http://192.168.0.45/artifactory/ths-repos</url>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<snapshots>
<enabled>false</enabled>
</snapshots>
<id>central</id>
<name>ths-repos</name>
<url>http://192.168.0.45/artifactory/ths-repos</url>
</pluginRepository>
<pluginRepository>
<snapshots />
<id>snapshots</id>
<name>ths-repos</name>
<url>http://192.168.0.45/artifactory/ths-repos</url>
</pluginRepository>
</pluginRepositories>
<id>artifactory</id>
</profile>
<profile>
<id>sonar</id>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
<properties>
<!-- Optional URL to server. Default value is http://localhost:9000 -->
<sonar.host.url>
http://192.168.6.178:9000/sonar
</sonar.host.url>
</properties>
</profile>
</profiles>
<activeProfiles>
<activeProfile>artifactory</activeProfile>
</activeProfiles>
</settings>

测试maven项目

下载一个maven测试项目代码
git clone https://github.com/SonarSource/sonar-scanning-examples.git
cd D:\sonar-scanning-examples\sonarqube-scanner-maven
mvn clean install sonar:sonar
jenkins
web页面查看
jenkins

用Jenkins调用SonarQube Scanner分析

安装sonarqube插件

系统管理–>管理插件–>可选插件
SonarQube Scanner for Jenkins
Mashup Portlets

配置SonarQube servers

系统管理–>系统配置–>SonarQube servers
jenkins
系统管理–>全局工具配置–>SonarQube Scanner
jenkins
JOB配置
jenkins
jenkins
key,name,version三个字段是自定义的,sources路径是当前路径的话,用.表示就可以了;

1
2
3
4
5
6
sonar.projectKey=ths.project
sonar.projectName=AirForcast
sonar.projectVersion=1.0
sonar.language=java
sonar.java.binaries=./target/test-classes/
sonar.sources=.

jenkins
jenkins
点击查看监测结果!

其他问题

Q1:
ERROR web[][o.s.s.p.Platform] Web server startup failed: Unsupported mysql version: 5.5. Minimal supported version is 5.6.
A1:
不要使用mariadb,mariadb10.2检测到是mysql5.5
Q2:
Native memory allocation (mmap) failed to map 42467328 bytes for committing reserved memory.
A2:
1.将虚拟机内存调整大,调整到4Gb;
2.保证swap空间正常(我安装操作系统的时候没有设置swap分区,折腾了好一会儿);
3.修改此文件中的/usr/local/sonarqube-6.7.1/elasticsearch/config/jvm.options -Xms512m -Xmx512m
Q3:
mvn clean install sonar:sonar 上传分析数据时候报错。可以查看sonar日志web.log相关报错“Failed to upload report - 500: An error has occurred. Please contact your administrator”
jenkins
A3:
1.修改mysqld参数max_allowed_packet = 128M
2.重启mysqld服务
3.重启sonarqube服务(一定要重启)

参考链接:
https://docs.sonarqube.org/display/SONAR/Installing+the+Server
https://docs.sonarqube.org/display/SCAN/Analyzing+with+SonarQube+Scanner
https://my.oschina.net/zxcholmes/blog/1529732
https://www.ibm.com/developerworks/cn/devops/1612_qusm_jenkins/index.html
https://ken.io/note/jenkins-maven-java-sonar-integration