SonarQube-代碼審查管理工具

Sonar家族框架

在這裏插入圖片描述

檢測代碼質量七個維度

  • 複雜度分佈(complexity):代碼複雜度過高將難以理解
  • 重複代碼(duplications):程序中包含大量複製、粘貼的代碼而導致代碼臃腫,sonar可以展示源碼中重複嚴重的地方
  • 單元測試統計(unit tests):統計並展示單元測試覆蓋率,開發或測試可以清楚測試代碼的覆蓋情況
  • 代碼規則檢查(coding rules):通過Findbugs,PMD,CheckStyle等檢查代碼是否符合規
  • 註釋率(comments):若代碼註釋過少,特別是人員變動後,其他人接手比較難接手;若過多,又不利於閱讀
  • 潛在的Bug(potential bugs):通過Findbugs,PMD,CheckStyle等檢測潛在的bug
  • 結構與設計(architecture & design):找出循環,展示包與包、類與類之間的依賴、檢查程序之間耦合度

支持語言

ABAP、C/C++、C#、CSS、COBOL、Flex、Go、HTML、Java、JavaScript、Kotlin、Objective-C、PL/SQL、PL/I、PHP、Python、RPG、Ruby、Swift、T-SQL、TypeScript、VB.NET、VB6、XML

環境部署

SonarQube下載與安裝

在SonarQube的下載頁面:https://www.sonarqube.org/downloads/
JDK11下載:https://www.oracle.com/technetwork/java/javase/downloads/jdk11-downloads-5066655.html

啓動SONARQUBE服務

雙擊StartSonar.bat即可啓動SonarQube服務
在這裏插入圖片描述
啓動成功命令行如下圖所示:
在這裏插入圖片描述
啓動成功後,用瀏覽器打開http://localhost:9000
在這裏插入圖片描述
到此爲止,SonarQube的服務端實際上已經部署成功,然而它還是隻是個測試用的環境不足以用於生產環境,因爲SonarQube是一個需要數據存儲的Web系統,它需要數據庫才能成爲一個完整的有數據存儲和展示功能的Web系統
在SonarQube的目錄中有個conf文件夾,該文件夾內是SonarQube的配置文件,數據庫的配置即是在sonar.properties中配置的,在該配置文件中我們也能看到當前版本的SonarQube支持哪些數據庫

數據庫配置

#--------------------------------------------------------------------------------------------------
# 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.jdbc.password=

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

#----- DEPRECATED 
#----- MySQL >=5.6 && <8.0
# Support of MySQL is dropped in Data Center Editions and deprecated in all other editions
# Only InnoDB storage engine is supported (not myISAM).
# Only the bundled driver is supported. It can not be changed.
sonar.jdbc.url=jdbc:mysql://localhost:3306/sonar?useUnicode=true&characterEncoding=utf8&rewriteBatchedStatements=true&useConfigs=maxPerformance&&useSSL=false
sonar.jdbc.username=mysql
sonar.jdbc.password=alex005x
sonar.sorceEncoding=UTF-8
sonar.login=admin
sonar.password=admin

#----- Oracle 11g/12c
# The Oracle JDBC driver must be copied into the directory extensions/jdbc-driver/oracle/.
# Only the thin client is supported, and only the versions 11.2.x or 12.2.x must be used. See
# https://jira.sonarsource.com/browse/SONAR-9758 for more details.
# If you need to set the schema, please refer to http://jira.sonarsource.com/browse/SONAR-5000
#sonar.jdbc.url=jdbc:oracle:thin:@localhost:1521/XE


#----- PostgreSQL 9.3 or greater
# By default the schema named "public" is used. It can be overridden with the parameter "currentSchema".
#sonar.jdbc.url=jdbc:postgresql://localhost/sonarqube?currentSchema=my_schema


#----- Microsoft SQLServer 2014/2016 and SQL Azure
# A database named sonar must exist and its collation must be case-sensitive (CS) and accent-sensitive (AS)
# Use the following connection string if you want to use integrated security with Microsoft Sql Server
# Do not set sonar.jdbc.username or sonar.jdbc.password property if you are using Integrated Security
# For Integrated Security to work, you have to download the Microsoft SQL JDBC driver package from
# https://www.microsoft.com/en-us/download/details.aspx?id=55539
# and copy sqljdbc_auth.dll to your path. You have to copy the 32 bit or 64 bit version of the dll
# depending upon the architecture of your server machine.
#sonar.jdbc.url=jdbc:sqlserver://localhost;databaseName=sonar;integratedSecurity=true

