当前位置: 代码迷 >> 综合 >> SonarQube API接口
  详细解决方案

SonarQube API接口

热度:82   发布时间:2023-09-30 13:48:29.0
//查找项目
api/projects/search?projects=${projectName}"//创建项目
api/projects/create?name=${projectName}&project=${projectName}"//更新语言规则集
api/qualityprofiles/add_project?language=${language}&qualityProfile=${qualityProfile}&project=${projectName}"//项目授权
api/permissions/apply_template?projectKey=${projectKey}&templateName=${templateName}"//更新质量阈
api/qualitygates/select?projectKey=${projectKey}&gateId=${gateId}"

SonarQube API接口

SonarQube API接口

SonarQube API接口

SonarQube API接口

http://139.198.170.122:9000/api/projects/search?projects=devops-maven-service

SonarQube API接口

SonarQube API接口

SonarQube API接口

SonarQube API接口

httpRequest authentication: 'd7aec8dd-c7e2-41db-b0ae-e37041f1c440', responseHandle: 'NONE', url: 'http://139.198.170.122:9000/web_api/api/projects/search?projects=devops-maven-service', wrapAsMultipart: false
steps {script {def response = httpRequest authentication: 'e89c6fa4-d9a2-4042-b3a5-8b00ff372d92',url: 'http://139.198.170.122:9000/api/projects/search?projects=devops-maven-service',wrapAsMultipart: falseprint(response.content)}}HttpMethod: GET
URL: http://139.198.170.122:9000/api/projects/search?projects=devops-maven-service
Using authentication: e89c6fa4-d9a2-4042-b3a5-8b00ff372d92
Sending request to url: http://139.198.170.122:9000/api/projects/search?projects=devops-maven-service
Response Code: HTTP/1.1 200 
Success code from [100‥399]
[Pipeline] echo
{"paging":{"pageIndex":1,"pageSize":100,"total":1},"components":[{"organization":"default-organization","id":"AXnf-zrBwuie6iwOEU8H","key":"devops-maven-service","name":"devops-maven-service","qualifier":"TRK","visibility":"public","lastAnalysisDate":"2021-06-22T09:04:10+0000"}]}

然后可以拿到返回值去使用readjson解析数据,判断项目存不存在,比如可以判断total的值是否为1来判断项目是否存在。

SonarQube API接口

封装到共享库


现在接口这么多,这些HTTP请求大同小异,是一样的。

SonarQube API接口

package org.devops//封装HTTPdef HttpReq(reqType,reqUrl,reqBody){def sonarServer = "http://139.198.170.122:9000/api"response = httpRequest authentication: 'e89c6fa4-d9a2-4042-b3a5-8b00ff372d92',httpMode: reqType, contentType: "APPLICATION_JSON",consoleLogResponseBody: true,ignoreSslErrors: true, requestBody: reqBody,url: "${sonarServer}/${reqUrl}"//quiet: truereturn response
}//搜索Sonar项目
def SerarchProject(projectName){apiUrl = "projects/search?projects=${projectName}"response = HttpReq("GET",apiUrl,'')response = readJSON text: """${response.content}"""result = response["paging"]["total"]if(result.toString() == "0"){return "false"} else {return "true"}
}//获取Sonar质量阈状态
def GetProjectStatus(projectName){apiUrl = "project_branches/list?project=${projectName}"response = HttpReq("GET",apiUrl,'')response = readJSON text: """${response.content}"""result = response["branches"][0]["status"]["qualityGateStatus"]//println(response)return result
}//创建Sonar项目
def CreateProject(projectName){apiUrl =  "projects/create?name=${projectName}&project=${projectName}"response = HttpReq("POST",apiUrl,'')println(response)
}//配置项目质量规则def ConfigQualityProfiles(projectName,lang,qpname){apiUrl = "qualityprofiles/add_project?language=${lang}&project=${projectName}&qualityProfile=${qpname}"response = HttpReq("POST",apiUrl,'')println(response)
}//获取质量阈ID
def GetQualtyGateId(gateName){apiUrl= "qualitygates/show?name=${gateName}"response = HttpReq("GET",apiUrl,'')response = readJSON text: """${response.content}"""result = response["id"]return result
}//配置项目质量阈def ConfigQualityGates(projectName,gateName){gateId = GetQualtyGateId(gateName)apiUrl = "qualitygates/select?gateId=${gateId}&projectKey=${projectName}"response = HttpReq("POST",apiUrl,'')println(response)println(response)
}

要先让项目扫描之后,才可以去配置质量规则和质量阈。所以需要去新创建项目。

