Jenkins integrates SonarQube code quality detection

上一篇文章> Jenkins releases Kubernetes (K8s) cluster (based on containerd)

1. Introduction to SonarQube


1 Introduction

SonarQube is an open platform for managing code quality, which can quickly locate potential or obvious errors in the code.

2. Download

https://www.sonarsource.com/products/sonarqube/downloads/

Insert image description here

2. Experimental environment


1. k8s environment

Version v1.26.5, the container is containerd
binary installation Kubernetes (K8s) cluster (based on containerd) - installation tutorial from scratch (with certificate)

CPU name IP system version install service
master01 10.10.10.21 rhel7.5 nginx、etcd、api-server、scheduler、controller-manager、kubelet、proxy
master02 10.10.10.22 rhel7.5 nginx、etcd、api-server、scheduler、controller-manager、kubelet、proxy
master03 10.10.10.23 rhel7.5 nginx、etcd、api-server、scheduler、controller-manager、kubelet、proxy
node01 10.10.10.24 rhel7.5 nginx、kubelet、proxy
node02 10.10.10.25 rhel7.5 nginx、kubelet、proxy

2. jenkins environment

Getting started with jenkins and installing
containers as docker

Host IP system version
jenkins 10.10.10.10 rhel7.5

3. SonarQube installation


1. Download the image

[root@jenkins ~]# docker pull postgres
[root@jenkins ~]# docker pull sonarqube:9.9.1-community

2. Start

[root@jenkins ~]# mkdir sonarqube
[root@jenkins ~]# cd sonarqube
[root@jenkins sonarqube]# cat docker-compose.yaml
version: "3.1"
services:
  db:
    image: postgres
    container_name: db
    ports:
      - 5432:5432
    networks:
      - sonarnet
    environment:
      TZ: Asia/Shanghai
      POSTGRES_USER: sonar
      POSTGRES_PASSWORD: sonar
      POSTGRES_DB: sonar
    volumes:
      - /etc/localtime:/etc/localtime:ro
      - ./data:/var/lib/postgresql/data
  sonarqube:
    image: sonarqube:9.9.1-community
    privileged: true
    container_name: sonarqube
    depends_on:
      - db
    volumes:
      - /etc/localtime:/etc/localtime:ro 
    ports:
      - "9000:9000"
    networks:
      - sonarnet
    environment:
      TZ: Asia/Shanghai
      SONAR_JDBC_URL: jdbc:postgresql://db:5432/sonar
      SONAR_JDBC_USERNAME: sonar
      SONAR_JDBC_PASSWORD: sonar
networks:
  sonarnet:
    driver: bridge

[root@jenkins sonarqube]# mkdir -p data
[root@jenkins sonarqube]# docker-compose up -d

3. Error handling

privileged: trueJust add

[root@jenkins sonarqube]# docker logs -f sonarqube
[0.056s][warning][os,thread] Failed to start thread "VM Thread" - pthread_create failed (EPERM) for attributes: stacksize: 1024k, guardsize: 4k, detached.
Error occurred during initialization of VM

4. Browser access

http://10.10.10.10:9000/Default
account password: admin/admin

Insert image description here
Insert image description here

5. Configure Chinese fonts

(1) Download fonts
Insert image description here
Insert image description here
(2) Restart sonarqube

[root@jenkins sonarqube]# docker restart sonarqube

(3) Log in again to view

Insert image description here

4. sonarqube test code


1. Maven (Method 1)

(1) Configuration setting

[root@jenkins ~]# vim /usr/local/maven/conf/settings.xml
    <profile>
        <id>sonar</id>
        <activation>
            <activeByDefault>true</activeByDefault>
        </activation>
        <properties>
            <sonar.login>admin</sonar.login>
            <sonar.password>1</sonar.password>
            <sonar.host.url>http://10.10.10.10:9000</sonar.host.url>
        </properties>
    </profile>

Insert image description here

(2) Test