# Use the following connection string if you want to use SQL Auth while connecting to MS Sql Server.
# Set the sonar.jdbc.username and sonar.jdbc.password appropriately.
#sonar.jdbc.url=jdbc:sqlserver://localhost;databaseName=sonar


#----- Connection pool settings
# The maximum number of active connections that can be allocated
# at the same time, or negative for no limit.
# The recommended value is 1.2 * max sizes of HTTP pools. For example if HTTP ports are
# enabled with default sizes (50, see property sonar.web.http.maxThreads)
# then sonar.jdbc.maxActive should be 1.2 * 50 = 60.
#sonar.jdbc.maxActive=60

# The maximum number of connections that can remain idle in the
# pool, without extra ones being released, or negative for no limit.
#sonar.jdbc.maxIdle=5

# The minimum number of connections that can remain idle in the pool,
# without extra ones being created, or zero to create none.
#sonar.jdbc.minIdle=2

# The maximum number of milliseconds that the pool will wait (when there
# are no available connections) for a connection to be returned before
# throwing an exception, or <= 0 to wait indefinitely.
#sonar.jdbc.maxWait=5000

#sonar.jdbc.minEvictableIdleTimeMillis=600000
#sonar.jdbc.timeBetweenEvictionRunsMillis=30000

Web Server配置


#--------------------------------------------------------------------------------------------------
# WEB SERVER
# Web server is executed in a dedicated Java process. By default heap size is 512Mb.
# Use the following property to customize JVM options.
#    Recommendations:
#
#    The HotSpot Server VM is recommended. The property -server should be added if server mode
#    is not enabled by default on your environment:
#    http://docs.oracle.com/javase/8/docs/technotes/guides/vm/server-class.html
#
#    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


# The maximum number of connections that the server will accept and process at any given time.
# When this number has been reached, the server will not accept any more connections until
# the number of connections falls below this value. The operating system may still accept connections
# based on the sonar.web.connections.acceptCount property. The default value is 50.
#sonar.web.http.maxThreads=50

# The minimum number of threads always kept running. The default value is 5.
#sonar.web.http.minThreads=5

# The maximum queue length for incoming connection requests when all possible request processing
# threads are in use. Any requests received when the queue is full will be refused.
# The default value is 25.
#sonar.web.http.acceptCount=25

# By default users are logged out and sessions closed when server is restarted.
# If you prefer keeping user sessions open, a secret should be defined. Value is
# HS256 key encoded with base64. It must be unique for each installation of SonarQube.
# Example of command-line:
# echo -n "type_what_you_want" | openssl dgst -sha256 -hmac "key" -binary | base64
#sonar.auth.jwtBase64Hs256Secret=

# The inactivity timeout duration of user sessions, in minutes. After the configured
# period of time, the user is logged out.
# The default value is set to 3 days (4320 minutes)
# and cannot be greater than 3 months. Value must be strictly positive.
#sonar.web.sessionTimeoutInMinutes=4320

# A passcode can be defined to access some web services from monitoring
# tools without having to use the credentials of a system administrator.
# Check the Web API documentation to know which web services are supporting this authentication mode.
# The passcode should be provided in HTTP requests with the header "X-Sonar-Passcode".
# By default feature is disabled.
#sonar.web.systemPasscode=

除了以上兩類重要配置外,還有單點登錄、LDAP、Java虛擬機配置等相關參數可配

配置插件

在這裏插入圖片描述

配置SonarQube Scanner

下載地址:https://docs.sonarqube.org/display/SCAN/Analyzing+with+SonarQube+Scanner
在這裏插入圖片描述

#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.jdbc.url=jdbc:mysql://localhost:3306/sonar?useUnicode=true&characterEncoding=utf8&rewriteBatchedStatements=true&useConfigs=maxPerformance&&useSSL=false
sonar.jdbc.username=mysql
sonar.jdbc.password=alex005x