SonarQube API接口

SonarQube API接口

SonarQube API接口

SonarQube API接口

可以看到创建的空项目

SonarQube API接口这样就可以去质量规则里面选择刚刚创建的项目了

SonarQube API接口

这样项目再次扫描的时候就是使用质量规则里面的myjava了,和质量规则一样,质量阈也一样。

所以上面的代码主要是解决项目在第一次代码分析扫描的时候,未能够正确配置质量规则和质量阈值,需要这样去做。

所有的配置都需要去UI界面手动的点点点,点完之后才能进行分析,要想做到自动化就是在分析之前,将空项目创建好,然后将质量配置好,质量阈也给其配置好。

Jenkinsfile


// 加载名称为devopslib的共享库的master版本
@Library("devopslib@master") _//导入共享库中的方法类
def mytools = new org.devops.mytools()
def builds  = new org.devops.builds()
def sonar = new org.devops.sonarqube()//定义构建工具类型与路径map
def buildTools = [  "maven": "/usr/local/apache-maven-3.8.1","gradle": "/usr/local/gradle-6.8.3/","golang": "/usr/local/go","web" : "/usr/local/node-v14.16.1-linux-x64/","sonar": "/usr/local/sonar-scanner-4.6.0.2311-linux/"]//定义UI上面的参数(用户去选择构建那个项目的那个分支的构建类型)
String branchName = "${env.branchName}"
String gitHttpURL = "${env.gitHttpURL}"
String buildType  = "${env.buildType}"
String credentialsId = "${env.credentialsId}"// 以下是流水线阶段
pipeline {agent { label  "build" }  options {skipDefaultCheckout true}stages {stage("GetCode"){steps{script{// 调用GetCode方法进行代码下载 mytools.GetCode("git",branchName,gitHttpURL,credentialsId)}}}stage("Build"){steps {script {// 调用Build方法进行代码构建builds.Build(buildTools, buildType)}}}stage("SonarScan"){steps {script {//定义项目名称projectName="devops-maven-service"//搜索项目result = sonar.SerarchProject(projectName)println(result)//判断项目是否存在if(result == "false"){println("${projectName}----->项目不存在,准备创建项目${projectName}")  sonar.CreateProject(projectName)    }else{println("${projectName}----->项目已存在!")}//配置项目质量规则qpname = "myjava"sonar.ConfigQualityProfiles(projectName,"java",qpname)//配置质量阈sonar.ConfigQualityGates(projectName,qpname)//扫描sh """${buildTools["sonar"]}/bin/sonar-scanner -Dsonar.host.url=http://139.198.170.122:9000 \-Dsonar.projectKey="${projectName}" \-Dsonar.projectName="${projectName}" \-Dsonar.projectVersion=1.0 \-Dsonar.login=admin \-Dsonar.password=admin \-Dsonar.ws.timeout=30 \-Dsonar.projectDescription="my first project!" \-Dsonar.links.homepage=http://139.198.170.122:81/root/devops-maven-service \-Dsonar.links.ci=http://139.198.170.122:8080/job/demo-maven-service/ \-Dsonar.sources=src/main \-Dsonar.sourceEncoding=UTF-8 \-Dsonar.java.binaries=target/classes \-Dsonar.java.test.binaries=target/test-classes \-Dsonar.java.surefire.report=target/surefire-reports """sleep 10//获取扫描结果result = sonar.GetProjectStatus(projectName)println(result)if (result.toString() == "ERROR"){error "代码质量阈失败,请及时修复"} else {println(result) }}}}}post {always {script{echo "always......"}}success {script {echo "success....."}}}}

接下来的效果就是在扫描之前,项目给你配置好,质量阈也会给你配置好

SonarQube API接口

HttpMethod: GET
URL: http://139.198.170.122:9000/api/projects/search?projects=devops-maven-service
Content-Type: application/json
Using authentication: e89c6fa4-d9a2-4042-b3a5-8b00ff372d92
Sending request to url: http://139.198.170.122:9000/api/projects/search?projects=devops-maven-service
Response Code: HTTP/1.1 200 
Response: 
{"paging":{"pageIndex":1,"pageSize":100,"total":0},"components":[]}
Success code from [100‥399]
[Pipeline] readJSON
[Pipeline] echo
false
[Pipeline] echo
devops-maven-service----->项目不存在,准备创建项目devops-maven-service
[Pipeline] httpRequest
HttpMethod: POST
URL: http://139.198.170.122:9000/api/projects/create?name=devops-maven-service&project=devops-maven-service
Content-Type: application/json
Using authentication: e89c6fa4-d9a2-4042-b3a5-8b00ff372d92
Sending request to url: http://139.198.170.122:9000/api/projects/create?name=devops-maven-service&project=devops-maven-service
Response Code: HTTP/1.1 200 
Response: 
{"project":{"key":"devops-maven-service","name":"devops-maven-service","qualifier":"TRK","visibility":"public"}}
Success code from [100‥399]
[Pipeline] echo
Status: 200
[Pipeline] httpRequest
HttpMethod: POST
URL: http://139.198.170.122:9000/api/qualityprofiles/add_project?language=java&project=devops-maven-service&qualityProfile=myjava
Content-Type: application/json
Using authentication: e89c6fa4-d9a2-4042-b3a5-8b00ff372d92
Sending request to url: http://139.198.170.122:9000/api/qualityprofiles/add_project?language=java&project=devops-maven-service&qualityProfile=myjava
Response Code: HTTP/1.1 204 
Response: 
null
Success code from [100‥399]
[Pipeline] echo
Status: 204
[Pipeline] httpRequest
HttpMethod: GET
URL: http://139.198.170.122:9000/api/qualitygates/show?name=myjava
Content-Type: application/json
Using authentication: e89c6fa4-d9a2-4042-b3a5-8b00ff372d92
Sending request to url: http://139.198.170.122:9000/api/qualitygates/show?name=myjava
Response Code: HTTP/1.1 200 
Response: 
{"id":4,"name":"myjava","conditions":[{"id":10,"metric":"branch_coverage","op":"LT","error":"60"}],"isBuiltIn":false,"actions":{"rename":true,"setAsDefault":true,"copy":true,"associateProjects":true,"delete":true,"manageConditions":true}}
Success code from [100‥399]
[Pipeline] readJSON
[Pipeline] httpRequest
HttpMethod: POST
URL: http://139.198.170.122:9000/api/qualitygates/select?gateId=4&projectKey=devops-maven-service
Content-Type: application/json
Using authentication: e89c6fa4-d9a2-4042-b3a5-8b00ff372d92
Sending request to url: http://139.198.170.122:9000/api/qualitygates/select?gateId=4&projectKey=devops-maven-service
Response Code: HTTP/1.1 204 
Response: 
null
Success code from [100‥399]
[Pipeline] echo
Status: 204
[Pipeline] sh
+ /usr/local/sonar-scanner-4.6.0.2311-linux//bin/sonar-scanner -Dsonar.host.url=http://139.198.170.122:9000 -Dsonar.projectKey=devops-maven-service -Dsonar.projectName=devops-maven-service -Dsonar.projectVersion=1.0 -Dsonar.login=admin -Dsonar.password=admin -Dsonar.ws.timeout=30 '-Dsonar.projectDescription=my first project!' -Dsonar.links.homepage=http://139.198.170.122:81/root/devops-maven-service -Dsonar.links.ci=http://139.198.170.122:8080/job/demo-maven-service/ -Dsonar.sources=src/main -Dsonar.sourceEncoding=UTF-8 -Dsonar.java.binaries=target/classes -Dsonar.java.test.binaries=target/test-classes -Dsonar.java.surefire.report=target/surefire-reports
INFO: Scanner configuration file: /usr/local/sonar-scanner-4.6.0.2311-linux/conf/sonar-scanner.properties
INFO: Project root configuration file: NONE
INFO: SonarScanner 4.6.0.2311
INFO: Java 1.8.0_282 AdoptOpenJDK (64-bit)[Pipeline] sleep
Sleeping for 10 sec
[Pipeline] httpRequest
HttpMethod: GET
URL: http://139.198.170.122:9000/api/project_branches/list?project=devops-maven-service
Content-Type: application/json
Using authentication: e89c6fa4-d9a2-4042-b3a5-8b00ff372d92
Sending request to url: http://139.198.170.122:9000/api/project_branches/list?project=devops-maven-service
Response Code: HTTP/1.1 200 
Response: 
{"branches":[{"name":"master","isMain":true,"type":"LONG","status":{"qualityGateStatus":"OK"},"analysisDate":"2021-06-26T03:05:59+0000"}]}
Success code from [100‥399]
[Pipeline] readJSON
[Pipeline] echo
OK
[Pipeline] echo
OK
[Pipeline] }

 上面信息可以看到将质量规则和质量阈都改成了myjava

SonarQube API接口

SonarQube API接口

SonarQube API接口

SonarQube API接口

相对于手动在web上面创建的操作,全部以调接口的方式在Jenkins里面完成了,要不然每次在新项目上都需要先创建新项目,然后授权。