虚拟化容器,大数据,DBA,中间件,监控。

SonarQube 03 SonarScanner的使用 java项目扫描

21 12月
作者:admin|分类:系统运维

配置好sonar的服务端后,接下来就要使用sonar检测我们的代码了,sonar主要是借助客户端检测工具来检测代码,所以要使用sonar就必须先在我们本地配置好客户端检测工具。 客户端可以通过IDE插件、Sonar-Scanner插件、Ant插件和Maven插件方式进行扫描分析。

常用的有扫描器有Sonar-Scanner和Sonar-Runner,使用起来都差不多。这里我使用Sonar-Scanner来作为检测客户端。 

之前sonar的环境ok了,一个sonar容器跑了server和内置的数据库,中文插件也安装了,现在创建一个项目。

这个令牌就是token,用于在扫描的时候做验证的

38c2231d6876f6c62d82d928194c84045bcbaacf

mvn sonar:sonar \
  -Dsonar.projectKey=devops-maven-service \
  -Dsonar.host.url=http://139.198.166.235:9000 \
  -Dsonar.login=38c2231d6876f6c62d82d928194c84045bcbaacf

可以看到基于不同的项目给出具体的扫描代码,我们下面基于scanner来进行扫描。

SonarScanner使用方法


  • 配置文件方式读取扫描参数
  • 命令行方式读取扫描参数

一个基本的sonar-project.properties配置文件的参数:

# 定义唯一的关键字
sonar.projectKey=devops-hello-service

# 定义项目名称
sonar.projectName=My project

# 定义项目的版本信息
sonar.projectVersion=1.0
 
# 指定扫描代码的目录位置(多个逗号分隔,java项目源代码一般在src目录下面)
sonar.sources=.
 
# 执行项目编码
sonar.sourceEncoding=UTF-8

sonar.host.url=
sonar.login
sonar.password

这些配置项都是统一的,目前sonar支持将扫描参数以文件的方式存放或者以命令行传参的方式读取。 文件方式:可以将扫描参数放到项目的根目录或者sonar-scanner的配置文件目录等自定义的目录中, 命令行传参则可以直接将变量传递给sonarsacnner cli -Dsonar.projectKey=xxx

# 指定配置文件,这个可以是本地的配置文件,也可以放在gitlab上面,jenkins拉取代码的时候拉取下来就可以使用myproject.properties,不需要指定路径了
sonar-scanner -Dproject.settings=myproject.properties

# 命令行传参
sonar-scanner -Dsonar.projectKey=myproject -Dsonar.sources=src1

扩展-Docker运行sonarscanner

docker run \
    --rm \
    -e SONAR_HOST_URL="http://${SONARQUBE_URL}" \
    -e SONAR_LOGIN="myAuthenticationToken" \
    -v "${YOUR_REPO}:/usr/src" \
    sonarsource/sonar-scanner-cli 

关于项目参数可以参考:Analysis Parameters | SonarQube Docs

各种语言的扫描示例:https://docs.sonarqube.org/latest/analysis/languages/

安装各种语言扫描插件


SonarQube中各种语言的扫描规则都是以jar包的方式。默认没有安装语言规则插件, 需要手动安装。 服务端安装Java Code Quality and Security  SonarJS  SonarGO 插件,并重启服务器。(如果这里由于网速原因下载不了插件,可以使用课程提供的压缩包,解压到downloads目录下然后重启sonarqube)

[root@tools1 plugins]# ls
sonar-go-plugin-1.6.0.719.jar      sonar-javascript-plugin-6.2.2.13315.jar  sonar-typescript-plugin-2.1.0.4359.jar
sonar-java-plugin-6.3.2.22818.jar  sonar-l10n-zh-plugin-1.29.jar
[root@tools1 plugins]# pwd
/data/cicd/sonarqube/sonarqube_extensions/plugins

 安装好之后多出来一堆规则

Java项目扫描


sonarqube服务器端需要安装Java语言规则插件

sonar.projectKey 指定项目的关键字,sonar.host.url指定服务器地址(可以直接在配置文件中写死),projectName指定项目的名称, projectVersion指定项目的版本(可以用构建时间和构建ID定义),login指定登录用户名,password指定登录用户密码, projectDescription指定项目的描述信息, links.homepage指定项目的主页(超链接), sources指定扫描的目录, sourceEncoding指定扫描时的编码, java.binaries指定编译后的类文件目录(必填), java.test.binaries指定编译后的测试类目录,java.surefire.report指定测试报告目录。

sonar-scanner -Dsonar.host.url=http://139.198.166.235:9000 \
-Dsonar.projectKey=devops-maven-service \
-Dsonar.projectName=devops-maven-service \
-Dsonar.projectVersion=1.0 \
-Dsonar.login=admin \
-Dsonar.password=admin123 \
-Dsonar.ws.timeout=30 \
-Dsonar.projectDescription="my first project!" \
-Dsonar.links.homepage=http://192.168.1.200/devops/devops-maven-service \
-Dsonar.links.ci=http://192.168.1.200:8080/job/demo-pipeline-service/ \
-Dsonar.sources=src \
-Dsonar.sourceEncoding=UTF-8 \
-Dsonar.java.binaries=target/classes \
-Dsonar.java.test.binaries=target/test-classes \
-Dsonar.java.surefire.report=target/surefire-reports

#可以换成token    -Dsonar.login=38c2231d6876f6c62d82d928194c84045bcbaacf
-Dsonar.login=admin \
-Dsonar.password=admin123 \

sonar-scanner \
-Dsonar.host.url=http://139.198.166.235:9000 \
-Dsonar.projectKey=devops-maven-service \
-Dsonar.projectName=devops-maven-service \
-Dsonar.projectVersion=1.0 \
-Dsonar.login=38c2231d6876f6c62d82d928194c84045bcbaacf \
-Dsonar.ws.timeout=30 \
-Dsonar.projectDescription="my first project!" \
-Dsonar.links.homepage=http://192.168.1.200/devops/devops-maven-service \
-Dsonar.links.ci=http://192.168.1.200:8080/job/demo-pipeline-service/ \
-Dsonar.sources=src \
-Dsonar.sourceEncoding=UTF-8 \
-Dsonar.java.binaries=target/classes \
-Dsonar.java.test.binaries=target/test-classes \
-Dsonar.java.surefire.report=target/surefire-reports

来到maven项目下第一件事情编译打包,注意代码扫描是在编译之后的,在sonar扫描的时候会用到target里面的classes,这里面存放的是编译过后的类。

[root@jenkins-agent devops-maven-service-master]# ls target/
classes                  demo-0.0.1-SNAPSHOT.jar.original  generated-test-sources  maven-status      test-classes
demo-0.0.1-SNAPSHOT.jar  generated-sources                 maven-archiver          surefire-reports
[root@jenkins-agent devops-maven-service-master]# ls target/classes/
application.properties  com
[root@jenkins-agent devops-maven-service-master]# ls target/classes/com/
example
[root@jenkins-agent devops-maven-service-master]# ls target/classes/com/example/
demo
[root@jenkins-agent devops-maven-service-master]# ls target/classes/com/example/demo/
DemoApplication.class

这个是测试类

 test-classes

 这个是测试报告

surefire-reports
[root@jenkins-master devops-maven-service-master]# ls
Jenkinsfile  mvnw  mvnw.cmd  pom.xml  src


[root@jenkins-master devops-maven-service-master]# mvn clean  package
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time:  17.034 s
[INFO] Finished at: 2021-06-06T12:08:27+08:00
[INFO] ------------------------------------------------------------------------

[root@jenkins-master devops-maven-service-master]# ls
Jenkinsfile  mvnw  mvnw.cmd  pom.xml  src  target



#test-classes测试类和surefire-reports测试报告
[root@jenkins-master target]# ls
classes                  demo-0.0.1-SNAPSHOT.jar.original  generated-test-sources  maven-status      test-classes
demo-0.0.1-SNAPSHOT.jar  generated-sources                 maven-archiver          surefire-reports
[root@jenkins-master target]# pwd
/root/devops-maven-service-master/target

[root@jenkins-master devops-maven-service-master]# ls
Jenkinsfile  mvnw  mvnw.cmd  pom.xml  src  target

sonar-scanner -Dsonar.host.url=http://139.198.170.122:9000 \
-Dsonar.projectKey=devops-maven-service \
-Dsonar.projectName=devops-maven-service \
-Dsonar.projectVersion=1.0 \
-Dsonar.login=admin \
-Dsonar.password=admin \
-Dsonar.ws.timeout=30 \
-Dsonar.projectDescription="my first project!" \
-Dsonar.links.homepage=http://139.198.170.122:81/root/devops-maven-service \
-Dsonar.links.ci=http://139.198.170.122:8080/job/demo-maven-service/ \
-Dsonar.sources=src/main \
-Dsonar.sourceEncoding=UTF-8 \
-Dsonar.java.binaries=target/classes \
-Dsonar.java.test.binaries=target/test-classes \
-Dsonar.java.surefire.report=target/surefire-reports

# -Dsonar.sources=src  扫描的目录,java项目的源码目录为src,里面有测试代码和你自己的代码,都会扫描,如果只想扫描项目的,就src/main

#可以看到这个是全局的配置文件,会读取里面的信息
INFO: Scanner configuration file: /usr/local/sonar-scanner-4.6.0.2311-linux/conf/sonar-scanner.properties


[root@jenkins-master devops-maven-service-master]# ls -a
.  ..  .git  .gitignore  Jenkinsfile  .mvn  mvnw  mvnw.cmd  pom.xml  .scannerwork  src  target

上面这些参数除了用命令行指定,还可以放到项目的目录里面

[root@jenkins-master devops-maven-service-master]# vim myproject.properties
[root@jenkins-master devops-maven-service-master]# sed -e 's/\\//g' -e 's/\-D//g'  myproject.properties 
sonar.host.url=http://139.198.170.122:9000 
sonar.projectKey=devops-maven-service 
sonar.projectName=devops-maven-service 
sonar.projectVersion=1.0 
sonar.login=admin 
sonar.password=admin 
sonar.ws.timeout=30 
sonar.projectDescription="my first project!" 
sonar.links.homepage=http://139.198.170.122:81/root/devops-maven-service 
sonar.links.ci=http://139.198.170.122:8080/job/devops-maven-service/ 
sonar.sources=src/main 
sonar.sourceEncoding=UTF-8 
sonar.java.binaries=target/classes 
sonar.java.test.binaries=target/test-classes 
sonar.java.surefire.report=target/surefire-reports


[root@jenkins-master devops-maven-service-master]# sonar-scanner -Dproject.settings=myproject.properties

SonarQube的参数


Mandatory Parameters

Server

Key Description Default
sonar.host.url the server URL http://localhost:9000

Project Configuration

Key Description Default
sonar.projectKey The project's unique key. Allowed characters are: letters, numbers, -_. and :, with at least one non-digit. For Maven projects, this defaults to <groupId>:<artifactId>

Optional Parameters

Project Identity

Key Description Default
sonar.projectName Name of the project that will be displayed on the web interface. <name> for Maven projects, otherwise project key. If not provided and there is already a name in the DB, it won't be overwritten
sonar.projectVersion The project version. <version> for Maven projects, otherwise "not provided"

Authentication

By default, user authentication is required to prevent anonymous users from browsing and analyzing projects on your instance, and you need to pass these parameters when running analyses. Authentication is enforced in the global Security(/instance-administration/security/) settings.