新增系統環境變量

SONAR_SCANNER_HOME:D:\sonar-scanner-4.2.0.1873-windows
在這裏插入圖片描述
Path中新增%SONAR_SCANNER_HOME%\bin;
在這裏插入圖片描述
驗證配置,在命令行輸入sonar-scanner -help

D:\cuss-social-jscoco\target\classes\com\xhl\cuss\social>sonar-scanner -help
ERROR: Unrecognized option: -help
INFO:
INFO: usage: sonar-scanner [options]
INFO:
INFO: Options:
INFO:  -D,--define <arg>     Define property
INFO:  -h,--help             Display help information
INFO:  -v,--version          Display version information
INFO:  -X,--debug            Produce execution debug output

在工程目錄下新建文件名爲sonar-project.properties,在文件中寫入如下項目信息,用於寫入Sonar數據庫

#項目的key
sonar.projectKey=my:baseInfo

#項目的名字
sonar.projectName=BASIC_INFORMATION

#項目的版本
sonar.projectVersion=1.0.0

#需要分析的源碼的目錄,多個目錄用英文逗號隔開
sonar.sources=D:/cuss-social-jscoco/src/main/java/com/xhl

# Language
sonar.language=java

sonar.java.binaries=.
sonar.sourceEncoding=UTF-8

執行掃描

在工程目錄下,執行命令sonar-scanner即可完成掃描,掃描結果會寫入數據庫,並可才Sonar平臺上查看結果

D:\cuss-social-jscoco>sonar-scanner
INFO: Scanner configuration file: D:\sonar-scanner-4.2.0.1873-windows\bin\..\conf\sonar-scanner.properties
INFO: Project root configuration file: D:\cuss-social-jscoco\sonar-project.properties
INFO: SonarQube Scanner 4.2.0.1873
INFO: Java 11.0.3 AdoptOpenJDK (64-bit)
INFO: Windows 10 10.0 amd64
INFO: User cache: C:\Users\Administrator\.sonar\cache
INFO: SonarQube server 7.6.0
INFO: Default locale: "zh_CN", source code encoding: "UTF-8"
INFO: Load global settings
WARNING: An illegal reflective access operation has occurred
WARNING: Illegal reflective access by com.google.protobuf.UnsafeUtil (file:/C:/Users/Administrator/.sonar/cache/993f707e3af7ba4f46f121039128516b/sonar-scanner-engine-shaded-7.6-all.jar) to field java.nio.Buffer.address
WARNING: Please consider reporting this to the maintainers of com.google.protobuf.UnsafeUtil
WARNING: Use --illegal-access=warn to enable warnings of further illegal reflective access operations
WARNING: All illegal access operations will be denied in a future release
INFO: Load global settings (done) | time=50ms
INFO: Server id: 49B321BC-AW5aoLlje3tu4A9kELXR
INFO: User cache: C:\Users\Administrator\.sonar\cache
INFO: Load/download plugins
INFO: Load plugins index
INFO: Load plugins index (done) | time=70ms
INFO: Plugin [l10nzh] defines 'l10nen' as base plugin. This metadata can be removed from manifest of l10n plugins since version 5.2.
INFO: Load/download plugins (done) | time=100ms
INFO: Process project properties
INFO: Execute project builders
INFO: Execute project builders (done) | time=10ms
INFO: Project key: my:baseInfo
INFO: Base dir: D:\cuss-social-jscoco
INFO: Working dir: D:\cuss-social-jscoco\.scannerwork
INFO: Load project settings
INFO: Load project settings (done) | time=20ms
INFO: Load project repositories
INFO: Load project repositories (done) | time=50ms
INFO: Load quality profiles
INFO: Load quality profiles (done) | time=40ms
INFO: Load active rules
INFO: Load active rules (done) | time=340ms
INFO: Load metrics repository
INFO: Load metrics repository (done) | time=21ms
WARN: SCM provider autodetection failed. Please use "sonar.scm.provider" to define SCM of your project, or disable the SCM Sensor in the project settings.
INFO: Language is forced to java
INFO: Indexing files...
INFO: Project configuration:
INFO: 132 files indexed
INFO: Quality profile for java: Sonar way
INFO: ------------- Run sensors on module BASIC_INFORMATION
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, you might end up with less precise results. Bytecode can be provided using sonar.java.libraries property.
INFO: JavaClasspath initialization (done) | time=20ms
INFO: JavaTestClasspath initialization
INFO: JavaTestClasspath initialization (done) | time=10ms
INFO: Java Main Files AST scan
INFO: 132 source files to be analyzed
INFO: 132/132 source files have been analyzed
INFO: Java Main Files AST scan (done) | time=9762ms
INFO: Java Test Files AST scan
INFO: 0 source files to be analyzed
INFO: Java Test Files AST scan (done) | time=0ms
INFO: 0/0 source files have been analyzed
INFO: Sensor JavaSquidSensor [java] (done) | time=10202ms
INFO: Sensor JaCoCo XML Report Importer [jacoco]
INFO: Sensor JaCoCo XML Report Importer [jacoco] (done) | time=10ms
INFO: Sensor SurefireSensor [java]
INFO: parsing [D:\cuss-social-jscoco\target\surefire-reports]
INFO: Sensor SurefireSensor [java] (done) | time=10ms
INFO: Sensor JaCoCoSensor [java]
INFO: Sensor JaCoCoSensor [java] (done) | time=0ms
INFO: Sensor JavaXmlSensor [java]
INFO: Sensor JavaXmlSensor [java] (done) | time=10ms
INFO: Sensor HTML [web]
INFO: Sensor HTML [web] (done) | time=10ms
INFO: Sensor Zero Coverage Sensor
INFO: Sensor Zero Coverage Sensor (done) | time=80ms
INFO: ------------- Run sensors on project
INFO: Sensor Java CPD Block Indexer
INFO: Sensor Java CPD Block Indexer (done) | time=271ms
INFO: No SCM system was detected. You can use the 'sonar.scm.provider' property to explicitly specify it.
INFO: 32 files had no CPD blocks
INFO: Calculating CPD for 100 files
INFO: CPD calculation finished
INFO: Analysis report generated in 270ms, dir size=1 MB
INFO: Analysis report compressed in 370ms, zip size=472 KB
INFO: Analysis report uploaded in 80ms
INFO: ANALYSIS SUCCESSFUL, you can browse http://localhost:9000/dashboard?id=my%3AbaseInfo
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=AW5eRz6r4XbRoxI2cCRW
INFO: Analysis total time: 13.842 s
INFO: ------------------------------------------------------------------------
INFO: EXECUTION SUCCESS
INFO: ------------------------------------------------------------------------
INFO: Total time: 14.893s
INFO: Final Memory: 8M/34M
INFO: ------------------------------------------------------------------------

