What is SonarQube? - How to Setup SonarQube in Linux?

What is SonarQube? - How to Setup SonarQube in Linux?

Maintaining good coding practice and achieving code quality underscores the primary aim of SonarQube. It helps consistently analyze the source code before forwarding it to production. 

When delivering a software project, one such factor that commonly gets compromised intentionally or unintentionally is code quality. Code duplication, potential bugs, a bad distribution of complexities, and unused methods and variables are signs of poor code quality.

Code quality affects the codebase's security, reliability, and safety and, hence, the project function. Delivering the project with clean code, less code complexity, without code duplication and any other potential bugs is always significant.

What is SonarQube?

SonarQube, or Sonar, is an open-source tool for continuous code quality that measures and analyzes the source code. It is built in Java but can analyze code in 20 diverse languages. SonarQube not only checks the code and highlights the issues but also tracks and monitors the code continuously, ensuring flawless code integration and deployment. It can display the result of the analysis in a visually appealing way using excellent charts, ‘green & red lights,’ and an issues list. Here is an example of the Sonarscanner analysis result.

Sonarscanner


Sonar incorporates the following sections of code quality:

  1. Architecture and Design
  2. Unit tests
  3. Duplicated code
  4. Potential bugs
  5. Complex code
  6. Coding standards

What does SonarQube do?

SonarQube is an open-source platform for continuous inspection of code quality. It performs static code analysis to identify and fix bugs, security vulnerabilities, code smells, and other quality issues in the source code. It provides comprehensive reports, metrics, and visualizations to help development teams and testing engineers maintain high-quality code and adhere to coding standards throughout the software development lifecycle.

Why use SonarQube?

SonarQube is a popular open-source platform designed to continuously inspect code quality to identify and fix issues early in the development process. Here are some reasons to use SonarQube:

  1. Code Quality Assurance: SonarQube helps ensure the overall quality of code by detecting and correcting various issues such as bugs, security vulnerabilities, and code smells.

  2. Continuous Inspection: It integrates seamlessly into the development workflow, allowing for continuous inspection of code, providing immediate feedback to developers.

  3. Comprehensive Analysis: SonarQube provides a comprehensive analysis of code quality, covering various aspects like code duplication, unit test coverage, and adherence to coding standards.

  4. Standardization: It promotes coding standards and best practices, leading to a more consistent and maintainable codebase.

  5. Security Scanning: SonarQube includes security analysis features to identify and rectify security vulnerabilities, making the code more robust against potential threats.

  6. Technical Debt Reduction: By identifying and addressing issues early in development, SonarQube helps in reducing technical debt, making it easier to maintain and enhance the software over time.

Steps to Setup Sonarscanner in your Linux System

Note:- To run .sh file, use bash command

  1. Run shell script file sonarscanner.sh

    Run shell script file sonarscanner.sh

  2. After that, you have to tweak some settings to persuade the scanner to work with the Linux server. To edit, open the config file:

sudo nano /opt/sonarscanner/sonar-scanner-3.2.0.1227-linux/conf/sonar-scanner.properties

  1. First, mention where you want the scanner to show the result of code analysis. Set the URL of your server on the line starting with sonar.host.url :

#----- Default SonarQube server

sonar.host.url=<Your SonarQubeserver URL>

  1. It’s time to run the sonar-scanner by passing the token:

sonar.login=<Your SonarQubeserver Token>

@sonar.login:- To get this token you have to login into URL, which you have given as host URL:

Go to My account page 

account page

Go to the security tab and generate a token by giving any name, which you like.

security tab

After that, place the generated token into the sonar.login parameter

Save and close the sonar-scanner.properties file.

  1. Run shell script file sonar-project.properties.sh to createproperties file in which project/ folder you need to run the sonar scanner:
    shell script

  2. Then, execute the script file using the command below:

bash  sonar-project.properties.sh @sonar.projectKey @sonar.projectName @sonar.projectVersion @sonar.exclusions

Substitute @variable with your original values. Avoid using any space while declaring variable values  

