Welcome toTencent Cloud + community, get more Tencent mass technology practice dry goods oh ~

This article is from the Cloud Computing tutorial series, compiled by Running Fast in Shoes.

introduce

Code quality is an approximation of the usefulness and maintainability of a particular piece of code. Quality code makes the task of maintaining and extending the application much easier. It helps ensure that fewer bugs are introduced when necessary changes are made in the future.

SonarQube is an open source tool that helps with code quality analysis and reporting. It scans the user’s source code for potential errors, vulnerabilities, and maintainability issues, and then displays the results in a report that makes it easier for users to identify potential problems in their applications.

The SonarQube tool consists of two sub-applications: an analysis engine, which is installed on the developer’s machine, and a centralized server for record keeping and reporting. A single SonarQube server instance can support multiple scanners, allowing users to centralize code quality reports from many developers.

In this tutorial, users configure the SonarQube server and scanner to analyze and create code and quality reports. The SonarQube tool can then be used to scan the machine and test the user’s machine.

To prepare

Before you start reading this tutorial, you need to follow the following:

  • One is set up and ready to usesudoNon-root account of the command,The memory is 2GB or moreUGBntu 16.04The serverAnd the firewall has been enabled. Those of you who don’t have a server canHere to buyBut I personally recommend itfreeTencent cloudDeveloper labConduct trials and learn to install afterBuying a server.
  • To install Oracle Java 8 on the server, see How to Install Java on Ubuntu 18.04.
  • To configure Nginx and MySQL, refer to Setting up web Server on CVM (LNMP).
  • To configure SSL certificates for Nginx, see How to Use SSL to protect Nginx on Ubuntu.
  • When A user installs SonarQube’s server, there is A fully qualified domain name and an A record. We will use them throughout this tutorialsonarqube.example.com.

Step 1 – Prepare for installation

Before we can install SonarQube, we need to perform several steps. Because SonarQube is a Java application that will run as a service, and because running the service as root is definitely not ideal, we will create another system user specifically to run the SonarQube service. Then we will create the installation directory and set its permissions and create a MySQL database and user for SonarQube.

First, create a Sonarqube user:

$ sudo adduser --system --no-create-home --group --disabled-login sonarqube
Copy the code

We will only use this user to run the SonarQube service, so we create a system user that cannot log directly into the server.

Next, create a directory to save SonarQube files:

$ sudo mkdir /opt/sonarqube
Copy the code

After creating a directory, update permissions so that users can read and write files in the directory:

$ sudo chown -R sonarqube:sonarqube /opt/sonarqube
Copy the code

SonarQube versions are packaged in a compressed format, so unzip installs the utility using the user’s package manager so that the user can extract the distribution files:

$ sudo apt-get install unzip
Copy the code

Next, we need to create the database and credentials to use for SonarQube. Log in to the MySQL server as user root:

$ mysql -u root -p
Copy the code

Create SonarQube database:

mysql> CREATE DATABASE sonarqube;
mysql> EXIT;
Copy the code

Create the credentials SonarQube uses to access the database.

mysql> CREATE USER sonarqube@'localhost' IDENTIFIED BY 'some_secure_password';
mysql> GRANT ALL ON sonarqube.* to sonarqube@'localhost';
Copy the code

Grant permissions so that newly created users can change the SonarQube database:

mysql> GRANT ALL ON sonarqube.* to sonarqube@'localhost';
Copy the code

Then change the application permissions and exit MySQL console:

mysql> FLUSH PRIVILEGES;
mysql> EXIT;
Copy the code

When we have users and directories, we can download and install SonarQube.

Step 2 – Download and install SonarQube

First change the current working directory to the SonarQube installation directory:

$ cd /opt/sonarqube
Copy the code

Then, go to the SonarQube Download page and get the download link for SonarQube 7.0. There are two versions of SonarQube available for download on the page, but for this particular tutorial we will be using SonarQube 7.0.

After obtaining the link, download the file:

$sudo wget HTTP: / / https://sonarsource.bintray.com/Distribution/sonarqube/sonarqube-7.0.zipCopy the code

Then unzip the file:

$sudo unzip sonarqube - 7.0. ZipCopy the code

After unzipping the file, delete the downloaded zip file because you no longer need it:

$sudo rm sonarqube - 7.0. ZipCopy the code

When all the files are in place, SonarQube can be configured.

Step 3 – Configure the SonarQube server

We need to edit something in the SonarQube configuration file. That is:

  • We need to specify the SonarQube server username and password for the database connection.
  • We also need to tell SonarQube to use MySQL for our back-end database.
  • We will tell SonarQube to run in server mode to improve performance.
  • We will also tell SonarQube to listen only to local network addresses because we will be using a reverse proxy.

First open the SonarQube configuration file:

$sudo nano sonarqube - 7.0 / conf/sonar. PropertiesCopy the code

Change the username and password SonarQube uses to access the database to the username and password created by the user in MySQL:

. sonar.jdbc.username=sonarqube sonar.jdbc.password=some_secure_password ...Copy the code