在結果中能夠看到鏈接

http://localhost:9000/dashboard?id=my%3AbaseInfo

用瀏覽器打開該鏈接,即可查看結果
在這裏插入圖片描述

掃描Maven項目

在這裏插入圖片描述
在這裏插入圖片描述
點擊Setup,然後輸入一個Name,並點擊Generate按鈕生成token
在這裏插入圖片描述
在這裏插入圖片描述
點擊Continue,然後根據項目的語言選擇要掃描什麼類型的項目,例如Java語言的項目jiu選擇Java然後,根據構建工具選擇Maven還是Gradle,例如選擇Maven
在這裏插入圖片描述

配置Maven

  <pluginGroups>
	 <pluginGroup>org.sonarsource.scanner.maven</pluginGroup>
  </pluginGroups>
        <profile>
            <id>sonar</id>
            <activation>
                <activeByDefault>true</activeByDefault>
            </activation>
            <properties>
                <sonar.host.url>
                  http://192.168.70.62:9000
                </sonar.host.url>
            </properties>
        </profile>

如果Maven環境配置成功,則只需要在命令行執行如下命令即可完成掃描

mvn sonar:sonar \
  -Dsonar.projectKey=java-c-leadscloud \
  -Dsonar.host.url=http://localhost:9000 \
  -Dsonar.login=c8e3f17a12f5ead7dac8a7a45460b7be958ef5e1

掃描Gradle項目

如果選擇Gradle,則需要作如下配置
在這裏插入圖片描述

發佈了155 篇原創文章 · 獲贊 43 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章