For example:

  • Acceptable:-  Test-key, TestKey
  • Non-Acceptable:-  Test Key

@sonar.projectKey :- This is the Unique Key for the project - To get this, go to project detail page on SonarQube

SonarQube

@sonar.projectName:-This is optional, as per your project name.

@sonar.exclusions:- Folder or file name you want to exclude from the scanner.

  1. Go to the folder where you have added the sonar-project.properties file open the terminal, and run the following command: -

sonar-scanner

  • After solving bugs related to Sonarqube and again run the sonar scanner command

SonarQube Architecture:

SonarQube typically follows a client-server architecture:

  • Web Server: It hosts the SonarQube web application, providing a user interface for interacting with the analysis results.

  • Database: SonarQube uses a relational database (like PostgreSQL or MySQL) to store project configurations, metrics, and analysis results.

  • Analysis Engine: This component performs the static code analysis and sends the results to the database for storage.

  • Scanner: Developers use scanners to initiate the analysis on their codebase. This scanner sends the code to the analysis engine for processing.

Integration:

SonarQube integrates seamlessly with various build tools and continuous integration (CI) servers. Popular integrations include Jenkins, Maven, Gradle, and Azure DevOps, ensuring that code analysis becomes an integral part of the development pipeline.

Machines and Locations:

SonarQube can be hosted on-premises or in the cloud. It is compatible with various operating systems, making it flexible for deployment. The choice of machines and locations depends on factors such as the size of the codebase, the number of projects, and organizational preferences.

Use Case:

SonarQube is suitable for any software development project where maintaining code quality is crucial. It is widely used in industries such as finance, healthcare, and technology for applications ranging from web development to mobile app development.

How SonarQube version 10.3 enhancements can Benefit Businesses:

1. Clean Code & Security Enhancements:

  • Preventing Issues at the Source: SonarQube 10.3 emphasizes writing clean code from the start. By identifying and addressing potential issues at the source, businesses can reduce the risk of introducing technical debt and ensure a higher standard of code quality.

  • Clearer Code Review in Pull Requests: The simplified Clean Code attribute in Pull Requests provides a streamlined view of issues, making it easier for developers to understand and address potential code cleanliness issues before merging changes. This leads to more efficient code reviews and improved collaboration within development teams.

  • Consistent Clean Code Taxonomy: The Clean Code Taxonomy updates ensure a consistent and intentional approach to writing code. This framework helps in maintaining code that is not only reliable and secure but also adaptable and responsible, aligning with industry best practices.

  • Automated Quality Profile Updates: The automatic propagation of Clean Code Taxonomy updates to all projects and issues ensures that businesses can consistently apply the latest code quality standards across their entire codebase. This feature is particularly valuable for maintaining historical code and ensuring ongoing adherence to best practices.

  • Efficient Quality Profile Inheritance: The ability to exclude undesired rules when inheriting a Quality Profile provides flexibility without sacrificing the benefits of inheritance. This allows teams to customize their code quality rules while still leveraging the latest updates from SonarQube, streamlining the development process.

2. Clean as You Code Improvements:

  • Reducing Technical Debt: The Clean as You Code methodology addresses the challenge of fixing technical debt in legacy code by ensuring that all newly developed code is clean and issue-free. This approach not only prevents the introduction of new technical debt but also gradually improves the cleanliness of legacy code over time.

  • Rigorous Quality Gate Criteria: The adoption of a zero-issues policy in the Sonar way Quality Gate sets a high standard for newly written and modified code. This ensures that businesses maintain a consistently high level of clean code, reducing the long-term burden of technical debt and enhancing the overall quality of their software.

Enhanced Security Capabilities:

  • Advanced Secrets Detection: SonarQube 10.3 introduces a comprehensive secrets detection engine, identifying and preventing sensitive information from entering the codebase. This not only strengthens security but also aligns with best practices for protecting proprietary and confidential data.

  • Risk Assessment: The inclusion of the new 2023 CWE Top 25 Report enables businesses to assess the security risk of their codebase more effectively. This proactive approach helps prioritize and address security vulnerabilities, reducing the likelihood of security breaches and safeguarding sensitive data.

  • Synchronization with GitLab Vulnerability Report: The seamless synchronization of issue statuses between SonarQube and GitLab enhances the overall security posture. This ensures that security issues are consistently managed and tracked, reducing the risk of overlooking critical vulnerabilities.

3. Language Updates & Data Science Support:

  • Wider Language Support: The expanded support for languages such as React, Jakarta, Spring Boot, .NET 8, C# 12, NumPy, and Pandas ensures that businesses can use the latest language features and frameworks. This support is crucial for staying current with technology trends and building robust, up-to-date software solutions.

  • Data Science Libraries Support: For businesses involved in data science and machine learning, the new rules supporting NumPy and Pandas in Python are valuable. This support aligns with the growing importance of data science in various industries, providing developers with the tools to write clean and efficient code in this domain.

4. Operational & UI Improvements:

  • Efficient Onboarding: The easy onboarding features, including automated GitHub project provisioning and team synchronization, streamline the setup process. This allows teams to start using SonarQube more quickly and ensures consistency between GitHub and SonarQube configurations.

  • Upgrade Change Messaging: The clear communication of changes in analysis results post-upgrade helps businesses understand the impact of updates. This transparency ensures that development teams can seamlessly adapt to the latest code quality standards.

  • Modern User Interface: The updated UI across various pages enhances the user experience and aligns with modern design principles. This contributes to a more intuitive and visually appealing developer environment, promoting productivity and ease of use.

SonarQube 10.3 version enhancements benefit businesses by promoting a clean and secure code culture, streamlining development workflows, and providing robust tools for managing code quality and security. These improvements contribute to long-term efficiency, reduced technical debt, and enhanced software quality.

Features and Advantages of SonarQube:

  • Code Smell Detection: Identifies and rectifies code smells, indicating potential code problems.

  • Security Vulnerability Detection: Offers security scanning to find and fix vulnerabilities in the code.

  • Duplication Detection: Identifies duplicated code, helping to reduce redundancy and improve maintainability.

  • Customizable Quality Profiles: Allows coding rules and quality profile customization based on project-specific requirements.

  • Integration with IDEs: Integrates with popular Integrated Development Environments (IDEs) to provide real-time feedback to developers during coding.

  • Historical Analysis: Maintains a history of code quality metrics, allowing for trend analysis and continuous improvement.

Role of SonarQube in Software Testing:

SonarQube plays a crucial role in software testing by focusing on static code complexity analysis and providing insights into the overall quality of the codebase. Its primary functions in software testing include:

Static Code Analysis:

SonarQube performs static code analysis, examining the source code without executing it. It identifies potential bugs, security vulnerabilities, code smells, and other issues early in the development process. This helps in managing and reducing code complexity throughout the software development lifecycle.

Code Quality Metrics:

SonarQube measures code quality metrics such as code complexity, maintainability, and test coverage. These metrics offer a quantitative assessment of the code's quality and help teams prioritize improvement areas. The tool provides valuable insights into how programming languages like JavaScript and TypeScript contribute to overall code quality.

Automated Code Review:

By automating the code review process, SonarQube ensures consistent and objective evaluations. It enforces coding standards and best practices, reducing the likelihood of introducing errors and maintaining a uniform code style across the development team. This helps in addressing and preventing issues related to code complexity in JavaScript and TypeScript.

Security Vulnerability Detection:

SonarQube includes security-focused analyzers that can identify and report security vulnerabilities in the code. This is crucial for ensuring that the software is resistant to common security threats and adheres to secure coding practices. It also addresses potential vulnerabilities related to the programming languages used, such as JavaScript and TypeScript.

Technical Debt Management:

SonarQube calculates and reports technical debt, representing the effort required to address existing code issues. This information helps teams prioritize and plan code improvements, balancing the need for rapid development with the necessity of maintaining a sustainable codebase. Reducing technical debt is essential for mitigating challenges related to code complexity and enhancing overall code quality.

Integration with CI/CD Pipelines:

