1. What is Sonar?
Sonar is introduced first in the middle of what, after all, I am the pursuit of perfection. Sonar is an open source code quality management platform, used to manage the quality of the source code, can check the project code vulnerabilities and potential logic problems, code quality score, health, etc., through plug-in form, can support including Java, C#, JavaScript and other more than 20 kinds of programming language code quality management and detection. Sonar can check code quality from the following seven dimensions, see other people’s blog summaries, feel the summary is in place:
- Sonar can use PMD, CheckStyle, Findbugs and other code rule detection tools to standardize code writing;
- Sonar can detect potential flaws with code rule checking tools like PMD, CheckStyle, Findbugs, etc.
- Poor complexity distribution files, classes, methods, etc. that are difficult to change if they are too complex make them difficult for developers to understand, and without automated unit testing, changes to any component of the program will likely result in the need for comprehensive regression testing;
- Duplication obviously the program contains a lot of copy-and-paste code is of low quality, Sonar can show the source code is heavily duplicated, this can guide packaging;
- Insufficient or too many comments will make the code readability worse, especially when there is inevitable staff change, the readability of the program will be greatly reduced, and too many comments will make developers spend too much energy on reading comments, which also defeats the purpose;
- The lack of unit testing Sonar makes it handy to tally up and show unit test coverage;
- Sonar can find loops, show package to package and class to class interdependencies, detect custom architecture rules, manage third-party JAR packages, use LCOM4 to detect the application of individual task rules and detect coupling.
With the concept out of the way, let’s get down to business and start installing the environment.
2. The sonar installation
2.1 Installation Preparations
First of all special attention, especially important, the version of the corresponding is particularly important, otherwise there will be a variety of pits!!
Preparations:
- JDK
- SonarQube
- sonar-scanner
- Mysql
Version related:
- SonarQube7.0 is recommended, which corresponds to JDK1.8 and Mysql5.6 or 5.7. Now the latest community release is 9.1, and obviously the JDK is adapted for version 11.
- The MysqlNote that SonarQube does not support mysql database after version 7.8, so if you want to use mysql database, choose SonarQube version 7.8 or lower.
What? Why do I need a Mysql database?
Sonar will need to upload the report to the database after analyzing the code, databasename= Sonar, so you need to create a new database named Sonar, Sonar will automatically create tables after initialization.
Mysql version requirements are available in the\ sonarqube - 7.8 \ conf \ sonar properties
You can search in the filemysql
View the supported versions as shown below:Mysql8.0 is installed by default, so SonarQube7.8 does not meet the requirements of Mysql database version. This will be reported when SonarQube7.8 is installed, Mysql8.0 is installed, and the database is configured
** The remote host forced an existing connection to close **
An error, but** Reported that the remote host force closed an existing connection **
The error is not necessarily due to the database version, which will be covered in the next article.
- About startup: You can’t use root to start the sonar service on Linux, you need to create a separate user, for example, name this user sonar, give this user full permissions on the SonarQube directory, then switch to the sonar user and start the service, Sh sonary. sh start and sh sonary. sh stop; The Sonarqube page is displayed after you access IP + port 9000 on the Web.
- Pay attention to:
Cheer up!!
Sonar will rely on Elasticsearch to start the es server. Es will be on port 9001. Check the es. You can see es error logs, high probability will be interface reported conflict, as long as the ES port in sonar. Properties can be changed, such as 9003, and then start sonar services. If you use sonar as root, you can’t use sonar as root, you can’t use sonar as root, you can’t use sonar as root, you can’t use sonar as root, you can’t use sonar as rootAbout to start
The reason why we did it.
Points to note:
1. SonarQube 7.9 requires JDK11+ installation
SonarQube 7.9 does not officially support MySQL
2.2 Preparing the Installation Environment
SonarQube builds on the environment: **Window**
(The deployment will be optimized to aliyun cloud server in the later stage)Mysql is installed into aliyun cloud server
The following software is required:
- JDK11 (Java Runtime environment, note version)
- SonarQube7.8
- Sonar-Runner (not found download source, mainly not going to use) or Sonar-Scanner (historical download address)
- Create Sonar database, I am in Ali cloud cloud server installed Mysql database, use
MySQL Yum Repository
Install, will not install Mysql in Ali cloud children shoes can refer to my other articleCentos7.6 mysql installation, has helped you step over the pit, very detailed.
Having said that, let’s start the installation.
2.3 to install the JDK
Win10 simultaneous installation using Java JDK8 and 11 two versions how to set environment variables? Win10 simultaneous installation using Java JDK8 and 11 two versions how to set environment variables
2.4 SonarQube installation
Against 2.4.1 SonarQube download
Enter thewebsiteDownload SonarQube and select community edition. Note that the latest version is 9.1, not the targetScroll down to the bottom of the page
Show all versions
Select the target version 7.8Select version installation
Download complete, local C disk create Sonar: unzip toSonar
Just unzip SonarQubeGo to sonar/bin, go to the corresponding system directory, start sonar
Open the browser and enter the URL: localhost:9000. If you can log in to the background page, the installation is successful.
Here I start the error as shown below:
Just do a random Internet search and let me
Delete all files in sonarqube Temp
Sonarqube Temp = sonarqube Temp = sonarqube Temp = Sonarqube Temp = Sonarqube Temp Then I deleted the entire Sonarqube folder, unzipped it, and booted it up again!!
First continue the following steps, time is precious, this question arises again to be explored.Pay attention to: To prevent the port from being occupied
The remote host forced an existing connection down
“, so directly change a port that may not be used
Modify the configuration sonaryssonar. properties file
The diagram below:
2.4.3. Localization
Log in. The default account is admin, and the default password is admin
Localization attention: in accordance with theOne, two, threeStep search out the Chinese plug-in is for version 9.1, sonarqube is currently the latest version, and if installedVersion 9.1
“Is not found at the end of the plugininstall
To install the button, click step 4Homepage
Go to Github and find the latest versionThe jar package
Download it and copy it to your local folderSonarQube7.8 version
“And what they found wasVersion 9.1
, version is not consistent, more to clickHomepage
, go to Github to find the correspondingJar package of version 7.8
, directly download jar package format code package, placed in\ Sonar \ sonarqube - 7.8 \ extensions \ plugins
Under the pathNote: Restart Sonar, enter CTRL C in the command window and wait for complete exit. If you close the window early, you may fail to exit. If you fail to exit, you will enter the task manager.
Kill the associated Java process
, or restart the computer and then restart SonarQube, SonarQube is the Chinese interface.
SonarQube fails if the task manager does not kill the associated Java process:
WrapperSimpleApp: Encountered an error running main: java.nio.file.FileSystemException: C:\Sonar\sonarqube-7.8\temp\ce-exploded-plugins\authgithub\META-INF\lib\gson-2.31.Jar: Another program is using this file and the process cannot access it.Copy the code
The diagram below:
Solution:
Open the task Manager and close the Java related processes
3. Configure MySQL database for SonarQube
Explain! SonarQube version 7.8 is used here
Explain! The JDK version used here is 11
Explain! The Mysql version used here is 5.7.36
3.1 Built-in Database
After the success of the Sonar installation, the default built-in H2 database, used to record a single scan results, for the same project repeat scan code, overwrite the previous scan, so the H2 database only applied to the test, can not be used in the production environment, that if you want to play, don’t want to scan your project for a long time, can don’t need to configure the database
3.2 Creating a Sonar database
At this time I have installed Mysql database in Ali cloud server, can refer to the article I wrote: Centos7.6 install Mysql create sonar database command as follows:
Sonar CREATE DATABASE`sonar`DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci; Sonar CREATE USER'sonar'@The '%' IDENTIFIED WITH mysql_native_password BY 'sonar'; Grant all permissions on sonar.* to'sonar'@The '%'; # Refresh PRIVILEGES to effect FLUSH PRIVILEGES;Copy the code
If you want to delete the sonar database, you can run all the commands again to create the sonar database. The command will be successful, but the second command will give an error message:
[Err] 1396 - Operation CREATE USER failed for 'sonar'@The '%'
Copy the code
The reason is that user sonar has been created, indicating that user sonar has been created in the mysql.user table, to create the user, you need to delete the user, as follows:
- Delete user
delete from mysql.user where user='sonar';
Copy the code
- Clear the cache
FLUSH PRIVILEGES;
Copy the code
- If an error is reported when adding the user again, execute the following statement (the possible cause is that the user has been deleted but not refreshed, or the user has been refreshed but has permission information about the user).
drop user 'test'@The '%';
Copy the code
- Create sonar User
CREATE USER 'sonar'@The '%' IDENTIFIED WITH mysql_native_password BY 'sonar';
Copy the code
- The creation succeeds.
SOnarQube 7.8 解决 mysql 解决 error: remote host forced to close an existing connection
- Whether the MySql database version is compatible with Sonar, the configuration database information file has instructions, version requirements, 5.6<= MySql <8.0
- The user name and password of the MySql database are incorrect.
- Whether a database with a name called Sonar already has the same name;
3.3 Finally, or fell on the road
Sonarqube: sonarqube: sonarqube: sonarqube: Sonarqube: Sonarqube: Sonarqube: Sonarqube: Sonarqube: Sonarqube: Sonarqube “Remote host forced to close an existing connection” solution note solution, I’m sure the selected database version is in line with the version requirements, Mysql5.7.36, username password all may have tried, database name is also the only sonar, but still error, powerful search engine also didn’t find what I need, It must be my way of looking. There is no choice but to switch to the second, locally installed Mysql database.
3.4 Installing Mysql locally
After the attempt to use the Mysql database installed on the remote server failed, the battle was not continued in order not to affect the time, and the Mysql database was installed locally instead.
Local installation database environment: Windows10
Mysql zip installation for Windows 10
Mysql 5.7.36: Yum Repository Mysql 5.7.35: Yum Repository 5.7.34: Yum Repository 5.7.36: Yum Repository 5.7.35: Yum Repository 5.7.34: Yum Repository 5.7.36: Yum Repository 5.7.35: Yum Repository 5.7.36: Yum Repository 5.7.35
This basically local installation of Mysql will not appear any problems, after the installation is completed repeat step 3.1, create create sonar database can be. Note: there may be a Mysql website download the installation package slowly slowly, reference the post: Mysql website to download too slow solution, set the thunderbolt download links for: downloads.mysql.com/archives/ge… Change the name to the version of the installation package you want to download.
Sonar-scanner installation and configuration
4.1 Sonar – Scanner is installed
Sonar command line analysis end software are two kinds of Sonar-Runner and Sonar-Scanner, here we use Sonar-Scanner to verify.
Download Sonar-Scanner, MY version is: Sonar-Scanner – CLI-4.6.1.2450 – Windows
Direct decompression, I decompress the directory and sonarqube in the same directory, as shown below:
4.2 Sonar – Scanner configuration
4.2.1 Configuring Environment Variables
- Fill in the variable name and value
The variable name is SONAR_RUNNER_HOME
The variable value is: sonar-scanner Decompression path
- Edit the path variable
Sonar: sonar: scanner- Windows \bin (C: sonar: sonar-scanner-4.6.1.2450-windows)
Pay attention to: I started with:%SONAR_RUNNER_HOME\bin, the result is invalid. After the environment variables are configured, run the CMD command (command prompt), enter sonar-scanner, press Enter, and the following information is displayed. The environment variables are configured.
But there is a problem, my information display will also have the following error:
ERROR: Error during SonarScanner execution
org.sonarsource.scanner.api.internal.ScannerException: Unable to execute SonarScanner analysis
at org.sonarsource.scanner.api.internal.IsolatedLauncherFactory.lambda$createLauncher$0(IsolatedLauncherFactory.java:85)
Copy the code
But this error does not affect my sonarqube use.
4.2.2 Sonar – Scanner configuration
Next for the sonar-scanner configuration, open the decompression directory, go to the sonar-scanner – conf folder, modify the sonar-scanner.
The configuration is as follows:
The source code is as follows:
Sonar. projectKey=sonar_test_project sonar.sources=. #----- Default SonarQube Server #----- SonarQube service link sonar.host.url=http://localhost:9999# -- -- -- -- -- SonarQube service token sonar. The login = e3bb99687d78f07e94d99f4dec960d178fc6e35d # -- -- -- -- -- the Default source code encoding sonar.sourceEncoding=UTF-8
Copy the code
4.2.3 Configuration in the tested project
- Start the sonarqube
- Log in to the system and click the “New Project” sign in the upper right corner.
3. Enter the project id
4. Create a token
After the setup is successful, the corresponding token can be created. The value of the token will be used in the relevant configuration of sonar-scanner above (
sonar-scanner.properties
In the fileThe SonarQube service token
Configuration item), including the corresponding project id, token name input “admin” (Name set yourself
), click the “Create” button on the right to complete the creation of the token. After the creation,Copy the value of the token below, the token value isRandomly generatedTherefore, the token values in this installation manual are invalid in the new deployment environment.
- Check the in-project configuration
In the ** root directory of the project under test, add the configuration file sonar-project.properties as follows.
The source code is as follows:
Sonar. ProjectKey =sonar_test_project sonar. ProjectName =sonar_test_project # code path sonar. Sources =.sonar0.1. 0
sonar.host.url=http://localhost:9999
sonar.login=df701374ff5d3bc1b36e9162cbb08b11b29cebe8
sonar.exclusions=**/*.less,assets/images/**,assets/less/**
Copy the code
5. Perform code scanning
Enter the root directory of the object code, click the corresponding path, CMD enter to locate the current directory, the specific steps are as follows.
CMD enters the root directory of the detected project:
Enter the following command:
sonar-scanner
Copy the code
Code scan.
The scan results are as follows: