SonarQube tutorial – Part I: How to Get Started?

Have you heard about SonarQube before? Do you want to know how to use it and what kind of value it can bring to the software development process?

You’re in a right place! We’ve prepared a series of 5 articles which will make dealing with SonarQube much easier.

  1. SonarQube – introduction (you’re here!)
  2. SonarScanner tutorial 
  3. SonarScanner for MSBuild tutorial 
  4. Rules, quality profiles and quality gates 
  5. Gitlab integration tutorial

 

So let’s get started! First of all – what is SonarQube?

SonarQube is an open source platform to perform automatic reviews with static analysis of code to detect bugs, code smells and security vulnerabilities on 25+ programming languages

SonarQube.org

SonarQube is a very universal tool for static code analysis that has become more or less the industry standard. Because it is covering the most popular programming languages, it’s the most complex solution that covers most use cases using a single application. This allows you to not use a separate app for every programming language that has to be analyzed.

 

What kind of value SonarQube brings

It helps to catch a lot of problems in code and thanks to its philosophy to focus on the new code it helps to fix issues as soon as they appear.

Keeping code clean, simple and easy to read is also a lot easier with SonarQube since a lot of rules also focus on those aspects which starts to pay off a lot after some time.

A lot more detailed feature descriptions that are widely used are described on the official SonarQube page and there is no point in duplicating them here.

 

What is this series of tutorials about?

The main goal of this tutorial is to show how to configure SonarQube scanners for both .NET example projects and JS example projects. SonarQube is used here as a Docker Image for demonstration purposes and should not be used in this configuration in production.

The reason for creating a custom image that is used to execute SonarQube analysis is to make sonar scanner syntax easier to read and modify during this tutorial than running it as the console commands.

 

Technical requirements

Docker – https://www.docker.com/get-started

Git – https://git-scm.com/downloads

 

First steps

Setup SonarQube

1. Run SonarQube server

docker run -d --name sonarqube -p 9000:9000 sonarqube:7.5-community

 

2. Run docker ps and check if a server is up and running

docker image

 

3. Wait for the server to start and log in to SonarQube server on http://localhost:9000 using default credentials: login: admin password: admin

4. Go to: http://localhost:9000/account/security/ and generate a token.

tokens image

 

5. Copy token value and save it somewhere, since you won’t be able to see it again! You will need it later in the tutorial.

6. Create a new folder for SonarQube scanner image dockerfile. Run mkdir sonarqube-scanner

7. Run cd sonarqube-scanner

8. Create dockerfile

9. Open created Dockerfile and paste the code below:

sonarqube-scanner dockerfile (click here to open)
# This is docker file for our sonarqube-scanner. You don't need to read it since
# the goal of this tutorial isn't about teaching docker or about presenting the best 
# way for creating Sonarqube scanner image. Of course feel free to check on it if you like.
# Get dotnetcore SDK
FROM microsoft/dotnet:2.2.104-sdk AS sonarqube

# Install OpenJDK-8
RUN apt-get update && \
    apt-get install -y openjdk-8-jdk && \
    apt-get install -y ant && \
    apt-get clean;

# Fix certificate issues
RUN apt-get update && \
    apt-get install ca-certificates-java && \
    apt-get clean && \
    update-ca-certificates -f;

# Setup JAVA_HOME
ENV JAVA_HOME /usr/lib/jvm/java-8-openjdk-amd64/
RUN export JAVA_HOM

# Env variables
ENV NODE_VERSION 10.13.0
ENV NODE_DOWNLOAD_SHA b4b5d8f73148dcf277df413bb16827be476f4fa117cbbec2aaabc8cc0a8588e1

# Install node.js
RUN curl -SL "https://nodejs.org/dist/v${NODE_VERSION}/node-v${NODE_VERSION}-linux-x64.tar.gz" --output nodejs.tar.gz \
    && echo "$NODE_DOWNLOAD_SHA nodejs.tar.gz" | sha256sum -c - \
    && tar -xzf "nodejs.tar.gz" -C /usr/local --strip-components=1 \
    && rm nodejs.tar.gz \
    && ln -s /usr/local/bin/node /usr/local/bin/nodejs

# Install global tools
RUN dotnet tool install -g dotnetsay
RUN dotnet tool install --global dotnet-sonarscanner --version 4.5.0

# Add global tools folder to PATH
ENV PATH="${PATH}:/root/.dotnet/tools"

# Get required packages for sonar scanner
RUN apt-get update && apt-get -y install curl bash unzip yarn bzip2

WORKDIR /root

ENV LATEST='sonar-scanner-cli-3.3.0.1492-linux.zip'

# Get & install sonar scanner
RUN env && \
curl -OL 'https://binaries.sonarsource.com/Distribution/sonar-scanner-cli/'$LATEST && \
mkdir sonar_scanner && unzip -d sonar_scanner $LATEST && mv sonar_scanner/* sonar_home && \
rm -rf sonar_scanner $LATEST

# Add sonar scanner to PATH
ENV SONAR_RUNNER_HOME=/root/sonar_home
ENV PATH ${SONAR_RUNNER_HOME}/bin:$PATH

ARG SONAR_HOST
ARG SONAR_LOGIN_TOKEN

# make temporary folder for seed analysis for javascript scanner
WORKDIR /root/temp1
RUN mkdir src
RUN touch src/test.js
# Init sonarscanner cache with plugins
RUN sonar-scanner -Dsonar.host.url=$SONAR_HOST -Dsonar.login=$SONAR_LOGIN_TOKEN -Dsonar.analysis.mode=preview -Dsonar.projectKey="pluginsSeedJS" -Dsonar.sources="src"

WORKDIR /root

# Remove temporary folder
RUN rm /root/temp1 -rf

# make temporary folder for seed analysis
WORKDIR /root/temp2
# Init sonarscanner cache with plugins for .NET scanner
RUN dotnet sonarscanner begin /k:"pluginsSeedNET" /d:sonar.host.url=$SONAR_HOST /d:sonar.login=$SONAR_LOGIN_TOKEN /d:sonar.analysis.mode=preview
RUN dotnet new sln --name FooBar
RUN dotnet new mvc --name Foo --output Foo
RUN dotnet new console --name Bar --output Bar
RUN dotnet sln add ./Foo/Foo.csproj
RUN dotnet sln add ./Bar/Bar.csproj
RUN dotnet restore
RUN dotnet build FooBar.sln
RUN dotnet sonarscanner end /d:sonar.login=$SONAR_LOGIN_TOKEN ; exit 0

WORKDIR /root

# Remove temporary folder
RUN rm /root/temp2 -rf

 

10. Build sonarqube-scanner image by executing following command in a console in sonarqube-scanner directory:

docker build --network=host --tag sonar-scanner-image:latest --build-arg SONAR_HOST="http://localhost:9000" --build-arg SONAR_LOGIN_TOKEN="TOKEN_VALUE" .

Remember to replace “TOKEN_VALUE” with your token from point 4.

Setup example project
  1. Run cd ..
  2. Run git clone https://github.com/SetappPL/react-starter-kit.git
  3. Run cd react-starter-kit
  4. Add following .dockerignore file to the root directory:
.dockerignore
.vs
node_modules

5. Open Dockerfile and replace it with the following code:

# It is our freshly build sonar-scanner-image from previous steps that
# is used here as a base image in docker file that we will be working on
FROM sonar-scanner-image:latest AS sonarqube_scan

# Here we are setting up a working directory to /app. It is like using `cd app` command
WORKDIR /app

# Copying all files from the project directory to our current location (/app) in image
# except patterns mention in .dockerignore
COPY . .

# Execution of example command. Here it is used to show a list of files and directories.
# It will be useful in later exercises in this tutorial. 
RUN ls -list

# To execute sonar-scanner we just need to run "sonar-scanner" in the image. 
# To pass Sonarqube parameter we need to add "-D"prefix to each as in the example below
# sonar.host.url is property used to define URL of Sonarqube server
# sonar.projectKey is used to define project key that will be used to distinguish it in 
# sonarqube server from other projects
# sonar.sources directory for sources of project
RUN sonar-scanner \
    -Dsonar.host.url="http://localhost:9000" \
    -Dsonar.projectKey="SONAR_PROJECT_KEY" \
    -Dsonar.sources="src"

 

First analysis

  1. Run docker build --network=host --no-cache . in react-starter-kit directory
  2. Enter http://localhost:9000/dashboard?id=SONAR_PROJECT_KEY to see analysis results

 

A few words about SonarQube administration

SonarQube settings administration

SonarQube have three levels of settings:

  1. Server level administration under http://localhost:9000/admin/settings
  2. Project level under http://localhost:9000/project/settings?id=SONAR_PROJECT_KEY
  3. Settings passed as parameters during an analysis

Since settings at both server and project levels location aren’t versioned I usually prefer to pass settings as parameters during analysis to version them together with the code of a living project.

 

Projects management

In Projects management tab http://localhost:9000/admin/projects_management you can add new projects and edit permissions to them.

 

What next?

In the next tutorial, you are going to learn about how to configure SonarScanner to work with your projects and to suit your needs – SonarScanner tutorial.

After this, we will take a look into SonarScanner for MSBuild and check the differences between it and SonarScanner and work with its unique features – SonarScanner for MSBuild tutorial.

Then we will play a little with customization of the server rules and behaviors in analysis context in Rules, quality profiles and quality gates tutorial.

We will wrap things up with Gitlab integration tutorial, which will show us how to integrate SonarQube with pull requests.

 

Cleaning up after a tutorial

To stop a container running SonarQube server instance run the following command: (don’t do this if you want to continue with the next tutorials!)

docker container stop sonarqube

To remove also all docker containers run

docker container prune --force

Finally to remove all images used in this tutorial run

docker image remove sonarqube:7.5-community sonar-scanner-image

Want to learn more about SonarQube?
Check our next article on how to use SonarScanner!

Let's create
something meaningful together!

Company data
  • Setapp Sp. z o.o.
  • VAT ID: PL7781465185
  • REGON: 301183743
  • KRS: 0000334616
Address
  • ul. Wojskowa 6
  • 60-792 Poznań, Poland
Contact us
Stay connected