Here is a previous project, just enter your corresponding project

[root@jenkins ~]# docker exec -it jenkins /bin/bash
root@67460f5b7c78:/# cd /var/jenkins_home/workspace/java-k8s
root@67460f5b7c78:/var/jenkins_home/workspace/java-k8s# ls
Dockerfile  Jenkinsfile  LICENSE  README.md  db  pipeline.yaml  pom.xml  src  target
root@67460f5b7c78:/var/jenkins_home/workspace/java-k8s# /usr/local/maven/bin/mvn sonar:sonar

Insert image description here
(3) View results

Insert image description here

2. sonar-scanner (method 2)

(1) Generate token

Insert image description here
Insert image description here
Insert image description here

(2) Download files

Download address: https://docs.sonarqube.org/latest/analyzing-source-code/scanners/sonarscanner/

[root@jenkins ~]# unzip sonar-scanner-cli-4.8.0.2856-linux.zip
[root@jenkins ~]# mv sonar-scanner-4.8.0.2856-linux /usr/local/sonar-scanner

(3) Restart jenkins

[root@jenkins ~]# docker stop jenkins
[root@jenkins ~]# docker rm jenkins
[root@jenkins ~]# docker run -d --name jenkins -p 8080:8080 -p 50000:50000 -u root \
-v /opt/jenkins_home:/var/jenkins_home \
-v /usr/local/maven:/usr/local/maven \
-v /usr/local/jdk:/usr/local/jdk \
-v /etc/localtime:/etc/localtime \
-v /usr/bin/docker:/usr/bin/docker \
-v /var/run/docker.sock:/var/run/docker.sock \
-v /usr/local/sonar-scanner:/usr/local/sonar-scanner \
--restart=always \
jenkins/jenkins:2.361.4-lts-jdk11

(4) Configure sonar-scanner.properties

[root@jenkins ~]# cat /usr/local/sonar-scanner/conf/sonar-scanner.properties
#Configure here general information about the environment, such as SonarQube server connection details for example
#No information about specific project should appear here

#----- Default SonarQube server
sonar.host.url=http://10.10.10.10:9000

#----- Default source code encoding
sonar.sourceEncoding=UTF-8

(5) Test

[root@jenkins ~]# cd /opt/jenkins_home/workspace/java-k8s
[root@jenkins java-k8s]# ls
db  Dockerfile  Jenkinsfile  LICENSE  pipeline.yaml  pom.xml  README.md  src  target
[root@jenkins java-k8s]# /usr/local/sonar-scanner/bin/sonar-scanner -Dsonar.source=./ -Dsonar.projectname=java-k8s -Dsonar.login=sqa_596d6ea2c88ab661eb56afcf72bfb48ef80bd8f2 -Dsonar.projectKey=java-k8s -D sonar.java.binaries=./target/

Insert image description here

5. Install sonar-scanner in Jenkins


1. Download sonar-scanner

Insert image description here
Then restart jenkins

2. Configure sonar-scanner

(1) System configuration

System Management–>System Configuration

Insert image description here

Due to lag and unable to click, re-enter and configure the token.

Insert image description here
Insert image description here

(2) Global tool configuration

System Management–>Global Tool Configuration

Insert image description here

3. Create project tests

(1) Create project
Insert image description here
(2) git configuration
Insert image description here
(3) sonarqube configuration

JAVA_HOME=/usr/local/jdk
PATH=$PATH:$JAVA_HOME/bin
/usr/local/maven/bin/mvn clean package -Dmaven.test.skip=true
sonar.source=./
sonar.projectname=${JOB_NAME}
sonar.projectKey=${JOB_NAME}
sonar.java.binaries=./target/

Insert image description here
Insert image description here

(4) View results

Insert image description here
Insert image description here

6. Pass the pipeline test


1. Create a pipeline project

Insert image description here

2. View files

Insert image description here
Dockerfile:

FROM harbor.wielun.com/library/tomcat:8.5.59
MAINTAINER Wielun
RUN rm -rf /usr/local/tomcat/webapps/*
ADD target/*.war /usr/local/tomcat/webapps/ROOT.war

pipeline.yaml:

apiVersion: apps/v1
kind: Deployment
metadata:
  namespace: test
  name: pipeline
  labels:
    app: pipeline
spec:
  replicas: 2
  selector:
    matchLabels:
      app: pipeline
  template:
    metadata:
      labels:
        app: pipeline
    spec:
      containers:
      - name: pipeline
        image: harbor.wielun.com/library/java-k8s:latest
        imagePullPolicy: Always
        ports:
        - containerPort: 8080
---
apiVersion: v1
kind: Service
metadata:
  namespace: test
  name: pipeline
  labels:
    app: pipeline
spec:
  ports:
  - port: 8081
    targetPort: 8080
  selector:
    app: pipeline
  type: NodePort
---
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  namespace: test
  name: pipeline
spec:
  ingressClassName: nginx
  rules:
  - host: "harbor.wielun.com"
    http:
      paths:
      - pathType: Prefix
        path: /
        backend:
          service:
            name: pipeline
            port:
              number: 8081

3. Modify Jenkinsfile

Insert image description here

pipeline {
    agent any
	environment {
		harborUser = 'admin'
		harborPasswd = 'Harbor12345'
		HarborAddress = 'harbor.wielun.com'
		harborRepo = 'library'
	}
    stages {
        stage('git拉取代码') {
            steps {
				git credentialsId: '0c71c0f9-8277-xxxx-bb31-540a9324cf08', url: 'https://jihulab.com/xxxx/java-demo.git'
            }
        }
    
        stage('maven编译') { 
           steps {
                    sh '''JAVA_HOME=/usr/local/jdk
                    PATH=$PATH:$JAVA_HOME/bin
                    /usr/local/maven/bin/mvn clean package -Dmaven.test.skip=true'''
                }
        }
        stage('通过SonarQube完成代码质量检测') { 
           steps {
                    sh '/usr/local/sonar-scanner/bin/sonar-scanner -Dsonar.source=./ -Dsonar.projectname=${JOB_NAME} -Dsonar.projectKey=${JOB_NAME} -Dsonar.java.binaries=./target/ -Dsonar.login=sqa_596d6ea2c88ab661eb56afcf72bfb48ef80bd8f2'
                }
        }
        stage('生成自定义镜像') { 
           steps {
                    sh '''docker build -t ${JOB_NAME}:latest .'''
                }
        }
        stage('上传自定义镜像到harbor') { 
           steps {
                    sh '''docker login -u ${harborUser} -p ${harborPasswd} ${HarborAddress}
                    docker tag ${JOB_NAME}:latest ${HarborAddress}/${harborRepo}/${JOB_NAME}:latest
                    docker push ${HarborAddress}/${harborRepo}/${JOB_NAME}:latest'''
                }
        }
        stage('发送yaml到k8s-master并部署') { 
           steps {
					sshPublisher(publishers: [sshPublisherDesc(configName: 'k8s-master', transfers: [sshTransfer(cleanRemote: false, excludes: '', execCommand: '''
					/usr/local/bin/kubectl apply -f /tmp/${JOB_NAME}/pipeline.yaml''', execTimeout: 120000, flatten: false, makeEmptyDirs: false, noDefaultExcludes: false, patternSeparator: '[, ]+', remoteDirectory: '${JOB_NAME}', remoteDirectorySDF: false, removePrefix: '', sourceFiles: 'pipeline.yaml')], usePromotionTimestamp: false, useWorkspaceInPromotion: false, verbose: false)])
                }
        } 
    }
}

4. View the results

Insert image description here
Insert image description here

下一篇文章> Jenkins publishes WinServer2016 via OpenSSH

Guess you like

Origin blog.csdn.net/Dream_ya/article/details/131327786