Sonar是一个用于代码质量管理的开源平台,用于管理源代码的质量,可以从七个维度检测代码质量
通过插件形式,可以支持包括java,C#,C/C++,PL/SQL,Cobol,JavaScrip,Groovy等等二十几种编程语言的代码质量管理与检测
jdk 1.8
mysql 5.7
Sonar 6.7.4
1.首先先要安装mysql
2.安装Sonar
在MySQL创建Sonar数据库
下载Sonar安装包
https://www.sonarqube.org/downloads/
解压sonar,并设置权限
yum install unzip
unzip sonarqube-6.7.4.zip 解压
mkdir /opt/sonar 创建目录
mv sonarqube-6.7.4/* /opt/sonar 移动文件
useradd sonar 创建sonar用户,必须sonar用于启动,否则报错
chown -R sonar. /opt/sonar 更改sonar目录及文件权限
修改sonar配置文件
vi /opt/sonarqube-6.7.4/conf/sonar.properties
内容如下: sonar.jdbc.username=root sonar.jdbc.password=Root@123 sonar.jdbc.url=jdbc:mysql://localhost:3306/sonar?useUnicode=true&characterEncoding=utf8&rewriteBatchedStatements=true&useConfigs=maxPerformance&useSSL=false
注意:sonar默认监听9000端口,如果9000端口被占用,需要更改。
sonar.web.port=9000
启动sonar
cd /opt/sonarqube-6.7.4
su sonar ./bin/linux-x86-64/sonar.sh start 启动
su sonar ./bin/linux-x86-64/sonar.sh status 查看状态
su sonar ./bin/linux-x86-64/sonar.sh stop 停止
tail -f logs/sonar.logs 查看日志
汉化教程
Sonar汉化包下载:GitHub - xuhuisheng/sonar-l10n-zh: Chinese Pack for SonarQube
Sonar汉化
Sonar默认的语言是英文的,看起来不是那么方便,社区也提供了汉化版的插件下载地址
下载完成将插件放到\extensions\plugins ,重启sonar即可。
[sonar@Test ~]#cd /usr/local/sonarqube-6.7.6/bin/linux-x86-64
[sonar@Test ~]#sh sonar.sh restart
实现代码审查
1.在Jenkins中安装SonarQube Scanner插件
在Jenkins中下载sonar插件目前插件为 SonarQube Scanner for Jenkins
安装完成后,在 系统管理->系统设置中,找到SonarQube servers模块,填写服务器信息:
其中认证token需要登陆sonar后,点击Administrator->security->user,点击token按钮,输入key后再点击generate进行生成
在 系统管理->全局工具配置中找到SonarQube Scanner模块,填写服务器信息:
添加代码审查步骤
以自由风格为例:打开 web_demo_freestyle
# must be unique in a given SonarQube instance
sonar.projectKey=web_demo_freestyle
# this is the name and version displayed in the SonarQube UI. Was mandatory prior to SonarQube 6.1.
sonar.projectName=web_demo_freestyle
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.exclusions=**/test/**,**/target/**
sonar.java.source=1.8
sonar.java.target=1.8
# Encoding of the source code. Default is default system encoding
sonar.sourceEncoding=UTF-8
在 sonarqube 服务器上刷新,查看结果
测试错误代码
新建 Java 和 resource 目录
配置 pom.xml 文件添加对 servlet 的依赖
javax.servlet
javax.servlet-api
4.0.1
需要下一些依赖组件,下载不下来查找原因。
新建编写 Servlet 文件
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class HelloServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
super.doPost(req,resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//模拟错误代码
int i = 100/0;
//模拟代码冗余
int j = 100;
j = 200;
resp.getWriter().write("hello Servlet");
}
}
将 pom.xml 和 HelloServlet.java 提交到 Gitlab
进行构建测试结果
查看 sonarqube
5.3 注意
解决方法:
项目根目录下,创建 sonar-project.properties 文件
# must be unique in a given SonarQube instance
sonar.projectKey=web_demo_pipeline
# this is the name and version displayed in the SonarQube UI. Was mandatory prior to SonarQube 6.1.
sonar.projectName=web_demo_pipeline
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.exclusions=**/test/**,**/target/**
sonar.java.source=1.8
sonar.java.target=1.8
# Encoding of the source code. Default is default system encoding
sonar.sourceEncoding=UTF-8
6.2 修改 Jenkinsfile,加入 SonarQube 代码审查阶段
pipeline {
agent any
stages {
stage('pull code') {
steps {
checkout([$class: 'GitSCM', branches: [[name: '*/${branch}']], extensions: [], userRemoteConfigs: [[credentialsId: '0b127895-eb97-4f8f-b471-1277e5549b54', url: '[email protected]:test-group/web_demo.git']]])
}
}
stage('code checking') {
steps {
script {
//引入了 sonarqube-scanner 工具
scannerHome = tool 'sonar-scanner'
}
//引入了 sonarqube 服务器系统环境
withSonarQubeEnv('sonarqube') {
sh "${scannerHome}/bin/sonar-scanner"
}
}
}
stage('build project') {
steps {
sh 'mvn clean package'
}
}
stage('deploy item') {
steps {
deploy adapters: [tomcat8(credentialsId: '1cf9c5dd-8e2d-4eb6-8c00-bb60e0f027ca', path: '', url: 'http://192.168.10.40:8080/')], contextPath: null, war: 'target/*.war'
}
}
}
post {
always {
emailext(
subject: '构建通知:${PROJECT_NAME} - Build # ${BUILD_NUMBER} - ${BUILD_STATUS}!',body: '${FILE,path="email.html"}', to: '[email protected]'
)
}
}
}
把更改后的 sonar-project.properties 和 Jenkinsfile 进行提交
修改 jdk 版本
和非流水线里面一样,需要修改 jdk 版本。
开始构建 web_demo_pipeline
查看 sonarqube
如果构建的过程中遇到以下错误,则在配置文件中添加
sonar.java.binaries=./target/classes
错误信息
ERROR: Error during SonarQube Scanner execution org.sonar.squidbridge.api.AnalysisException: Please provide compiled classes of your project with sonar.java.binaries property at org.sonar.java.JavaClasspath.init(JavaClasspath.java:59) at org.sonar.java.AbstractJavaClasspath.getElements(AbstractJavaClasspath.java:281) at org.sonar.java.SonarComponents.getJavaClasspath(SonarComponents.java:141) at org.sonar.java.JavaSquid.(JavaSquid.java:83) at org.sonar.plugins.java.JavaSquidSensor.execute(JavaSquidSensor.java:83) at org.sonar.scanner.sensor.SensorWrapper.analyse(SensorWrapper.java:53) at org.sonar.scanner.phases.SensorsExecutor.executeSensor(SensorsExecutor.java:88) at org.sonar.scanner.phases.SensorsExecutor.execute(SensorsExecutor.java:82) at org.sonar.scanner.phases.SensorsExecutor.execute(SensorsExecutor.java:68) at org.sonar.scanner.phases.AbstractPhaseExecutor.execute(AbstractPhaseExecutor.java:88) at org.sonar.scanner.scan.ModuleScanContainer.doAfterStart(ModuleScanContainer.java:177) at org.sonar.core.platform.ComponentContainer.startComponents(ComponentContainer.java:135)