During the development phase of a project, there are some common measures you’d typically take to ensure your code is at industrial standard. These steps include checking if it’s secure or contains not-so-obvious vulnerabilities and ensuring it’s easily compatible with other code.
You can take these steps manually through peer review and other processes. However, this method could lead to more problems or unresolved issues. Automating this procedure will be the best approach for your team, and you can achieve this using static code analysis tools.
Static code analysis tools allow you to analyze your source code without running it. They examine the code for potential issues, vulnerabilities, or violations of coding standards. Some examples of these tools include Coverity, CodeScene, veracode and the focus of this article, SonarQube.
This article lets you understand SonarQube, its features, and why you need it for your project. You’ll get to install SonarQube and have a quick overview of its console. By the end of this article, you’ll gain more confidence in the quality of your code.
Understanding SonarQube
SonarQube is an open-source static code analysis tool. It allows you to continuously monitor, analyze, and improve your code. After your code analysis, SonarQube provides a report with the results.
This report provides detailed metrics to help you understand and improve the quality of your codebase over time. Additionally, it offers recommendations to improve your codebase.
SonarQube is an overall quality management tool. This means it not only does code analysis but also code coverage and a report-generating system for any test you carry out, like unit tests.
Although it’s a Java-based tool, it’s not limited to Java. It can analyze 30+ programming languages and infrastructure as code (IaC) platforms.
SonarQube offers you two key features. The first is the Quality Gate, and the second is the Customizable Ruleset. Quality Gates in SonarQube act as checkpoints in your CI/CD pipeline, ensuring that your code meets predefined quality criteria before it can be merged into the main branch or deployed.
Customizable Rulesets in SonarQube allow you to define specific coding rules and standards tailored to your project’s requirements and guidelines. SonarQube uses these rules during static code analysis to identify issues such as bugs, code smells, and security vulnerabilities.
Why You Need SonarQube
If you understood the section above, you’ll notice that SonarQube offers you so much. Well, that’s just a bit of what you can do with this tool. The following are some reasons why you should use SonarQube:
– Cost savings: No organization loves to waste money. By identifying and fixing issues early in the development cycle, SonarQube can help reduce the cost of software maintenance and support over time.
– Easy CI/CD integration: SonarQube integrates seamlessly with CI/CD pipelines, allowing you to automate code analysis as part of your development workflow. This helps catch issues early and ensures that only quality code is merged and deployed.
– Confidence in your code quality: If your project needs to adhere to specific coding standards, industry regulations, or security requirements, SonarQube can help enforce these standards, making you more confident about the quality of your codebase.
– Security Assurance: With its built-in security hotspots feature, SonarQube helps identify and mitigate security risks in your codebase, protecting your software from potential threats and attacks.
Setting Up SonarQube
There are several ways to set up a SonarQube server. One is downloading the zip file from the SonarQube website. The other uses the community edition Docker image. In this tutorial, you’ll be using the latter.
Prerequisites
To install the SonarQube server, ensure you have Docker installed on your machine. Aside from that, you need the following hardware and software requirements:
- At least 4GB of RAM for small-scale installations and 16GB of RAM for large ones.
- You’ll need a 64-bit operating system with at least two cores for small-scale installations and eight for large ones.
- At least 30GB of disk space for small-scale installations
- You’ll need a web browser to access the SonarQube web interface.
For a complete list of hardware and software requirements, please refer to the SonarQube installation requirements page.
The following steps will guide you in installing the SonarQube server using Docker. This method is more straightforward to set up, and you won’t need to install any additional software like Java.
Step 1: Run the Docker image
Once you have installed Docker on your machine, you can run the Docker image on your command line.
docker run -d --name sonarqube -e SONAR_ES_BOOTSTRAP_CHECKS_DISABLE=true -p 9000:9000 sonarqube:latest
This command pulls and runs the latest version of SonarQube on your machine. You can confirm that it’s running by checking the Docker status.
Step 2: Access the SonarQube web interface
After the installation, it takes a few minutes for the SonarQube server to start. Once it starts, you can access the SonarQube web interface at http://localhost:9000
.
Step 3: Configure SonarQube
You’ll be prompted to set a login and password for the SonarQube server. The default login and password is admin
for both.
You’ll be prompted to change the default password once you’ve logged in using the default credentials.
Input the new password and confirm it. Once you’re done, you can reaccess the SonarQube web interface.
Quick Overview of the SonarQube Console
To have a good overview of the console, we’ll set up project and analyze it using SonarQube.
Step 1: Select the project source
You can create a new project using the Projects section of the SonarQube console. This section determines where the project source is located. This can be on your local machine or a remote repository like GitHub or GitLab.
In this guide, you’ll create a local project. To do that, go to the Projects section of the SonarQube console and click Create a local project.
Step 2: Add project description
After selecting the local project, you will be prompted to provide a Project display name, Project key and Main branch name. The project display name and project key are used to identify the project in the SonarQube console.
The Main branch name is the name of the main branch in the project. The default value is main
.
Step 3: Setup Clean as You Code
Clean as You Code (CaYC) is a SonarQube methodology for software development that allows you to take responsibility for the quality of the code you produce, mainly focusing on the new code that you’re adding or modifying.
In this approach, you’ll aim to write clean, readable, and maintainable code from the beginning rather than postponing cleanup or refactoring to a later time.
You’ll be prompted to select your Clean as You Code option. You have the following options:
- Previous Version: Considers any code that has changed since the project’s most recent version.
- Number of Days: Specifies a floating new code period based on a specified number of days.
- Reference Branch: Considers changes made between your branch and a specific reference branch as new code.
For this example, we’ll choose Previous Version.
After this, click on Create project, and SonarQube will create your project in the console.
Step 4: Select Analysis Method
After the project is created, you’ll be prompted to select the Analysis method. The Analysis method lets you specify how you want to analyze your code.
The options are CI/CD tools such as GitHub Actions, Jenkins, SemaphoreCI, etc. For this example, we’ll choose Locally.
Step 5: Set up a project token
You’ll be prompted to enter a Project token. This token is used to authenticate with SonarQube. This token will notify you when you perform an analysis.
Add the project name and click the Generate button to generate the token.
After which, you can copy this token and click the Continue button.
Step 6: Run analysis on the project
After creating the token, you can now analyze the project. You’ll need to select the format that best fits your build. This can be either Maven, Gradle or for any programming language like JS, Python, Go, etc.
After which, you’ll need to download the SonarQube Scanner to your local machine — it, in turn, will be running against the SonarQube server we’re running via docker at http://localhost:9000
. The SonarQube Scanner is a tool that automatically runs analysis on your code. You can download the SonarQube Scanner from the SonarQube Scanner download page.
You’ll need to configure your project once you’ve downloaded the SonarQube Scanner that fits your OS and architecture.
NOTE: There is no support for the ARM64 architecture. To bypass this, install the JRE and choose the Any option on the installation page.
In the root directory of your project, create a sonar-project.properties
file and add the following properties:
# must be unique in a given SonarQube instance
sonar.projectKey=Test-project
# --- optional properties ---# defaults to project key
#sonar.projectName=My project
# defaults to 'not provided'
#sonar.projectVersion=1.0
# Path is relative to the sonar-project.properties file. Defaults to.
#sonar.sources=.
# Encoding of the source code. Default is default system encoding
sonar.sourceEncoding=UTF-8
Replace the sonar.projectKey
with your project key.
After this, on your SonarQube console, you’ll see a prefilled sonar-scanner
command containing your project details. This command should look like this:
sonar-scanner \
-Dsonar.projectKey=Test-project \
-Dsonar.sources=. \
-Dsonar.host.url=http://localhost:9000 \
-Dsonar.token=sqp_448617bdbf2dd550b03fbfffcae92b9011e6f35b
Copy the command, navigate to your project directory via the command line and run it.
Once your execution is successful, as in the image above, switch back to the console. You should now see the analysis results in the SonarQube console.
NOTE: The project used for this tutorial is a local JavaScript project. You can use any project of your choice, but if you prefer, you can clone this one on GitHub. Since it’s a JavaScript project, you’ll need Node Js installed on your machine for the Sonar scanner to work.
Step 7: Analyze the Report
Once you get back to the console, you’ll see your analysis report. This report is quite detailed and can get confusing, so let’s go through each section.
This page contains overall information about the project. On this page, you can see whether your scan succeeded or failed. You can also find the scores of each metric.
These metrics are security, reliability, maintainability, hotspots, coverage and duplications. Scrolling down the page will give you more details, like the size and languages used in the project.
In the issues section, you can see the issues that were found in every file of your project. Under each file, you can find the year the file was created and assign an open issue to a team member.
The rules section, as the name implies, contains rules that are used to identify security issues. They are categorized into four types: code smell, bug, vulnerability, and security hotspot.
Each type has specific expectations, such as zero false positives for bugs and code smells and more than 80% true positives for vulnerabilities. Rules can be filtered by language, type, tag, repository, severity, status, etc.
A quality profile defines the rules and configurations you can apply during code analysis for a specific programming language. It determines the coding standards, best practices, potential bugs, security vulnerabilities, and code smells checked for in the codebase.
You can customize or extend a quality profile to meet your project’s requirements so the quality of your code is consistent across projects.
A quality gate allows you to define a set of conditions that must be met before a project can be released. They define criteria like bug counts or code coverage.
The default quality gate is “Sonar way”; however, you can create your own. Permissions ensure that only authorized users can edit or manage quality gates. Only users with global administration permissions can modify quality gates by default, but this permission can be delegated to specific experts or groups for individual gates.
The administration section allows you to configure your console. Here, you can authenticate with DevOps platforms like GitLab, GitHub, etc.
You can also set general rules concerning your project creation, quality profiles, and the Look & feel of your console.
Conclusion
In this article, you learnt how to analyze a project using SonarQube. In the process, you understood how to use this tool, installed the SonarQube server, and had a quick overview of the console.
All this information might be confusing initially; however, once you master the console, maintaining clean, secure and reusable code will be easy.
Once you’ve gotten the hang of this, you should look out for the next article, in which we’ll go through how to integrate SonarQube into your Semaphore CI pipeline.
Originally published at https://semaphoreci.com on June 19, 2024.