When authentication is required or the "Anyone" pseudo-group does not have permission to perform analyses, you'll need to supply the credentials of a user with Execute Analysis permissions for the analysis to run under.

Key Description Default
sonar.login The authentication token or login of a SonarQube user with Execute Analysis permission on the project.
sonar.password If you're using an authentication token, leave this blank. If you're using a login, this is the password that goes with your sonar.login username.

Web Services

Key Description Default
sonar.ws.timeout Maximum time to wait for the response of a Web Service call (in seconds). Modifying this value from the default is useful only when you're experiencing timeouts during analysis while waiting for the server to respond to Web Service calls. 60

Project Configuration

Key Description Default
sonar.projectDescription The project description. <description> for Maven projects
sonar.links.homepage Project home page. <url> for Maven projects
sonar.links.ci Continuous integration. <ciManagement><url> for Maven projects
onar.sources Comma-separated paths to directories containing main source files. Read from build system for Maven, Gradle, MSBuild projects. Defaults to project base directory when neither sonar.sources nor sonar.tests is provided.
sonar.sourceEncoding Encoding of the source files. Ex: UTF-8MacRomanShift_JIS. This property can be replaced by the standard property project.build.sourceEncoding in Maven projects. The list of available encodings depends on your JVM. System encoding

最后整体项目代码如下:

withCredentials([string(credentialsId: 'f8b33d17-c1cf-428e-aa31-99d4038e59d0', variable: 'sonar_token')]) {
    // some block
}
@Library("devopslib@main") _

def project = new org.devops.build()
def buildTools = ["maven": "/usr/local/apache-maven-3.8.1"]
def credentials = ["devops-maven-sonarqube": "f8b33d17-c1cf-428e-aa31-99d4038e59d0"]

String buildType = "${env.buildType}"

currentBuild.description = "maven project"


pipeline {
    
   agent {
      label 'build'
   }

    stages {
        stage('CheckOut') {
            steps {
                checkout([$class: 'GitSCM', 
                          branches: [[name: "${branchName}"]], 
                          extensions: [], userRemoteConfigs: 
                          [[credentialsId: "${credentialsId}", 
                          url: "${srcUrl}"]]])
            }
        }
        
        stage('Build'){
           steps{
             script{
                project.build(buildType,buildTools)
             }
         }
     }
     
       stage("UnitTest"){
          steps{
             script{
               sh "${buildTools["maven"]}/bin/mvn test"
             }
         }
          post{
             success{
                script{
                     junit 'target/surefire-reports/*.xml'
                }
             }
         }
     }
      stage('CodeScan'){
           steps{
             script{
                 withCredentials([string(credentialsId: "${credentials['devops-maven-sonarqube']}", variable: 'sonar_token')]) {
        
             
               sh """
               sonar-scanner \
                -Dsonar.host.url=http://139.198.166.235:9000 \
                -Dsonar.projectKey=${env.JOB_NAME} \
                -Dsonar.projectName=${env.JOB_NAME} \
                -Dsonar.projectVersion=${env.BUILD_NUMBER} \
                -Dsonar.login=${sonar_token} \
                -Dsonar.ws.timeout=30 \
                -Dsonar.projectDescription="my first project!" \
                -Dsonar.links.homepage=${env.srcUrl} \
                -Dsonar.links.ci=${env.BUILD_URL} \
                -Dsonar.sources=src \
                -Dsonar.sourceEncoding=UTF-8 \
                -Dsonar.java.binaries=target/classes \
                -Dsonar.java.test.binaries=target/test-classes \
                -Dsonar.java.surefire.report=target/surefire-reports
                """
                 }
             }
         }
      }
   }
}


浏览533 评论0
返回
目录
返回
首页
SonarQube 05 CI流水线集成 shell 命令行方式和Jenkins 插件方式 SonarQube 02 插件安装以及配置scanner