SonarQube integrates seamlessly into continuous integration and deployment (CI/CD) pipelines. This integration allows teams to automatically trigger code complexity analysis and receive feedback on code quality and issues as part of their development workflow. This ensures that issues related to programming languages like JavaScript and TypeScript are addressed early in the pipeline.

Quality Gates:

Quality gates in SonarQube allow teams to define criteria that must be met for code to be considered acceptable. This ensures that only high-quality, compliant code progresses through the development pipeline, reducing the likelihood of defects reaching production. It acts as a safeguard against issues stemming from high code complexity in JavaScript, TypeScript, and other programming languages.

Custom Rules and Profiles:

SonarQube allows teams to define custom coding rules and quality profiles to adapt the analysis to specific project requirements and industry standards. This flexibility ensures that the tool can be tailored to the unique needs of different software projects, considering the specific characteristics of programming languages like JavaScript and TypeScript.

Continuous Monitoring:

Beyond initial code analysis, SonarQube supports continuous monitoring of code quality. This means that teams can track changes in code quality over time and address emerging issues as the codebase evolves. Continuous monitoring is crucial for maintaining consistent quality standards, especially when dealing with the evolving nature of programming languages like JavaScript and TypeScript.

SonarQube Test Coverage:

SonarQube includes features for tracking and reporting on code coverage, which measures how much of your code is executed during testing. It helps identify untested or under-tested portions of your code, allowing teams to improve test coverage and ensure comprehensive application testing.

Install SonarQube on Ubuntu:

To install SonarQube on Ubuntu, you can follow these general steps:

  1. Ensure you have Java installed.
  2. Download and unzip the SonarQube distribution.
  3. Configure the database settings in the sonar.properties file.
  4. Start the SonarQube server.

For detailed, up-to-date instructions, refer to the official SonarQube installation guide.

How to Run SonarQube Locally:

Running SonarQube locally involves downloading the distribution, configuring it to connect to a local database, and starting the SonarQube server. Developers can then access the SonarQube web interface to perform code analysis and view reports. It's important to have Java installed, and database configuration is typically done in the sonar.properties file.

SonarQube Supported Languages:

SonarQube supports a wide range of programming languages, including but not limited to:

  • Java
  • C#
  • C/C++
  • JavaScript
  • TypeScript
  • Python
  • PHP
  • Ruby
  • Kotlin
  • Swift

The list is continually expanding, and the platform remains versatile, accommodating projects written in various languages.

Best Alternative to SonarQube:

Fortify vs. SonarQube:

Fortify and SonarQube serve different purposes in the software development lifecycle. Fortify, developed by Micro Focus, is primarily focused on dynamic application security testing (DAST) and static application security testing (SAST), emphasizing security vulnerabilities. SonarQube, on the other hand, is more broadly used for continuous code quality inspection, covering not only security issues but also bugs, code smells, and more.

SonarCloud vs. SonarQube:

SonarCloud is a cloud-based service provided by SonarSource that offers the same functionality as SonarQube. The key difference lies in deployment: SonarCloud is hosted and managed by SonarSource, while SonarQube is typically self-hosted on-premises or in a private cloud. Both tools provide static code analysis and help maintain code quality.

Unknown Fact: SonarCloud seamlessly integrates with popular code repository platforms such as GitHub and Bitbucket, allowing for automatic code analysis on every pull request.

SonarLint vs. SonarQube:

SonarLint is a lightweight extension for popular Integrated Development Environments (IDEs) that brings SonarQube's static code analysis capabilities directly into the developer's local environment. While SonarQube is used for centralized code quality management, SonarLint operates at the developer's desktop, providing real-time feedback on code quality issues as code is being written.

Conclusion:

In conclusion, SonarQube is a powerful tool for ensuring code quality throughout the development lifecycle, and SonarCloud provides a cloud-based alternative with easy integration into modern development workflows.

Empower your code with SonarQube's advanced static code analysis – ensuring robust software quality and security. Elevate your software testing and QA game and embrace excellence in software development with SonarQube today!

Author

Talk To Our Experts