SonarQube is then told to use MySQL as the database driver:

. sonar.jdbc.url=jdbc:mysql://localhost:3306/sonarqube? useUnicode=true&characterEncoding=utf8&rewriteBatchedStatements=true&useConfigs=maxPerformance&useSSL=false.Copy the code

Finally, tell SonarQube to run in server mode and listen only to local addresses:

. Sonar. Web. Host = 127.0.0.1 sonar. Web. JavaAdditionalOpts = - serverCopy the code

After updating these fields, save and close the file.

Next, we configure the SonarQube server to run as a service so that it starts automatically when the server restarts.

Create service file:

$ sudo nano /etc/systemd/system/sonarqube.service
Copy the code

Add the following to the file that specifies how the SonarQube service should be started and stopped:

[Unit] Description=SonarQube service After=syslog.target network.target [Service] Type=forking ExecStart = / opt/sonarqube/sonarqube - 7.0 / bin/Linux x86-64 / sonar. Sh start ExecStop=/opt/sonarqube/sonarqube-7.0/bin/linux-x86-64/sonar. Sh stop User=sonarqube Group=sonarqube Restart=always [Install] WantedBy=multi-user.targetCopy the code

Close and save the file, then start the SonarQube service:

$ sudo service sonarqube start
Copy the code

Check the status of the SonarQube service to ensure it is up and running as expected:

$ service sonarqube status
Copy the code

If the service started successfully, you should see an “Active” line like this:

Low sonarqube. Service - sonarqube service the Loaded: the Loaded (/ etc/systemd/system/sonarqube. Service; enabled; vendor preset Active: active (running) since Sun 2018-03-04 01:29:44 UTC; 1 months 14 daysCopy the code

Next, configure the SonarQube service to start automatically at boot time:

$ sudo systemctl enable sonarqube
Copy the code

Like most other Java applications, SonarQube will take some time to initialize. After the initialization process is complete, you can proceed to the next step.

Step 4 – Configure the reverse proxy

Now that we have the SonarQube server running, it is time to configure Nginx, which will be the reverse proxy and HTTPS finalizer for our SonarQube instance.

Start by creating a new Nginx configuration file for your site:

$ sudo nano /etc/nginx/sites-enabled/sonarqube
Copy the code

Add this configuration so that Nginx can route incoming traffic to SonarQube:

server { listen 80; server_name sonarqube.example.com; Location / {proxy_pass http://127.0.0.1:9000; }}Copy the code

Save and close the file.

Next, make sure your configuration file doesn’t have any syntax errors:

$ sudo nginx -t
Copy the code

If you see errors, fix them and run the sudo nginx -t command again. Once there are no errors, restart Nginx:

$ sudo service nginx restart
Copy the code

For a quick test, can be in the browser to http://sonarqube.example.com. When opened, you will see the SonarQube interface greeting.

Now that we have finished setting up the reverse proxy, we can proceed to secure our SonarQube server.

Step 5 – Protect SonarQube

SonarQube comes with a default administrator username and password administrator. This default password is not secure, so we want to update it to a more secure security practice.

First access the URL for the installation, then log in using the default credentials.

After login, click the “** Administration” ** TAB, select “Security” from the drop down list, and then select “User” :

Here, click the pinion to the right of the Administrator account line, and then click Change Password. Make sure you change your password to something easy to remember but hard to guess.

Now create a normal user that you can use to create projects and submit analysis results to the server from the same page. Click the “Create User” button in the upper right corner of the page:

You then create a tag for a specific user by clicking the button in the Tag column and specifying a name for the tag. This token is needed later when the code scanner is called, so be sure to write it in a safe place.

Finally, you may notice that SonarQube instances are open to the world, and anyone can view the analysis results and source code. This setting is very insecure, so we configure SonarQube to allow only logged-in users to access the interface. On the same administration TAB, click Configure, and then click Security in the left pane. Flip the switch on this page to require user authentication.

Now that we’ve finished setting up the server, let’s set up the scanner.

Step 6 – Set up the code scanner

SonarQube’s code scanner is a separate package that you can install ona different computer than the one running the SonarQube server, such as a local development workstation or continuous delivery server.

In this tutorial, we will install the code scanner on the same server that hosts the SonarQube server.

First create a directory for the scanner and switch to a new directory:

$ sudo mkdir /opt/sonarscanner
$ cd /opt/sonarscanner
Copy the code

Then use wGET to download the SonarQube scanner for Linux:

$sudo wget HTTP: / / https://sonarsource.bintray.com/Distribution/sonar-scanner-cli/sonar-scanner-cli-3.0.3.778-linux.zipCopy the code

Unzip the scanner and then delete the ZIP archive file:

$sudo unzip sonar-scanner-cli-3.0.3.778-linux.zip $sudo rm sonar-scanner-cli-3.0.3.778-linux.zipCopy the code

After that, we need to modify some Settings to make the scanner work with the server we installed. Open the configuration file for editing:

$sudo nano sonar - scanner - 3.0.3.778 - Linux/conf/sonar - scanner. The propertiesCopy the code

First, tell the scanner where to submit code analysis results. Uncomment the line sonar.host.url at the beginning and set it to the URL of the SonarQube server:

/ opt/sonarscanner/sonar - scanner - 3.0.3.778 - Linux/conf/sonar. The properties at sonar.host.url=https://sonarqube.example.comCopy the code

Save and close the file. Now make scanner binary executable:

$sonar chmod +x sonar-scanner-3.0.3.778- Linux /bin/sonar-scannerCopy the code

Then create a symbolic link so that the user can call the scanner without specifying a path:

$ sudo ln -s/ opt/sonarscanner/sonar - scanner - 3.0.3.778 - Linux/bin/sonar - scanner/usr /local/bin/sonar-scanner
Copy the code

With the scanner set up, we are ready to run our first code scan.

Step 7 – Run the test scan

Create a new working directory in your home directory and switch to that directory:

$ cd ~
$ mkdir sonar-test && cd sonar-test
Copy the code

Download the sample project:

$ wget https://github.com/SonarSource/sonar-scanning-examples/archive/master.zip
Copy the code

Unzip the project and delete the archive files:

$ unzip master.zip
$ rm master.zip
Copy the code

Next, switch to the sample project directory:

$ cd sonar-scanning-examples-master/sonarqube-scanner
Copy the code

Run the scanner and pass it the token you created earlier:

$ sonar-scanner -D sonar.login=your_token_here
Copy the code

After the scan is complete, you should see something similar on the console:

INFO: the Task of total time: 9.834 s INFO: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- the INFO: EXECUTION SUCCESS INFO: ------------------------------------------------------------------------ INFO: Total time: INFO: 14.076 s Final Memory: 47 m / 112 m INFO: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --Copy the code

The report for the sample project will now be on the SonarQube dashboard, as follows:

When you have confirmed that the SonarQube server and scanner are working as expected, you can have SonarQube analyze your code.

Move the project to the server, or follow the steps in Step 6 to install and configure the SonarQube scanner on the workstation and configure it to point to the SonarQube server.

Then, in the root directory of the project, create a SonarQube configuration file:

$ nano sonar-project.properties
Copy the code

You will use this file to present SonarQube with some information about the project:

First, define the project key, which is the unique ID of the project. You can use anything you like, but this ID must be unique to SonarQube instances:

                                 sonar-project.properties
    # Unique ID for this project
    sonar.projectKey=foobar:hello-world

    ...
Copy the code

Then, specify the project name and version so SonarQube can display this information in the dashboard:

sonar-project.properties ... Sonar. ProjectName =Hello World Project sonar. ProjectVersion =1.0...Copy the code

Finally, tell SonarQube where to look for the code files. Note that this depends on the directory where the configuration file is located. Set it to the current directory:

                                   sonar-project.properties
    # Path is relative to the sonar-project.properties file. Replace "" by "/" on Windows.
    sonar.sources=.
Copy the code

Close and save the file.

You are ready to run code quality analysis on your own code. Run again

Sonar-scanner, pass your token:

$ sonar-scanner -D sonar.login=your_token_here
Copy the code

After the scan is complete, you will see a summary similar to this:

INFO: the Task of total time: 5.417 s INFO: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- the INFO: EXECUTION SUCCESS INFO: ------------------------------------------------------------------------ INFO: Total time: INFO: 9.659 s Final Memory: 39 m / 112 m INFO: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --Copy the code

The project’s code quality report will appear on the SonarQube interface.

conclusion

In this tutorial, you have set up the SonarQube server and scanner for code quality analysis. Now, just run the scan and SonarQube will tell you what problems you might have to make sure the code is easy to maintain!

Use SonarQube maintenance code quality at the same time, data security is very important also, if your server is used in a production environment, it is recommended that you directly use relational database of cloud, the cloud relational database allows you to easily deploy in the cloud, management and extension of relational database, provide safe and reliable, scalable and flexible on-demand cloud database service. Tencent Cloud relational database provides MySQL, SQL Server, MariaDB, PostgreSQL database engines, and has optimized the performance of database engines. Cloud relational database is a highly available hosting service that provides a full range of database operation and maintenance solutions such as disaster recovery, backup, recovery, monitoring, and migration. It frees you from time-consuming database management tasks and allows you to focus more time on your applications and services.

For more Linux tutorials, please visit Tencent Cloud + community to learn more knowledge.

Question and answer

Pros and cons of MongoDB?

reading

Redis cloud architecture is simple

Tencent cloud database file back solution

World Cup dark horse haunt, No tears in Moscow

Cloud, college courses, special recommend | tencent technology test team leader, in combination with 8 years experience in detail for you hot and cold separation principle

This article has been authorized by the author to Tencent Cloud + community, more original text pleaseClick on the

Search concern public number “cloud plus community”, the first time to obtain technical dry goods, after concern reply 1024 send you a technical course gift package!

Massive technical practice experience, all in the cloud plus community!