1. Overview
1.概述
In this article, we’re going to be looking at static source code analysis with SonarQube – which is an open-source platform for ensuring code quality.
在这篇文章中,我们将通过SonarQube来了解静态源代码分析–这是一个用于确保代码质量的开源平台。
Let’s start with a core question – why analyze source code in the first place? Very simply put, to ensure quality, reliability, and maintainability over the life-span of the project; a poorly written codebase is always more expensive to maintain.
让我们从一个核心问题开始 – 为什么首先要分析源代码?很简单,为了确保项目生命周期内的质量、可靠性和可维护性;一个写得不好的代码库的维护成本总是很高。
Alright, now let’s get started by downloading the latest LTS version of SonarQube from the download page and setting up our local server as outlined in this quick start guide.
好了,现在让我们开始吧,从下载页面下载最新的LTS版本的SonarQube,并按照本快速入门指南中的规定设置我们的本地服务器。
2. Analyzing Source Code
2.分析源代码
We’ll use the token later at the point of analyzing our project(s). We also need to select the primary language (Java) and the build technology of the project (Maven).
我们将在以后分析项目时使用该令牌。我们还需要选择主要语言(Java)和项目的构建技术(Maven)。
Let’s define the plugin in the pom.xml:
让我们在pom.xml中定义该插件。
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.sonarsource.scanner.maven</groupId>
<artifactId>sonar-maven-plugin</artifactId>
<version>3.4.0.905</version>
</plugin>
</plugins>
</pluginManagement>
</build>
The latest version of the plugin is available here. Now, we need to execute this command from the root of our project directory to scan it:
该插件的最新版本可在这里。现在,我们需要从我们项目目录的根部执行这个命令来扫描它。
mvn sonar:sonar -Dsonar.host.url=http://localhost:9000
-Dsonar.login=the-generated-token
We need to replace the-generated-token with the token from above.
我们需要将the-generated-token替换成上面的token。
The project that we used in this article is available here.
我们在本文中使用的项目可在这里获得。。
We specified the host URL of the SonarQube server and the login (generated token) as parameters for the Maven plugin.
我们为Maven插件指定了SonarQube服务器的主机URL和登录(生成的token)作为参数。
After executing the command, the results will be available on the Projects dashboard – at http://localhost:9000.
执行命令后,结果将在项目仪表板上显示 – http://localhost:9000。
There are other parameters that we can pass to the Maven plugin or even set from the web interface; sonar.host.url, sonar.projectKey, and sonar.sources are mandatory while others are optional.
我们还可以向Maven插件传递其他参数,甚至可以从Web界面设置;sonar.host.url、sonar.projectKey和sonar.sources是必须的,其他参数是可选的。
Other analysis-parameters and their default values are here. Also, note that each language-plugin has rules for analyzing compatible source code.
其他分析参数及其默认值在这里。另外,请注意,每个语言插件都有分析兼容源代码的规则。
3. Analysis Result
3.分析结果
Now that we’ve analyzed our first project, we can go to the web interface at http://localhost:9000 and refresh the page.
现在我们已经分析了我们的第一个项目,我们可以到http://localhost:9000的网络界面,刷新页面。
There we’ll see the report summary:
在那里我们会看到报告摘要。
Discovered issues can either be a Bug, Vulnerability, Code Smell, Coverage or Duplication. Each category has a corresponding number of issues or a percentage value.
发现的问题可以是Bug、漏洞、代码嗅觉、覆盖率或重复。每个类别都有一个相应的问题数量或百分比值。
Moreover, issues can have one of five different severity levels: blocker, critical, major, minor and info. Just in front of the project name is an icon that displays the Quality Gate status – passed (green) or failed (red).
此外,问题可以有五个不同的严重程度之一。阻止者、关键、主要、次要和信息。在项目名称前面有一个图标,显示质量门的状态 – 通过(绿色)或失败(红色)。
Clicking on the project name will take us to a dedicated dashboard where we can explore issues particular to the project in greater detail.
点击项目名称将带我们到一个专门的仪表板,在那里我们可以更详细地探索项目的具体问题。
We can see the project code, activity and perform administration tasks from the project dashboard – each available on a separate tab.
我们可以从项目仪表板上看到项目代码、活动和执行管理任务–每一个都可以在一个单独的标签上找到。
Though there is a global Issues tab, the Issues tab on the project dashboard display issues specific to the project concerned alone:
虽然有一个全局问题标签,但项目仪表板上的问题标签只显示相关项目的具体问题。
The issues tab always display the category, severity level, tag(s), and the calculated effort (regarding time) it will take to rectify an issue.
问题选项卡总是显示类别、严重程度、标签,以及纠正一个问题所需的计算努力(关于时间)。
From the issues tab, it’s possible to assign an issue to another user, comment on it, and change its severity level. Clicking on the issue itself will show more detail about the issue.
从问题标签中,可以将一个问题分配给另一个用户,对它进行评论,并改变其严重程度。点击问题本身将显示关于该问题的更多细节。
The issue tab comes with sophisticated filters to the left. These are good for pinpointing issues. So how can one know if the codebase is healthy enough for deployment into production? That’s what Quality Gate is for.
问题选项卡的左边有复杂的过滤器。这些都有利于准确定位问题。那么,如何才能知道代码库是否足够健康,可以部署到生产中呢?这就是质量门的作用。
4. SonarQube Quality Gate
4.SonarQube质量门
In this section, we’re going to look at a key feature of SonarQube – Quality Gate. Then we’ll see an example of how to set up a custom one.
在这一节中,我们要看一下SonarQube的一个关键功能–质量门。然后我们将看到一个如何设置一个自定义的例子。
4.1. What Is a Quality Gate?
4.1.什么是质量门?
A Quality Gate is a set of conditions the project must meet before it can qualify for production release. It answers one question: can I push my code to production in its current state or not?
质量门是项目在有资格进行生产发布之前必须满足的一组条件。它回答了一个问题:我是否可以在当前状态下将我的代码推向生产?
Ensuring code quality of “new” code while fixing existing ones is one good way to maintain a good codebase over time. The Quality Gate facilitates setting up rules for validating every new code added to the codebase on subsequent analysis.
在修复现有代码的同时确保 “新 “代码的代码质量是长期保持良好代码库的一个好方法。质量门便于设置规则,以验证在后续分析上添加到代码库的每段新代码。
The conditions set in the Quality Gate still affect unmodified code segments. If we can prevent new issues arising, over time, we’ll eliminate all issues.
质量门中设置的条件仍然影响着未修改的代码段。如果我们能防止新问题的产生,随着时间的推移,我们将消除所有问题。
This approach is comparable to fixing the water leakage from the source. This brings us to a particular term – Leakage Period. This is the period between two analyses/versions of the project.
这种方法相当于从源头解决漏水问题。这就给我们带来了一个特殊的术语–漏水期。这是项目的两次分析/版本之间的时期。
If we rerun the analysis, on the same project, the overview tab of the project dashboard will show results for the leak period:
如果我们重新运行分析,在同一个项目上,项目仪表板的概览标签将显示泄漏期的结果。
From the web interface, the Quality Gates tab is where we can access all the defined quality gates. By default, SonarQube way came preinstalled with the server.
从Web界面,质量门标签是我们可以访问所有定义的质量门的地方。默认情况下,SonarQube方式预装在服务器上。
The default configuration for SonarQube way flags the code as failed if:
SonarQube方式的默认配置将代码标记为失败,如果。
- the coverage on new code is less than 80%
- percentage of duplicated lines on new code is greater than 3
- maintainability, reliability or security rating is worse than A
With this understanding, we can create a custom Quality Gate.
有了这种认识,我们就可以创建一个定制的质量门。
4.2. Adding Custom Quality Gate
4.2.添加自定义质量门
First, we need to click on the Quality Gates tab and then click on the Create button which is on the left of the page. We’ll need to give it a name – baeldung.
首先,我们需要点击质量门标签,然后点击页面左边的创建按钮。我们需要给它起个名字–baeldung。
Now we can set the conditions we want:
现在我们可以设置我们想要的条件。
From the Add Condition drop-down, let’s choose Blocker Issues; it’ll immediately show up on the list of conditions.
从添加条件下拉菜单中,让我们选择封锁者问题;它将立即显示在条件列表中。
We’ll specify is greater than as the Operator, set zero (0) for the Error column and check Over Leak Period column:
我们将指定是大于作为操作者,为错误列设置零(0),并检查过漏期列。
Then we’ll click on the Add button to effect the changes. Let’s add another condition following the same procedure as above.
然后我们点击添加按钮来实现这些改变。让我们按照上述同样的程序添加另一个条件。
We’ll select issues from the Add Condition drop-down and check Over Leak Period column.
我们将从添加条件下拉中选择问题,并选中过漏期列。
The value of the Operator column will be set to “is less than” and we’ll add one (1) as the value for the Error column. This means if the number of issues in the new code added is less than 1, mark the Quality Gate as failed.
Operator列的值将被设置为”小于”,我们将添加一(1)作为Error列的值。这意味着如果添加的新代码中的问题数量少于1,则将质量门标记为失败。
I know this doesn’t make technical sense but let’s use it for learning sake. Don’t forget to click the Add button to save the rule.
我知道这在技术上没有意义,但为了学习,让我们使用它。不要忘记点击Add按钮来保存规则。
One final step, we need to attach a project to our custom Quality Gate. We can do so by scrolling down the page to the Projects section.
最后一步,我们需要为我们的自定义质量门附加一个项目。我们可以通过向下滚动页面到项目部分来做到这一点。
There we need to click on All and then mark our project of choice. We can as well set it as the default Quality Gate from the top-right corner of the page.
在那里我们需要点击全部,然后标记我们选择的项目。我们也可以在页面的右上角将其设置为默认的质量门。
We’ll scan the project source code, again, as we did before with Maven command. When that’s done, we’ll go to the projects tab and refresh.
我们将再次扫描项目源代码,就像我们之前用Maven命令做的那样。完成后,我们将进入项目标签并刷新。
This time, the project will not meet the Quality Gate criteria and will fail. Why? Because in one of our rules we have specified that, it should fail if there are no new issues.
这一次,该项目将不符合质量门的标准,将失败。为什么?因为在我们的一个规则中,我们规定,如果没有新的问题,它就应该失败。
Let’s go back to the Quality Gates tab and change the condition for issues to is greater than. We need to click the update button to effect this change.
让我们回到质量门标签,将问题的条件改为是大于。我们需要点击更新按钮来实现这一改变。
A new scan of the source code will pass this time around.
这次对源代码的新扫描将通过。
5. Integrating SonarQube into a CI
5.将SonarQube集成到一个CI中
Making SonarQube part of a Continuous Integration process is possible. This will automatically fail the build if the code analysis did not satisfy the Quality Gate condition.
使SonarQube成为持续集成过程的一部分是可能的。如果代码分析没有满足质量门的条件,这将自动导致构建失败。
For us to achieve this, we’re going to be using SonarCloud which is the cloud-hosted version of SonaQube server. We can create an account here.
为了实现这一目标,我们将使用SonarCloud,这是SonaQube服务器的云托管版本。我们可以在这里创建一个账户。
From My Account > Organizations, we can see the organization key, and it will usually be in the form xxxx-github or xxxx-bitbucket.
从 “我的账户”>”组织”,我们可以看到组织密钥,它通常是xxxx-github或xxxx-bitbucket形式。
Also from My Account > Security, we can generate a token as we did in the local instance of the server. Take note of both the token and the organization key for later use.
同样从My Account > Security,我们可以像在服务器的本地实例中那样生成一个令牌。把令牌和组织密钥都记下来,以便以后使用。
In this article, we’ll be using Travis CI, and we’ll create an account here with an existing Github profile. It will load all our projects, and we can flip the switch on any to activate Travis CI on it.
在这篇文章中,我们将使用Travis CI,并且我们将用现有的Github配置文件创建一个帐户这里。它将加载我们所有的项目,我们可以在任何一个项目上打开开关以激活Travis CI。
We need to add the token we generated on SonarCloud to Travis environment variables. We can do this by clicking on the project we’ve activated for CI.
我们需要将我们在SonarCloud上生成的令牌添加到Travis环境变量中。我们可以通过点击我们为CI激活的项目来做到这一点。
Then, we’ll click “More Options” > “Settings” and then scroll down to “Environment Variables”:
然后,我们将点击 “更多选项”>”设置”,然后向下滚动到 “环境变量”。
We’ll add a new entry with the name SONAR_TOKEN and use the token generated, on SonarCloud, as the value. Travis CI will encrypt and hide it from public view:
我们将添加一个新条目,名称为SONAR_TOKEN,并使用在SonarCloud上生成的令牌作为值。Travis CI将对它进行加密并隐藏起来,不让公众看到。
Finally, we need to add a .travis.yml file to the root of our project with the following content:
最后,我们需要在我们项目的根部添加一个.travis.yml文件,内容如下。
language: java
sudo: false
install: true
addons:
sonarcloud:
organization: "your_organization_key"
token:
secure: "$SONAR_TOKEN"
jdk:
- oraclejdk8
script:
- mvn clean org.jacoco:jacoco-maven-plugin:prepare-agent package sonar:sonar
cache:
directories:
- '$HOME/.m2/repository'
- '$HOME/.sonar/cache'
Remember to substitute your organization key with the organization key described above. Committing the new code and pushing to Github repo will trigger Travis CI build and in turn activate the sonar scanning as well.
记得用上述的组织密钥替换你的组织密钥。提交新代码并推送到Github repo将触发Travis CI构建,并反过来激活声纳扫描。
6. Conclusion
6.结论
In this tutorial, we’ve looked at how to set up a SonarQube server locally and how to use Quality Gate to define the criteria for the fitness of a project for production release.
在本教程中,我们已经了解了如何在本地设置SonarQube服务器,以及如何使用质量门来定义一个项目适合生产发布的标准。
The SonarQube documentation has more information about other aspects of the platform.
SonarQube文档中有更多关于平台其他方面的信息。