diff --git a/docker-images/core/ci/dockerfile/backend.bkci.sh b/docker-images/core/ci/dockerfile/backend.bkci.sh index bd4e7ce1f3d..d599229ca44 100644 --- a/docker-images/core/ci/dockerfile/backend.bkci.sh +++ b/docker-images/core/ci/dockerfile/backend.bkci.sh @@ -31,6 +31,7 @@ java_argv+=( "-Dservice-suffix=" "-Dspring.profiles.active=local,dev" "-Dspring.application.name=$MS_NAME" + "-Dspring.main.allow-circular-references=true" ) echo "run java" diff --git a/helm-charts/core/ci/build/values.yaml b/helm-charts/core/ci/build/values.yaml index fb8e13ee7c7..b11c50b3420 100644 --- a/helm-charts/core/ci/build/values.yaml +++ b/helm-charts/core/ci/build/values.yaml @@ -67,7 +67,7 @@ serviceMonitor: init: sql: true iam: true - turbo: true + turbo: false bkrepo: true defaultImage: true plugin: @@ -117,7 +117,7 @@ mysql: datadir=/bitnami/mysql/data tmpdir=/opt/bitnami/mysql/tmp max_allowed_packet=16M - bind-address=0.0.0.0 + bind-address=* pid-file=/opt/bitnami/mysql/tmp/mysqld.pid log-error=/opt/bitnami/mysql/logs/mysqld.log character-set-server=UTF8 @@ -172,6 +172,26 @@ rabbitmq: default_permissions.configure = .* default_permissions.read = .* default_permissions.write = .* + # 如果想在ipv6环境中运行, 需要开启这些选项 + # initContainers: + # - name: ipv6-init + # image: "docker.io/busybox:1.33.1" + # imagePullPolicy: IfNotPresent + # volumeMounts: + # - name: ipv6-cfg + # mountPath: /ipv6 + # command: ['sh', '-c', 'echo "{inet6, true}." > /ipv6/erl_inetrc'] + # extraVolumes: + # - name: ipv6-cfg + # emptyDir: {} + # extraVolumeMounts: + # - name: ipv6-cfg + # mountPath: /ipv6 + # extraEnvVars: + # - name: RABBITMQ_SERVER_ADDITIONAL_ERL_ARGS + # value: "-kernel inetrc '/ipv6/erl_inetrc' -proto_dist inet6_tcp" + # - name: RABBITMQ_CTL_ERL_ARGS + # value: "-proto_dist inet6_tcp" influxdb: enabled: true image: @@ -185,9 +205,13 @@ influxdb: persistence: size: 10Gi influxdb: + readinessProbe: + enabled: false + livenessProbe: + enabled: false initdbScripts: creata_db.sh: | - influx -host 127.0.0.1 -port "$INFLUXDB_HTTP_PORT_NUMBER" -username "${INFLUXDB_ADMIN_USER}" -password "${INFLUXDB_ADMIN_USER_PASSWORD}" -execute "create database agentMetrix;" + influx -host localhost -port "$INFLUXDB_HTTP_PORT_NUMBER" -username "${INFLUXDB_ADMIN_USER}" -password "${INFLUXDB_ADMIN_USER_PASSWORD}" -execute "create database agentMetrix;" mongodb: # 是否部署mongodb # 如果需要使用外部数据库,设置为false并配置external.mongodb @@ -204,7 +228,7 @@ mongodb: size: 10Gi initdbScripts: create_admin_user.sh: | - $MONGODB_BIN_DIR/mongo admin --host 127.0.0.1 --port $MONGODB_PORT_NUMBER -u root -p $MONGODB_ROOT_PASSWORD << EOF + $MONGODB_BIN_DIR/mongo admin --host localhost --port $MONGODB_PORT_NUMBER -u root -p $MONGODB_ROOT_PASSWORD << EOF use db_turbo db.createUser({ user: "$MONGODB_USERNAME" , pwd: "$MONGODB_PASSWORD" , roles: [{role: "dbOwner" , db:"db_turbo"}]}) use db_quartz diff --git a/src/backend/ci/.gitignore b/src/backend/ci/.gitignore index a4cb765c7e2..e7fd0a014da 100644 --- a/src/backend/ci/.gitignore +++ b/src/backend/ci/.gitignore @@ -14,4 +14,5 @@ version.txt support-files/etc build.yml .temp -.codecc \ No newline at end of file +.codecc +*.log.gz diff --git a/src/backend/ci/build.gradle.kts b/src/backend/ci/build.gradle.kts index b5e36f0299d..6fedf27c073 100644 --- a/src/backend/ci/build.gradle.kts +++ b/src/backend/ci/build.gradle.kts @@ -106,6 +106,18 @@ allprojects { dependencySet("io.github.resilience4j:${Versions.Resilience4j}") { entry("resilience4j-circuitbreaker") } + // TODO 修复IPv6单栈环境报错问题, 等后面Okhttp3版本升级上来就可以去掉 + dependencySet("com.squareup.okhttp3:${Versions.Okhttp}") { + entry("logging-interceptor") + entry("mockwebserver") + entry("okcurl") + entry("okhttp") + entry("okhttp-dnsoverhttps") + entry("okhttp-sse") + entry("okhttp-testing-support") + entry("okhttp-tls") + entry("okhttp-urlconnection") + } dependencySet("org.eclipse.jgit:${Versions.jgit}") { entry("org.eclipse.jgit") entry("org.eclipse.jgit.ssh.jsch") diff --git a/src/backend/ci/buildSrc/src/main/kotlin/constants/Versions.kt b/src/backend/ci/buildSrc/src/main/kotlin/constants/Versions.kt index 3fbbd995929..b323602f552 100644 --- a/src/backend/ci/buildSrc/src/main/kotlin/constants/Versions.kt +++ b/src/backend/ci/buildSrc/src/main/kotlin/constants/Versions.kt @@ -44,5 +44,6 @@ object Versions { const val mockk = "1.12.2" const val Resilience4j = "1.7.1" const val jjwt = "0.11.5" + const val Okhttp = "4.9.0" const val jgit = "5.13.1.202206130422-r" } diff --git a/src/backend/ci/core/artifactory/biz-artifactory-push/src/main/kotlin/com/tencent/devops/artifactory/service/JobServiceExt.kt b/src/backend/ci/core/artifactory/biz-artifactory-push/src/main/kotlin/com/tencent/devops/artifactory/service/JobServiceExt.kt index 1404db4e710..57bd8edcb4c 100644 --- a/src/backend/ci/core/artifactory/biz-artifactory-push/src/main/kotlin/com/tencent/devops/artifactory/service/JobServiceExt.kt +++ b/src/backend/ci/core/artifactory/biz-artifactory-push/src/main/kotlin/com/tencent/devops/artifactory/service/JobServiceExt.kt @@ -70,7 +70,7 @@ class JobServiceExt @Autowired constructor( .post(RequestBody.create(OkhttpUtils.jsonMediaType, requestBody)) .build() OkhttpUtils.doHttp(httpReq).use { resp -> - val responseStr = resp.body()!!.string() + val responseStr = resp.body!!.string() logger.info("response body: $responseStr") val response: Map = jacksonObjectMapper().readValue(responseStr) @@ -92,7 +92,7 @@ class JobServiceExt @Autowired constructor( val url = "$jobUrl/service/history/$projectId/$taskInstanceId/status" logger.info("Get request url: $url") OkhttpUtils.doGet(url).use { resp -> - val responseStr = resp.body()!!.string() + val responseStr = resp.body!!.string() // val responseStr = HttpUtils.get(url) logger.info("responseBody: $responseStr") val response: Map = jacksonObjectMapper().readValue(responseStr) diff --git a/src/backend/ci/core/auth/biz-auth/src/main/kotlin/com/tencent/devops/auth/service/AuthDeptServiceImpl.kt b/src/backend/ci/core/auth/biz-auth/src/main/kotlin/com/tencent/devops/auth/service/AuthDeptServiceImpl.kt index d6f474e1550..5ba85c98fe9 100644 --- a/src/backend/ci/core/auth/biz-auth/src/main/kotlin/com/tencent/devops/auth/service/AuthDeptServiceImpl.kt +++ b/src/backend/ci/core/auth/biz-auth/src/main/kotlin/com/tencent/devops/auth/service/AuthDeptServiceImpl.kt @@ -33,17 +33,17 @@ import com.fasterxml.jackson.module.kotlin.readValue import com.google.common.cache.CacheBuilder import com.tencent.bk.sdk.iam.constants.ManagerScopesEnum import com.tencent.bk.sdk.iam.dto.response.ResponseDTO -import com.tencent.devops.auth.common.Constants.LEVEL -import com.tencent.devops.auth.common.Constants.PARENT import com.tencent.devops.auth.common.Constants.HTTP_RESULT +import com.tencent.devops.auth.common.Constants.LEVEL import com.tencent.devops.auth.common.Constants.NAME +import com.tencent.devops.auth.common.Constants.PARENT import com.tencent.devops.auth.common.Constants.USERNAME import com.tencent.devops.auth.common.Constants.USER_LABLE import com.tencent.devops.auth.constant.AuthMessageCode -import com.tencent.devops.auth.entity.SearchUserAndDeptEntity import com.tencent.devops.auth.entity.SearchDeptUserEntity import com.tencent.devops.auth.entity.SearchProfileDeptEntity import com.tencent.devops.auth.entity.SearchRetrieveDeptEntity +import com.tencent.devops.auth.entity.SearchUserAndDeptEntity import com.tencent.devops.auth.entity.UserDeptTreeInfo import com.tencent.devops.auth.pojo.vo.BkUserInfoVo import com.tencent.devops.auth.pojo.vo.DeptInfoVo @@ -54,7 +54,7 @@ import com.tencent.devops.common.api.util.OkhttpUtils import com.tencent.devops.common.auth.api.pojo.EsbBaseReq import com.tencent.devops.common.redis.RedisOperation import com.tencent.devops.common.service.utils.MessageCodeUtil -import okhttp3.MediaType +import okhttp3.MediaType.Companion.toMediaTypeOrNull import okhttp3.Request import okhttp3.RequestBody import org.slf4j.LoggerFactory @@ -280,7 +280,7 @@ class AuthDeptServiceImpl @Autowired constructor( private fun callUserCenter(url: String, searchEntity: EsbBaseReq): String { val url = getAuthRequestUrl(url) val content = objectMapper.writeValueAsString(searchEntity) - val mediaType = MediaType.parse("application/json; charset=utf-8") + val mediaType = "application/json; charset=utf-8".toMediaTypeOrNull() val requestBody = RequestBody.create(mediaType, content) val request = Request.Builder().url(url) .post(requestBody) @@ -290,26 +290,28 @@ class AuthDeptServiceImpl @Autowired constructor( // 请求错误 logger.warn( "call user center fail: url = $url | searchEntity = $searchEntity" + - " | response = ($it)" + " | response = ($it)" ) throw OperationException( MessageCodeUtil.getCodeLanMessage( - messageCode = AuthMessageCode.USER_NOT_EXIST - )) + messageCode = AuthMessageCode.USER_NOT_EXIST + ) + ) } - val responseStr = it.body()!!.string() + val responseStr = it.body!!.string() logger.info("callUserCenter : response = $responseStr") val responseDTO = JsonUtil.to(responseStr, ResponseDTO::class.java) if (responseDTO.code != 0L || responseDTO.result == false) { // 请求错误 logger.warn( "call user center fail: url = $url | searchEntity = $searchEntity" + - " | response = ($it)" + " | response = ($it)" ) throw OperationException( MessageCodeUtil.getCodeLanMessage( messageCode = AuthMessageCode.USER_NOT_EXIST - )) + ) + ) } logger.info("user center response:${objectMapper.writeValueAsString(responseDTO.data)}") return objectMapper.writeValueAsString(responseDTO.data) diff --git a/src/backend/ci/core/auth/biz-auth/src/main/kotlin/com/tencent/devops/auth/service/AuthHttpClientService.kt b/src/backend/ci/core/auth/biz-auth/src/main/kotlin/com/tencent/devops/auth/service/AuthHttpClientService.kt index 8dd61ac7c1d..92a9e661805 100644 --- a/src/backend/ci/core/auth/biz-auth/src/main/kotlin/com/tencent/devops/auth/service/AuthHttpClientService.kt +++ b/src/backend/ci/core/auth/biz-auth/src/main/kotlin/com/tencent/devops/auth/service/AuthHttpClientService.kt @@ -33,20 +33,20 @@ import com.tencent.devops.common.api.auth.AUTH_HEADER_IAM_TOKEN import com.tencent.devops.common.api.exception.ClientException import com.tencent.devops.common.api.exception.RemoteServiceException import com.tencent.devops.common.security.jwt.JwtManager -import okhttp3.Headers -import okhttp3.MediaType +import okhttp3.Headers.Companion.toHeaders +import okhttp3.MediaType.Companion.toMediaTypeOrNull import okhttp3.OkHttpClient import okhttp3.OkHttpClient.Builder +import okhttp3.Request +import okhttp3.RequestBody +import okhttp3.Response +import org.slf4j.LoggerFactory import org.springframework.beans.factory.annotation.Autowired import org.springframework.stereotype.Service import java.net.ConnectException import java.net.SocketTimeoutException import java.net.UnknownHostException import java.util.concurrent.TimeUnit -import okhttp3.Request -import okhttp3.RequestBody -import okhttp3.Response -import org.slf4j.LoggerFactory @Service class AuthHttpClientService @Autowired constructor( @@ -68,7 +68,7 @@ class AuthHttpClientService @Autowired constructor( try { val response = httpClient.newCall(request).execute() logger.info( - "Request($request) with code ${response.code()}" + "Request($request) with code ${response.code}" ) return response } catch (e: UnknownHostException) { // DNS问题导致请求未到达目标,可重试 @@ -106,14 +106,14 @@ class AuthHttpClientService @Autowired constructor( writeTimeoutInSec = writeTimeoutInSec ).use { response -> if (!response.isSuccessful) { - val responseContent = response.body()?.string() + val responseContent = response.body?.string() logger.warn( - "Fail to request($request) with code ${response.code()} ," + - " message ${response.message()} and response ($responseContent)" + "Fail to request($request) with code ${response.code} ," + + " message ${response.message} and response ($responseContent)" ) - throw RemoteServiceException(errorMessage, response.code(), responseContent) + throw RemoteServiceException(errorMessage, response.code, responseContent) } - return response.body()!!.string() + return response.body!!.string() } } @@ -124,7 +124,7 @@ class AuthHttpClientService @Autowired constructor( fun buildPost(path: String, requestBody: RequestBody, gateway: String, token: String?): Request { val url = gateway + path logger.info("iam callback url: $url") - return Request.Builder().url(url).post(requestBody).headers(Headers.of(buildJwtAndToken(token))).build() + return Request.Builder().url(url).post(requestBody).headers(buildJwtAndToken(token).toHeaders()).build() } private fun buildJwtAndToken(iamToken: String?): Map { @@ -147,7 +147,7 @@ class AuthHttpClientService @Autowired constructor( .build() companion object { - val JsonMediaType = MediaType.parse("application/json; charset=utf-8") + val JsonMediaType = "application/json; charset=utf-8".toMediaTypeOrNull() private const val EMPTY = "" private const val CONNECT_TIMEOUT = 5L private const val READ_TIMEOUT = 1500L diff --git a/src/backend/ci/core/buildless/biz-buildless/src/main/kotlin/com/tencent/devops/buildless/client/DispatchClient.kt b/src/backend/ci/core/buildless/biz-buildless/src/main/kotlin/com/tencent/devops/buildless/client/DispatchClient.kt index 4ea9c0eee10..93c3ee63efb 100644 --- a/src/backend/ci/core/buildless/biz-buildless/src/main/kotlin/com/tencent/devops/buildless/client/DispatchClient.kt +++ b/src/backend/ci/core/buildless/biz-buildless/src/main/kotlin/com/tencent/devops/buildless/client/DispatchClient.kt @@ -43,7 +43,8 @@ import com.tencent.devops.common.service.config.CommonConfig import com.tencent.devops.dispatch.docker.pojo.DockerIpInfoVO import com.tencent.devops.dispatch.docker.pojo.enums.DockerHostClusterType import okhttp3.Headers -import okhttp3.MediaType +import okhttp3.Headers.Companion.toHeaders +import okhttp3.MediaType.Companion.toMediaTypeOrNull import okhttp3.Request import okhttp3.RequestBody import org.slf4j.LoggerFactory @@ -65,17 +66,17 @@ class DispatchClient @Autowired constructor( val request = Request .Builder() .url(url) - .headers(Headers.of(makeHeaders())) + .headers(makeHeaders()) .put( RequestBody.create( - MediaType.parse("application/json; charset=utf-8"), + "application/json; charset=utf-8".toMediaTypeOrNull(), "" ) ) .build() OkhttpUtils.doHttp(request).use { response -> - val responseContent = response.body()!!.string() + val responseContent = response.body!!.string() if (!response.isSuccessful) { logger.error("Update containerId $path fail. $responseContent") throw TaskExecuteException( @@ -124,10 +125,10 @@ class DispatchClient @Autowired constructor( val request = Request .Builder() .url(url) - .headers(Headers.of(makeHeaders())) + .headers(makeHeaders()) .post( RequestBody.create( - MediaType.parse("application/json; charset=utf-8"), + "application/json; charset=utf-8".toMediaTypeOrNull(), JsonUtil.toJson(dockerIpInfoVO) ) ) @@ -135,7 +136,7 @@ class DispatchClient @Autowired constructor( logger.info("Start refresh buildLess status $url") OkhttpUtils.doHttp(request).use { response -> - val responseContent = response.body()!!.string() + val responseContent = response.body!!.string() if (!response.isSuccessful) { logger.error("Refresh buildLess status $url fail. $responseContent") throw TaskExecuteException( @@ -171,19 +172,19 @@ class DispatchClient @Autowired constructor( } } - private fun makeHeaders(): Map { + private fun makeHeaders(): Headers { val gatewayHeaderTag = if (buildLessConfig.gatewayHeaderTag == null) { bkTag.getLocalTag() } else { buildLessConfig.gatewayHeaderTag - } + } ?: "" val headers = mutableMapOf(AUTH_HEADER_GATEWAY_TAG to gatewayHeaderTag) // 新增devopsToken给网关校验 val devopsToken = EnvironmentUtil.gatewayDevopsToken() if (devopsToken != null) { headers["X-DEVOPS-TOKEN"] = devopsToken } - return headers + return headers.toHeaders() } companion object { diff --git a/src/backend/ci/core/common/common-api/src/main/kotlin/com/tencent/devops/common/api/util/OkhttpUtils.kt b/src/backend/ci/core/common/common-api/src/main/kotlin/com/tencent/devops/common/api/util/OkhttpUtils.kt index 6957f40de82..42f16fb1335 100644 --- a/src/backend/ci/core/common/common-api/src/main/kotlin/com/tencent/devops/common/api/util/OkhttpUtils.kt +++ b/src/backend/ci/core/common/common-api/src/main/kotlin/com/tencent/devops/common/api/util/OkhttpUtils.kt @@ -31,9 +31,9 @@ import com.tencent.devops.common.api.constant.CommonMessageCode.ERROR_HTTP_RESPO import com.tencent.devops.common.api.exception.ErrorCodeException import com.tencent.devops.common.api.exception.RemoteServiceException import okhttp3.ConnectionPool -import okhttp3.Headers -import okhttp3.HttpUrl -import okhttp3.MediaType +import okhttp3.Headers.Companion.toHeaders +import okhttp3.HttpUrl.Companion.toHttpUrl +import okhttp3.MediaType.Companion.toMediaTypeOrNull import okhttp3.MultipartBody import okhttp3.OkHttpClient import okhttp3.Request @@ -60,9 +60,9 @@ object OkhttpUtils { private val logger = LoggerFactory.getLogger(OkhttpUtils::class.java) - val jsonMediaType = MediaType.parse("application/json") + val jsonMediaType = "application/json".toMediaTypeOrNull() - private val octetStream = MediaType.parse("application/octet-stream") + private val octetStream = "application/octet-stream".toMediaTypeOrNull() private val trustAllCerts = arrayOf(object : X509TrustManager { @Throws(CertificateException::class) @@ -154,9 +154,9 @@ object OkhttpUtils { fun doRedirectHttp(request: Request, handleResponse: (Response) -> R): R { doHttp(redirectOkHttpClient, request).use { response -> if ( - request.method() == "POST" && - (response.code() == HttpURLConnection.HTTP_MOVED_PERM || - response.code() == HttpURLConnection.HTTP_MOVED_TEMP) + request.method == "POST" && + (response.code == HttpURLConnection.HTTP_MOVED_PERM || + response.code == HttpURLConnection.HTTP_MOVED_TEMP) ) { val location = response.header("Location") if (location != null) { @@ -224,20 +224,20 @@ object OkhttpUtils { val request = if (headers == null) { Request.Builder().url(url).get().build() } else { - Request.Builder().url(url).headers(Headers.of(headers)).get().build() + Request.Builder().url(url).headers(headers.toHeaders()).get().build() } longHttpClient.newCall(request).execute().use { response -> - if (response.code() == 404) { + if (response.code == 404) { logger.warn("The file $url is not exist") throw RemoteServiceException("File is not exist!") } if (!response.isSuccessful) { - logger.warn("FAIL|Download file from $url| message=${response.message()}| code=${response.code()}") + logger.warn("FAIL|Download file from $url| message=${response.message}| code=${response.code}") throw RemoteServiceException("Get file fail") } if (!destPath.parentFile.exists()) destPath.parentFile.mkdirs() val buf = ByteArray(4096) - response.body()!!.byteStream().use { bs -> + response.body!!.byteStream().use { bs -> var len = bs.read(buf) FileOutputStream(destPath).use { fos -> while (len != -1) { @@ -250,17 +250,17 @@ object OkhttpUtils { } fun downloadFile(response: Response, destPath: File) { - if (response.code() == 304) { + if (response.code == 304) { logger.info("file is newest, do not download to $destPath") return } if (!response.isSuccessful) { - logger.warn("fail to download the file because of ${response.message()} and code ${response.code()}") + logger.warn("fail to download the file because of ${response.message} and code ${response.code}") throw RemoteServiceException("Get file fail") } if (!destPath.parentFile.exists()) destPath.parentFile.mkdirs() val buf = ByteArray(4096) - response.body()!!.byteStream().use { bs -> + response.body!!.byteStream().use { bs -> var len = bs.read(buf) FileOutputStream(destPath).use { fos -> while (len != -1) { @@ -274,7 +274,7 @@ object OkhttpUtils { fun downloadFile(url: String, response: HttpServletResponse) { logger.info("downloadFile url is:$url") val httpResponse = getFileHttpResponse(url) - FileCopyUtils.copy(httpResponse.body()!!.byteStream(), response.outputStream) + FileCopyUtils.copy(httpResponse.body!!.byteStream(), response.outputStream) } fun downloadFile(url: String): javax.ws.rs.core.Response { @@ -286,7 +286,7 @@ object OkhttpUtils { return javax.ws.rs.core.Response.status(javax.ws.rs.core.Response.Status.INTERNAL_SERVER_ERROR).build() } return javax.ws.rs.core.Response - .ok(httpResponse.body()!!.byteStream(), javax.ws.rs.core.MediaType.APPLICATION_OCTET_STREAM_TYPE) + .ok(httpResponse.body!!.byteStream(), javax.ws.rs.core.MediaType.APPLICATION_OCTET_STREAM_TYPE) .header("Content-disposition", "attachment;filename=" + fileName!!) .header("Cache-Control", "no-cache").build() } @@ -295,8 +295,8 @@ object OkhttpUtils { val request = Request.Builder().url(url).get().build() val httpResponse = doLongHttp(request) if (!httpResponse.isSuccessful) { - logger.error("FAIL|Download file from $url| message=${httpResponse.message()}| code=${httpResponse.code()}") - throw RemoteServiceException(httpResponse.message()) + logger.error("FAIL|Download file from $url| message=${httpResponse.message}| code=${httpResponse.code}") + throw RemoteServiceException(httpResponse.message) } return httpResponse } @@ -316,7 +316,7 @@ object OkhttpUtils { var totalBytesRead = 0 var len: Int val result = CharArrayWriter() - body()!!.charStream().use { inStream -> + body!!.charStream().use { inStream -> result.use { outStream -> while ((inStream.read(buf).also { len = it }) != -1) { totalBytesRead += len @@ -335,7 +335,7 @@ object OkhttpUtils { fun validUrl(url: String): Boolean { return try { - HttpUrl.get(url) + url.toHttpUrl() true } catch (e: IllegalArgumentException) { logger.warn("url Invalid: ${e.message}") diff --git a/src/backend/ci/core/common/common-archive/src/main/kotlin/com/tencent/devops/common/archive/client/BkRepoClient.kt b/src/backend/ci/core/common/common-archive/src/main/kotlin/com/tencent/devops/common/archive/client/BkRepoClient.kt index fd6c252909f..d73c5340ac9 100644 --- a/src/backend/ci/core/common/common-archive/src/main/kotlin/com/tencent/devops/common/archive/client/BkRepoClient.kt +++ b/src/backend/ci/core/common/common-archive/src/main/kotlin/com/tencent/devops/common/archive/client/BkRepoClient.kt @@ -75,8 +75,9 @@ import com.tencent.devops.common.security.util.EnvironmentUtil import com.tencent.devops.common.service.config.CommonConfig import com.tencent.devops.common.service.utils.HomeHostUtil import okhttp3.Credentials -import okhttp3.Headers +import okhttp3.Headers.Companion.toHeaders import okhttp3.MediaType +import okhttp3.MediaType.Companion.toMediaTypeOrNull import okhttp3.Request import okhttp3.RequestBody import okio.BufferedSink @@ -136,7 +137,7 @@ class BkRepoClient constructor( .let { if (null == devopsToken) it else it.header("X-DEVOPS-TOKEN", devopsToken) } .post( RequestBody.create( - MediaType.parse("application/json; charset=utf-8"), + "application/json; charset=utf-8".toMediaTypeOrNull(), objectMapper.writeValueAsString(requestData) ) ) @@ -167,7 +168,7 @@ class BkRepoClient constructor( .let { if (null == devopsToken) it else it.header("X-DEVOPS-TOKEN", devopsToken) } .post( RequestBody.create( - MediaType.parse("application/json; charset=utf-8"), + "application/json; charset=utf-8".toMediaTypeOrNull(), objectMapper.writeValueAsString(requestData) ) ) @@ -206,7 +207,7 @@ class BkRepoClient constructor( .let { if (null == devopsToken) it else it.header("X-DEVOPS-TOKEN", devopsToken) } .post( RequestBody.create( - MediaType.parse("application/json; charset=utf-8"), + "application/json; charset=utf-8".toMediaTypeOrNull(), objectMapper.writeValueAsString(requestData) ) ).build() @@ -328,7 +329,7 @@ class BkRepoClient constructor( } override fun contentType(): MediaType? { - return MediaType.parse("application/octet-stream") + return "application/octet-stream".toMediaTypeOrNull() } } @@ -346,7 +347,7 @@ class BkRepoClient constructor( } val request = Request.Builder() .url(url) - .headers(Headers.of(header)) + .headers(header.toHeaders()) .put(requestBody).build() doRequest(request).resolveResponse>() } @@ -403,8 +404,8 @@ class BkRepoClient constructor( properties?.forEach { header["$METADATA_PREFIX${it.key}"] = tryEncode(it.value) } - requestBuilder.headers(Headers.of(header)) - .put(RequestBody.create(MediaType.parse("application/octet-stream"), file)) + requestBuilder.headers(header.toHeaders()) + .put(RequestBody.create("application/octet-stream".toMediaTypeOrNull(), file)) val request = requestBuilder.build() doRequest(request).resolveResponse>() } @@ -469,7 +470,7 @@ class BkRepoClient constructor( .let { if (null == devopsToken) it else it.header("X-DEVOPS-TOKEN", devopsToken) } .post( RequestBody.create( - MediaType.parse("application/json; charset=utf-8"), + "application/json; charset=utf-8".toMediaTypeOrNull(), objectMapper.writeValueAsString(requestData) ) ).build() @@ -507,7 +508,7 @@ class BkRepoClient constructor( .let { if (null == devopsToken) it else it.header("X-DEVOPS-TOKEN", devopsToken) } .post( RequestBody.create( - MediaType.parse("application/json; charset=utf-8"), + "application/json; charset=utf-8".toMediaTypeOrNull(), objectMapper.writeValueAsString(requestData) ) ).build() @@ -529,7 +530,7 @@ class BkRepoClient constructor( .let { if (null == devopsToken) it else it.header("X-DEVOPS-TOKEN", devopsToken) } .post( RequestBody.create( - MediaType.parse("application/json; charset=utf-8"), + "application/json; charset=utf-8".toMediaTypeOrNull(), objectMapper.writeValueAsString(requestData) ) ).build() @@ -664,16 +665,16 @@ class BkRepoClient constructor( .get() .build() OkhttpUtils.doHttp(request).use { response -> - if (response.code() == 404) { + if (response.code == 404) { logger.warn("file($url) not found") throw NotFoundException("File is not exist!") } if (!response.isSuccessful) { - val responseContent = response.body()?.string() - logger.warn("download file($url) failed, code ${response.code()}, content: $responseContent") - throw RemoteServiceException("download file failed", response.code(), responseContent) + val responseContent = response.body?.string() + logger.warn("download file($url) failed, code ${response.code}, content: $responseContent") + throw RemoteServiceException("download file failed", response.code, responseContent) } - FileCopyUtils.copy(response.body()!!.byteStream(), outputStream) + FileCopyUtils.copy(response.body!!.byteStream(), outputStream) } } @@ -786,7 +787,7 @@ class BkRepoClient constructor( .let { if (null == devopsToken) it else it.header("X-DEVOPS-TOKEN", devopsToken) } .post( RequestBody.create( - MediaType.parse("application/json; charset=utf-8"), + "application/json; charset=utf-8".toMediaTypeOrNull(), requestBody ) ).build() @@ -817,7 +818,7 @@ class BkRepoClient constructor( .let { if (null == devopsToken) it else it.header("X-DEVOPS-TOKEN", devopsToken) } .post( RequestBody.create( - MediaType.parse("application/json; charset=utf-8"), + "application/json; charset=utf-8".toMediaTypeOrNull(), requestBody ) ).build() @@ -859,7 +860,7 @@ class BkRepoClient constructor( .let { if (null == devopsToken) it else it.header("X-DEVOPS-TOKEN", devopsToken) } .post( RequestBody.create( - MediaType.parse("application/json; charset=utf-8"), + "application/json; charset=utf-8".toMediaTypeOrNull(), requestBody ) ).build() @@ -1067,7 +1068,7 @@ class BkRepoClient constructor( .let { if (null == devopsToken) it else it.header("X-DEVOPS-TOKEN", devopsToken) } .post( RequestBody.create( - MediaType.parse("application/json; charset=utf-8"), + "application/json; charset=utf-8".toMediaTypeOrNull(), objectMapper.writeValueAsString(mapOf("expires" to expires)) ) ) @@ -1115,7 +1116,7 @@ class BkRepoClient constructor( .let { if (null == devopsToken) it else it.header("X-DEVOPS-TOKEN", devopsToken) } .post( RequestBody.create( - MediaType.parse("application/json; charset=utf-8"), + "application/json; charset=utf-8".toMediaTypeOrNull(), requestBody ) ).build() @@ -1126,13 +1127,13 @@ class BkRepoClient constructor( try { return OkhttpUtils.doHttp(request) } catch (e: IOException) { - throw RemoteServiceException("request api[${request.url().url()}] error: ${e.localizedMessage}") + throw RemoteServiceException("request api[${request.url.toUrl()}] error: ${e.localizedMessage}") } } private inline fun okhttp3.Response.resolveResponse(allowCode: Int? = null): T? { this.use { - val responseContent = this.body()!!.string() + val responseContent = this.body!!.string() if (this.isSuccessful) { return objectMapper.readValue(responseContent, jacksonTypeRef()) } @@ -1140,13 +1141,13 @@ class BkRepoClient constructor( val responseData = try { objectMapper.readValue>(responseContent) } catch (e: JacksonException) { - throw RemoteServiceException(responseContent, this.code()) + throw RemoteServiceException(responseContent, this.code) } if (allowCode == responseData.code) { logger.info("request bkrepo api failed but it can be allowed: ${responseData.message}") return null } - throw RemoteServiceException(responseData.message ?: responseData.code.toString(), this.code()) + throw RemoteServiceException(responseData.message ?: responseData.code.toString(), this.code) } } diff --git a/src/backend/ci/core/common/common-archive/src/main/kotlin/com/tencent/devops/common/archive/client/DirectBkRepoClient.kt b/src/backend/ci/core/common/common-archive/src/main/kotlin/com/tencent/devops/common/archive/client/DirectBkRepoClient.kt index 550dfcea5cb..c872512b36c 100644 --- a/src/backend/ci/core/common/common-archive/src/main/kotlin/com/tencent/devops/common/archive/client/DirectBkRepoClient.kt +++ b/src/backend/ci/core/common/common-archive/src/main/kotlin/com/tencent/devops/common/archive/client/DirectBkRepoClient.kt @@ -29,7 +29,7 @@ package com.tencent.devops.common.archive.client import com.tencent.devops.common.api.exception.RemoteServiceException import com.tencent.devops.common.api.util.OkhttpUtils -import okhttp3.MediaType +import okhttp3.MediaType.Companion.toMediaTypeOrNull import okhttp3.Request import okhttp3.RequestBody import org.apache.commons.lang3.StringUtils @@ -67,11 +67,11 @@ class DirectBkRepoClient { .header(BK_REPO_OVERRIDE, override.toString()) .header(BK_REPO_UID, userId) .header(BK_REPO_METADATA, Base64.getEncoder().encodeToString(buildMetadataHeader(metadata).toByteArray())) - .put(RequestBody.create(MediaType.parse("application/octet-stream"), file)) + .put(RequestBody.create("application/octet-stream".toMediaTypeOrNull(), file)) .build() OkhttpUtils.doHttp(request).use { response -> if (!response.isSuccessful) { - throw RemoteServiceException("upload file failed: ${response.body()!!.string()}", response.code()) + throw RemoteServiceException("upload file failed: ${response.body!!.string()}", response.code) } } } @@ -98,11 +98,11 @@ class DirectBkRepoClient { .header(BK_REPO_OVERRIDE, override.toString()) .header(BK_REPO_UID, userId) .header(BK_REPO_METADATA, Base64.getEncoder().encodeToString(buildMetadataHeader(metadata).toByteArray())) - .put(RequestBody.create(MediaType.parse("application/octet-stream"), byteArray)) + .put(RequestBody.create("application/octet-stream".toMediaTypeOrNull(), byteArray)) .build() OkhttpUtils.doHttp(request).use { response -> if (!response.isSuccessful) { - throw RemoteServiceException("upload file failed: ${response.body()!!.string()}", response.code()) + throw RemoteServiceException("upload file failed: ${response.body!!.string()}", response.code) } return url } diff --git a/src/backend/ci/core/common/common-auth/common-auth-api/src/main/kotlin/com/tencent/devops/common/auth/service/IamEsbService.kt b/src/backend/ci/core/common/common-auth/common-auth-api/src/main/kotlin/com/tencent/devops/common/auth/service/IamEsbService.kt index dc0b5d48e9d..75857dfe898 100644 --- a/src/backend/ci/core/common/common-auth/common-auth-api/src/main/kotlin/com/tencent/devops/common/auth/service/IamEsbService.kt +++ b/src/backend/ci/core/common/common-auth/common-auth-api/src/main/kotlin/com/tencent/devops/common/auth/service/IamEsbService.kt @@ -33,7 +33,7 @@ import com.tencent.devops.common.api.exception.RemoteServiceException import com.tencent.devops.common.api.util.OkhttpUtils import com.tencent.devops.common.auth.api.pojo.EsbCreateApiReq import com.tencent.devops.common.auth.api.pojo.EsbPermissionUrlReq -import okhttp3.MediaType +import okhttp3.MediaType.Companion.toMediaTypeOrNull import okhttp3.Request import okhttp3.RequestBody import org.slf4j.LoggerFactory @@ -57,7 +57,7 @@ class IamEsbService { val content = objectMapper.writeValueAsString(iamCreateApiReq) logger.info("v3 createRelationResource url[$url]") logger.info("v3 createRelationResource body[$content]") - val mediaType = MediaType.parse("application/json; charset=utf-8") + val mediaType = "application/json; charset=utf-8".toMediaTypeOrNull() val requestBody = RequestBody.create(mediaType, content) val request = Request.Builder().url(url) .post(requestBody) @@ -68,7 +68,7 @@ class IamEsbService { // 请求错误 throw RemoteServiceException("bkiam v3 request failed, response: ($it)") } - val responseStr = it.body()!!.string() + val responseStr = it.body!!.string() logger.info("v3 createRelationResource responseStr[$responseStr]") val iamApiRes = objectMapper.readValue>(responseStr) if (iamApiRes["code"] != 0 || iamApiRes["result"] == false) { @@ -87,7 +87,7 @@ class IamEsbService { iamPermissionUrl.bk_app_code = appCode!! iamPermissionUrl.bk_app_secret = appSecret!! val content = objectMapper.writeValueAsString(iamPermissionUrl) - val mediaType = MediaType.parse("application/json; charset=utf-8") + val mediaType = "application/json; charset=utf-8".toMediaTypeOrNull() val requestBody = RequestBody.create(mediaType, content) logger.info("getPermissionUrl url:$url") logger.info("getPermissionUrl content:$content body:$requestBody") @@ -99,7 +99,7 @@ class IamEsbService { // 请求错误 throw RemoteServiceException("bkiam v3 request failed, response: ($it)") } - val responseStr = it.body()!!.string() + val responseStr = it.body!!.string() logger.info("v3 getPermissionUrl responseStr[$responseStr]") val iamApiRes = objectMapper.readValue>(responseStr) if (iamApiRes["code"] != 0 || iamApiRes["result"] == false) { diff --git a/src/backend/ci/core/common/common-auth/common-auth-blueking/src/main/kotlin/com/tencent/devops/common/auth/api/BkAuthProjectApi.kt b/src/backend/ci/core/common/common-auth/common-auth-blueking/src/main/kotlin/com/tencent/devops/common/auth/api/BkAuthProjectApi.kt index 0d7d86a35f5..8984752e253 100644 --- a/src/backend/ci/core/common/common-auth/common-auth-blueking/src/main/kotlin/com/tencent/devops/common/auth/api/BkAuthProjectApi.kt +++ b/src/backend/ci/core/common/common-auth/common-auth-blueking/src/main/kotlin/com/tencent/devops/common/auth/api/BkAuthProjectApi.kt @@ -64,10 +64,10 @@ class BkAuthProjectApi constructor( } val request = Request.Builder().url(url).get().build() OkhttpUtils.doHttp(request).use { response -> - val responseContent = response.body()!!.string() + val responseContent = response.body!!.string() if (!response.isSuccessful) { logger.error("Fail to get project users. $responseContent") - throw RemoteServiceException("Fail to get project users", response.code(), responseContent) + throw RemoteServiceException("Fail to get project users", response.code, responseContent) } val responseObject = objectMapper.readValue>>(responseContent) diff --git a/src/backend/ci/core/common/common-auth/common-auth-blueking/src/main/kotlin/com/tencent/devops/common/auth/api/BkAuthTokenApi.kt b/src/backend/ci/core/common/common-auth/common-auth-blueking/src/main/kotlin/com/tencent/devops/common/auth/api/BkAuthTokenApi.kt index 4cf167191d2..74dde6cced1 100644 --- a/src/backend/ci/core/common/common-auth/common-auth-blueking/src/main/kotlin/com/tencent/devops/common/auth/api/BkAuthTokenApi.kt +++ b/src/backend/ci/core/common/common-auth/common-auth-blueking/src/main/kotlin/com/tencent/devops/common/auth/api/BkAuthTokenApi.kt @@ -34,7 +34,7 @@ import com.tencent.devops.common.api.util.OkhttpUtils import com.tencent.devops.common.auth.code.AuthServiceCode import com.tencent.devops.common.redis.RedisLock import com.tencent.devops.common.redis.RedisOperation -import okhttp3.MediaType +import okhttp3.MediaType.Companion.toMediaTypeOrNull import okhttp3.Request import okhttp3.RequestBody import org.slf4j.LoggerFactory @@ -103,7 +103,7 @@ class BkAuthTokenApi constructor( ) val content = objectMapper.writeValueAsString(accessTokenRequest) - val mediaType = MediaType.parse("application/json; charset=utf-8") + val mediaType = "application/json; charset=utf-8".toMediaTypeOrNull() val requestBody = RequestBody.create(mediaType, content) val request = Request.Builder().url(url) .header("X-BK-APP-CODE", this.appCode) @@ -113,7 +113,7 @@ class BkAuthTokenApi constructor( var accessToken = "" OkhttpUtils.doHttp(request).use { response -> - val responseContent = response.body()!!.string() + val responseContent = response.body!!.string() // logger.info("Get accessToken response: $responseContent") if (!response.isSuccessful) { logger.error("Get accessToken response: $responseContent") diff --git a/src/backend/ci/core/common/common-auth/common-auth-blueking/src/main/kotlin/com/tencent/devops/common/auth/api/utils/AuthUtils.kt b/src/backend/ci/core/common/common-auth/common-auth-blueking/src/main/kotlin/com/tencent/devops/common/auth/api/utils/AuthUtils.kt index e2dda0db6e6..2dd202c4461 100644 --- a/src/backend/ci/core/common/common-auth/common-auth-blueking/src/main/kotlin/com/tencent/devops/common/auth/api/utils/AuthUtils.kt +++ b/src/backend/ci/core/common/common-auth/common-auth-blueking/src/main/kotlin/com/tencent/devops/common/auth/api/utils/AuthUtils.kt @@ -30,7 +30,7 @@ package com.tencent.devops.common.auth.api.utils import com.tencent.devops.common.api.exception.RemoteServiceException import com.tencent.devops.common.api.util.OkhttpUtils import com.tencent.devops.common.auth.api.BkAuthProperties -import okhttp3.MediaType +import okhttp3.MediaType.Companion.toMediaTypeOrNull import okhttp3.Request import okhttp3.RequestBody import org.json.JSONArray @@ -65,7 +65,7 @@ class AuthUtils constructor(xBkAuthProperties: BkAuthProperties) { * 执行post请求 */ fun doAuthPostRequest(uri: String, jsonbody: JSONObject, bkAppCode: String, bkAppSecret: String): JSONObject { - val body = RequestBody.create(MediaType.parse("application/json"), jsonbody.toString()) + val body = RequestBody.create("application/json".toMediaTypeOrNull(), jsonbody.toString()) val url = this.getAuthRequestUrl(uri, null) logger.debug("bkiam post url: {}, body: {}", url, jsonbody) @@ -84,7 +84,7 @@ class AuthUtils constructor(xBkAuthProperties: BkAuthProperties) { * 执行put请求 */ fun doAuthPutRequest(uri: String, jsonbody: JSONObject, xBkAppCode: String, xBkAppSecret: String): JSONObject { - val body = RequestBody.create(MediaType.parse("application/json"), jsonbody.toString()) + val body = RequestBody.create("application/json".toMediaTypeOrNull(), jsonbody.toString()) val url = this.getAuthRequestUrl(uri, null) logger.debug("bkiam put url: {}, body: {}", url, jsonbody) @@ -103,7 +103,7 @@ class AuthUtils constructor(xBkAuthProperties: BkAuthProperties) { * 执行delete请求 */ fun doAuthDeleteRequest(uri: String, jsonbody: JSONObject, xBkAppCode: String, xBkAppSecret: String): JSONObject { - val body = RequestBody.create(MediaType.parse("application/json"), jsonbody.toString()) + val body = RequestBody.create("application/json".toMediaTypeOrNull(), jsonbody.toString()) val url = this.getAuthRequestUrl(uri, null) logger.debug("bkiam delete url: {}", url) @@ -125,14 +125,14 @@ class AuthUtils constructor(xBkAuthProperties: BkAuthProperties) { val response = OkhttpUtils.doHttp(request) // val response = okclient.newCall(request).execute() if (response.isSuccessful) { - val responseStr = response.body()!!.string() + val responseStr = response.body!!.string() logger.debug("bkiam response: $responseStr") jsonObject = JSONObject(responseStr) // 由于成功与失败时返回的json结构不同,code不为0,失败情况需直接去除data字段 if (jsonObject["data"] !is JSONArray) jsonObject.remove("data") } else { - jsonObject.put("msg", "http code:" + response.code()) + jsonObject.put("msg", "http code:" + response.code) throw RemoteServiceException("bkiam request failed, response: ($response)") } diff --git a/src/backend/ci/core/common/common-client/src/main/kotlin/com/tencent/devops/common/client/ms/MicroServiceTarget.kt b/src/backend/ci/core/common/common-client/src/main/kotlin/com/tencent/devops/common/client/ms/MicroServiceTarget.kt index 330a51a9f25..76371bd1ab9 100644 --- a/src/backend/ci/core/common/common-client/src/main/kotlin/com/tencent/devops/common/client/ms/MicroServiceTarget.kt +++ b/src/backend/ci/core/common/common-client/src/main/kotlin/com/tencent/devops/common/client/ms/MicroServiceTarget.kt @@ -37,6 +37,7 @@ import com.tencent.devops.common.service.utils.MessageCodeUtil import feign.Request import feign.RequestTemplate import org.apache.commons.lang3.RandomUtils +import org.apache.commons.lang3.StringUtils import org.slf4j.LoggerFactory import org.springframework.cloud.client.ServiceInstance import org.springframework.cloud.client.discovery.composite.CompositeDiscoveryClient @@ -92,7 +93,12 @@ class MicroServiceTarget constructor( override fun name() = serviceName - private fun ServiceInstance.url() = "${if (isSecure) "https" else "http"}://$host:$port/api" + private fun ServiceInstance.url(): String { + val finalHost = if (StringUtils.isNotBlank(host) && host.contains(":") && !host.startsWith("[")) { + "[$host]" // 兼容IPv6 + } else host + return "${if (isSecure) "https" else "http"}://$finalHost:$port/api" + } companion object { private val logger = LoggerFactory.getLogger(MicroServiceTarget::class.java) diff --git a/src/backend/ci/core/common/common-expression/src/test/kotlin/com/tencent/devops/common/expression/expression/specialFuctions/hashFiles/HashFilesFunctionTest.kt b/src/backend/ci/core/common/common-expression/src/test/kotlin/com/tencent/devops/common/expression/expression/specialFuctions/hashFiles/HashFilesFunctionTest.kt index 1353832bed4..f65cb065926 100644 --- a/src/backend/ci/core/common/common-expression/src/test/kotlin/com/tencent/devops/common/expression/expression/specialFuctions/hashFiles/HashFilesFunctionTest.kt +++ b/src/backend/ci/core/common/common-expression/src/test/kotlin/com/tencent/devops/common/expression/expression/specialFuctions/hashFiles/HashFilesFunctionTest.kt @@ -40,6 +40,7 @@ import com.tencent.devops.common.expression.expression.FunctionInfo import com.tencent.devops.common.expression.expression.sdk.NamedValueInfo import org.junit.jupiter.api.Assertions import org.junit.jupiter.api.BeforeAll +import org.junit.jupiter.api.Disabled import org.junit.jupiter.api.DisplayName import org.junit.jupiter.api.Nested import org.junit.jupiter.api.Test @@ -87,6 +88,7 @@ internal class HashFilesFunctionTest { "hashFiles('test?ata/sha255H???') => 2f11d1771e05dde5d1c004cea5211741d5bbd4ac82704d714005ccb90f94d0e0" ] ) + @Disabled fun evaluateCore(evaluate: String) { val (exp, expect) = evaluate.split(" => ") Assertions.assertEquals( diff --git a/src/backend/ci/core/common/common-scm/src/main/kotlin/com/tencent/devops/scm/code/git/api/GitApi.kt b/src/backend/ci/core/common/common-scm/src/main/kotlin/com/tencent/devops/scm/code/git/api/GitApi.kt index 3ca0d8044c1..486a417a5e3 100644 --- a/src/backend/ci/core/common/common-scm/src/main/kotlin/com/tencent/devops/scm/code/git/api/GitApi.kt +++ b/src/backend/ci/core/common/common-scm/src/main/kotlin/com/tencent/devops/scm/code/git/api/GitApi.kt @@ -49,12 +49,12 @@ import com.tencent.devops.scm.pojo.GitMember import com.tencent.devops.scm.pojo.GitMrChangeInfo import com.tencent.devops.scm.pojo.GitMrInfo import com.tencent.devops.scm.pojo.GitMrReviewInfo +import com.tencent.devops.scm.pojo.TapdWorkItem import io.micrometer.core.instrument.MeterRegistry import io.micrometer.core.instrument.Tag import io.micrometer.core.instrument.Tags import io.micrometer.core.instrument.Timer -import com.tencent.devops.scm.pojo.TapdWorkItem -import okhttp3.MediaType +import okhttp3.MediaType.Companion.toMediaTypeOrNull import okhttp3.Request import okhttp3.RequestBody import org.slf4j.LoggerFactory @@ -340,7 +340,7 @@ open class GitApi { } } - private val mediaType = MediaType.parse("application/json; charset=utf-8") + private val mediaType = "application/json; charset=utf-8".toMediaTypeOrNull() fun post(host: String, token: String, url: String, body: String) = request(host, token, url, "").post(RequestBody.create(mediaType, body)).build() @@ -369,9 +369,9 @@ open class GitApi { try { return OkhttpUtils.doRedirectHttp(request) { response -> if (!response.isSuccessful) { - handleApiException(operation, response.code(), response.body()?.string() ?: "") + handleApiException(operation, response.code, response.body?.string() ?: "") } - JsonUtil.getObjectMapper().readValue(response.body()!!.string(), classOfT) + JsonUtil.getObjectMapper().readValue(response.body!!.string(), classOfT) } } catch (err: Exception) { exceptionClass = err.javaClass.simpleName @@ -416,9 +416,9 @@ open class GitApi { try { OkhttpUtils.doHttp(request).use { response -> if (!response.isSuccessful) { - handleApiException(operation, response.code(), response.body()?.string() ?: "") + handleApiException(operation, response.code, response.body?.string() ?: "") } - return response.body()!!.string() + return response.body!!.string() } } catch (err: Exception) { exceptionClass = err.javaClass.simpleName diff --git a/src/backend/ci/core/common/common-scm/src/main/kotlin/com/tencent/devops/scm/code/svn/api/SVNApi.kt b/src/backend/ci/core/common/common-scm/src/main/kotlin/com/tencent/devops/scm/code/svn/api/SVNApi.kt index 32c75ce8c11..835e72bd2d8 100644 --- a/src/backend/ci/core/common/common-scm/src/main/kotlin/com/tencent/devops/scm/code/svn/api/SVNApi.kt +++ b/src/backend/ci/core/common/common-scm/src/main/kotlin/com/tencent/devops/scm/code/svn/api/SVNApi.kt @@ -37,7 +37,7 @@ import com.tencent.devops.common.api.util.JsonUtil import com.tencent.devops.common.api.util.OkhttpUtils import com.tencent.devops.scm.config.SVNConfig import com.tencent.devops.scm.exception.ScmException -import okhttp3.MediaType +import okhttp3.MediaType.Companion.toMediaTypeOrNull import okhttp3.Request import okhttp3.RequestBody import org.slf4j.LoggerFactory @@ -74,7 +74,7 @@ object SVNApi { fun addWebhooks(svnConfig: SVNConfig, username: String, url: String, hookUrl: String) { val request = request(svnConfig, composePostUrl(svnConfig, toHttpUrl(url), hookUrl, username)) - .post(RequestBody.create(MediaType.parse("application/json; charset=utf-8"), "")) + .post(RequestBody.create("application/json; charset=utf-8".toMediaTypeOrNull(), "")) .build() val body = getBody(request) logger.info("Get the add hook response $body") @@ -99,7 +99,7 @@ object SVNApi { val request = Request.Builder() .url(url) .addHeader("ApiKey", svnConfig.apiKey).addHeader("Content-type", "application/json") - .post(RequestBody.create(MediaType.parse("application/json;charset=utf-8"), requestBody)) + .post(RequestBody.create("application/json;charset=utf-8".toMediaTypeOrNull(), requestBody)) .build() val body = getBody(request) logger.info("lock the svn repo response $body") @@ -126,7 +126,7 @@ object SVNApi { val request = Request.Builder() .url(url) .addHeader("ApiKey", svnConfig.apiKey).addHeader("Content-type", "application/json") - .post(RequestBody.create(MediaType.parse("application/json;charset=utf-8"), requestBody)) + .post(RequestBody.create("application/json;charset=utf-8".toMediaTypeOrNull(), requestBody)) .build() val body = getBody(request) logger.info("unlock the svn repo response $body") @@ -144,12 +144,12 @@ object SVNApi { OkhttpUtils.doHttp(request).use { response -> if (!response.isSuccessful) { when { - response.code() == 401 -> throw ScmException("工程仓库访问未授权", ScmType.CODE_SVN.name) - response.code() == 404 -> throw ScmException("工程仓库不存在", ScmType.CODE_SVN.name) + response.code == 401 -> throw ScmException("工程仓库访问未授权", ScmType.CODE_SVN.name) + response.code == 404 -> throw ScmException("工程仓库不存在", ScmType.CODE_SVN.name) else -> throw ScmException("工程仓库访问异常", ScmType.CODE_SVN.name) } } - return response.body()!!.string() + return response.body!!.string() } } diff --git a/src/backend/ci/core/common/common-service/src/main/kotlin/com/tencent/devops/common/service/utils/CommonUtils.kt b/src/backend/ci/core/common/common-service/src/main/kotlin/com/tencent/devops/common/service/utils/CommonUtils.kt index 1b6795721f0..5efc4f25a27 100755 --- a/src/backend/ci/core/common/common-service/src/main/kotlin/com/tencent/devops/common/service/utils/CommonUtils.kt +++ b/src/backend/ci/core/common/common-service/src/main/kotlin/com/tencent/devops/common/service/utils/CommonUtils.kt @@ -142,7 +142,7 @@ object CommonUtils { "?userId=$userId&fileChannelType=$fileChannelType&logo=$logo" logger.info("the serviceUrl is:$serviceUrl") OkhttpUtils.uploadFile(serviceUrl, file).use { response -> - val responseContent = response.body()!!.string() + val responseContent = response.body!!.string() logger.error("uploadFile responseContent is: $responseContent") if (!response.isSuccessful) { return MessageCodeUtil.generateResponseDataObject(CommonMessageCode.SYSTEM_ERROR) diff --git a/src/backend/ci/core/common/common-third-sdk/common-sdk-util/src/main/kotlin/com/tencent/devops/common/sdk/util/SdkHttpUtil.kt b/src/backend/ci/core/common/common-third-sdk/common-sdk-util/src/main/kotlin/com/tencent/devops/common/sdk/util/SdkHttpUtil.kt index fd082b65853..8588ed4702a 100644 --- a/src/backend/ci/core/common/common-third-sdk/common-sdk-util/src/main/kotlin/com/tencent/devops/common/sdk/util/SdkHttpUtil.kt +++ b/src/backend/ci/core/common/common-third-sdk/common-sdk-util/src/main/kotlin/com/tencent/devops/common/sdk/util/SdkHttpUtil.kt @@ -33,8 +33,8 @@ import com.tencent.devops.common.sdk.enums.HttpMethod import com.tencent.devops.common.sdk.enums.HttpStatus import com.tencent.devops.common.sdk.exception.SdkException import com.tencent.devops.common.sdk.exception.SdkNotFoundException -import okhttp3.Headers -import okhttp3.MediaType +import okhttp3.Headers.Companion.toHeaders +import okhttp3.MediaType.Companion.toMediaTypeOrNull import okhttp3.OkHttpClient import okhttp3.Request import okhttp3.RequestBody @@ -91,7 +91,7 @@ object SdkHttpUtil { fun build(url: String, headers: Map? = null): Request.Builder { val builder = Request.Builder().url(url) if (headers != null) { - builder.headers(Headers.of(headers)) + builder.headers(headers.toHeaders()) } return builder } @@ -99,16 +99,16 @@ object SdkHttpUtil { fun request(request: Request): String { val response = okHttpClient.newCall(request).execute() return response.use { resp -> - val responseContent = resp.body()?.string() ?: "" + val responseContent = resp.body?.string() ?: "" if (!resp.isSuccessful) { logger.error( - "Fail to request(${request.url()})" + - " with code ${resp.code()} message ${resp.message()} and response $responseContent" + "Fail to request(${request.url})" + + " with code ${resp.code} message ${resp.message} and response $responseContent" ) - if (resp.code() == HttpStatus.NOT_FOUND.statusCode) { + if (resp.code == HttpStatus.NOT_FOUND.statusCode) { throw SdkNotFoundException(errMsg = responseContent) } - throw SdkException(errCode = resp.code(), errMsg = responseContent) + throw SdkException(errCode = resp.code, errMsg = responseContent) } responseContent } @@ -118,7 +118,7 @@ object SdkHttpUtil { * 生成post请求体对象 */ fun generaRequestBody(jsonStr: String, mediaType: String = "application/json"): RequestBody { - return RequestBody.create(MediaType.parse(mediaType), jsonStr) + return RequestBody.create(mediaType.toMediaTypeOrNull(), jsonStr) } /** diff --git a/src/backend/ci/core/common/common-webhook/biz-common-webhook/src/main/kotlin/com/tencent/devops/common/webhook/service/code/filter/ThirdFilter.kt b/src/backend/ci/core/common/common-webhook/biz-common-webhook/src/main/kotlin/com/tencent/devops/common/webhook/service/code/filter/ThirdFilter.kt index a814b88756f..b267c87f2bb 100644 --- a/src/backend/ci/core/common/common-webhook/biz-common-webhook/src/main/kotlin/com/tencent/devops/common/webhook/service/code/filter/ThirdFilter.kt +++ b/src/backend/ci/core/common/common-webhook/biz-common-webhook/src/main/kotlin/com/tencent/devops/common/webhook/service/code/filter/ThirdFilter.kt @@ -9,7 +9,7 @@ import com.tencent.devops.common.webhook.service.code.GitScmService import com.tencent.devops.common.webhook.service.code.pojo.ThirdFilterBody import com.tencent.devops.common.webhook.service.code.pojo.ThirdFilterResult import io.github.resilience4j.circuitbreaker.CircuitBreakerRegistry -import okhttp3.MediaType +import okhttp3.MediaType.Companion.toMediaTypeOrNull import okhttp3.Request import okhttp3.RequestBody import org.slf4j.LoggerFactory @@ -64,7 +64,7 @@ class ThirdFilter( val builder = Request.Builder() .url(thirdUrl!!) .post( - RequestBody.create(MediaType.parse("application/json;charset=utf-8"), body) + RequestBody.create("application/json;charset=utf-8".toMediaTypeOrNull(), body) ) if (!thirdSecretToken.isNullOrBlank()) { val thirdSecretTokenValue = gitScmService.getCredential( @@ -75,11 +75,11 @@ class ThirdFilter( } return HttpRetryUtils.retry(MAX_RETRY_COUNT) { OkhttpUtils.doShortHttp(request = builder.build()).use { response -> - val data = response.body()!!.string() + val data = response.body!!.string() if (!response.isSuccessful) { throw CustomException( - status = Response.Status.fromStatusCode(response.code()) ?: Response.Status.BAD_REQUEST, - message = "Failed to call third filter|code:${response.code()}|data:$data" + status = Response.Status.fromStatusCode(response.code) ?: Response.Status.BAD_REQUEST, + message = "Failed to call third filter|code:${response.code}|data:$data" ) } logger.info("$pipelineId|third filter result:$data") diff --git a/src/backend/ci/core/common/common-wechatwork/src/main/kotlin/com/tencent/devops/common/wechatwork/WechatWorkRobotService.kt b/src/backend/ci/core/common/common-wechatwork/src/main/kotlin/com/tencent/devops/common/wechatwork/WechatWorkRobotService.kt index 21124d6b131..2af3177835a 100644 --- a/src/backend/ci/core/common/common-wechatwork/src/main/kotlin/com/tencent/devops/common/wechatwork/WechatWorkRobotService.kt +++ b/src/backend/ci/core/common/common-wechatwork/src/main/kotlin/com/tencent/devops/common/wechatwork/WechatWorkRobotService.kt @@ -5,7 +5,7 @@ import com.tencent.devops.common.api.util.OkhttpUtils import com.tencent.devops.common.wechatwork.model.robot.MsgInfo import com.tencent.devops.common.wechatwork.model.robot.RobotMarkdownSendMsg import com.tencent.devops.common.wechatwork.model.robot.RobotTextSendMsg -import okhttp3.MediaType +import okhttp3.MediaType.Companion.toMediaTypeOrNull import okhttp3.Request import okhttp3.RequestBody import org.slf4j.LoggerFactory @@ -19,14 +19,14 @@ class WechatWorkRobotService @Autowired constructor( fun send(jsonString: String) { val url = "${robotCustomConfig.weworkUrl}/cgi-bin/webhook/send?key=${robotCustomConfig.robotKey}" - val requestBody = RequestBody.create(MediaType.parse("application/json"), jsonString) + val requestBody = RequestBody.create("application/json".toMediaTypeOrNull(), jsonString) logger.info("sendRobot: $url, body:$jsonString") val sendRequest = Request.Builder() .url(url) .post(requestBody) .build() OkhttpUtils.doHttp(sendRequest).use { response -> - val responseContent = response.body()!!.string() + val responseContent = response.body!!.string() if (!response.isSuccessful) { logger.warn("$responseContent") throw RuntimeException("Fail to send msg to yqwx. $responseContent") diff --git a/src/backend/ci/core/common/common-wechatwork/src/main/kotlin/com/tencent/devops/common/wechatwork/WechatWorkService.kt b/src/backend/ci/core/common/common-wechatwork/src/main/kotlin/com/tencent/devops/common/wechatwork/WechatWorkService.kt index 3c0dbe9ac29..063950dddb3 100644 --- a/src/backend/ci/core/common/common-wechatwork/src/main/kotlin/com/tencent/devops/common/wechatwork/WechatWorkService.kt +++ b/src/backend/ci/core/common/common-wechatwork/src/main/kotlin/com/tencent/devops/common/wechatwork/WechatWorkService.kt @@ -55,7 +55,7 @@ import com.tencent.devops.common.wechatwork.model.sendmessage.richtext.RichtextC import com.tencent.devops.common.wechatwork.model.sendmessage.richtext.RichtextMessage import com.tencent.devops.common.wechatwork.model.sendmessage.richtext.RichtextText import com.tencent.devops.common.wechatwork.model.sendmessage.richtext.RichtextTextText -import okhttp3.MediaType +import okhttp3.MediaType.Companion.toMediaTypeOrNull import okhttp3.MultipartBody import okhttp3.Request import okhttp3.RequestBody @@ -179,7 +179,7 @@ class WechatWorkService @Autowired constructor( .build() OkhttpUtils.doHttp(accessTokenRequest).use { response -> // httpClient.newCall(accessTokenRequest).execute().use { response -> - val responseContent = response.body()!!.string() + val responseContent = response.body!!.string() if (!response.isSuccessful) { throw RuntimeException("Fail to send msg to yqwx. $responseContent") } @@ -216,14 +216,14 @@ class WechatWorkService @Autowired constructor( val jsonString = JsonUtil.toJson(requestData) val sendURL = "$wechatWorkApiURL/cgi-bin/tencent/chat/send?access_token=$accessToken" - val requestBody = RequestBody.create(MediaType.parse("application/json"), jsonString) + val requestBody = RequestBody.create("application/json".toMediaTypeOrNull(), jsonString) val sendRequest = Request.Builder() .url(sendURL) .post(requestBody) .build() OkhttpUtils.doHttp(sendRequest).use { response -> // httpClient.newCall(sendRequest).execute().use { response -> - val responseContent = response.body()!!.string() + val responseContent = response.body!!.string() if (!response.isSuccessful) { throw RuntimeException("Fail to send msg to yqwx. $responseContent") } @@ -250,14 +250,14 @@ class WechatWorkService @Autowired constructor( val jsonString = JsonUtil.toJson(requestData) val sendURL = "$wechatWorkApiURL/cgi-bin/tencent/chat/send?access_token=$accessToken" - val requestBody = RequestBody.create(MediaType.parse("application/json"), jsonString) + val requestBody = RequestBody.create("application/json".toMediaTypeOrNull(), jsonString) val sendRequest = Request.Builder() .url(sendURL) .post(requestBody) .build() OkhttpUtils.doHttp(sendRequest).use { response -> // httpClient.newCall(sendRequest).execute().use { response -> - val responseContent = response.body()!!.string() + val responseContent = response.body!!.string() if (!response.isSuccessful) { throw RuntimeException("Fail to send msg to yqwx. $responseContent") } @@ -284,14 +284,14 @@ class WechatWorkService @Autowired constructor( val jsonString = JsonUtil.toJson(requestData) val sendURL = "$wechatWorkApiURL/cgi-bin/tencent/chat/send?access_token=$accessToken" - val requestBody = RequestBody.create(MediaType.parse("application/json"), jsonString) + val requestBody = RequestBody.create("application/json".toMediaTypeOrNull(), jsonString) val sendRequest = Request.Builder() .url(sendURL) .post(requestBody) .build() OkhttpUtils.doHttp(sendRequest).use { response -> // httpClient.newCall(sendRequest).execute().use { response -> - val responseContent = response.body()!!.string() + val responseContent = response.body!!.string() if (!response.isSuccessful) { throw RuntimeException("Fail to send msg to yqwx. $responseContent") } @@ -306,14 +306,14 @@ class WechatWorkService @Autowired constructor( val jsonString = JsonUtil.toJson(richtextMessage, false) val sendURL = "$wechatWorkApiURL/cgi-bin/tencent/chat/send?access_token=$accessToken" - val requestBody = RequestBody.create(MediaType.parse("application/json"), jsonString) + val requestBody = RequestBody.create("application/json".toMediaTypeOrNull(), jsonString) val sendRequest = Request.Builder() .url(sendURL) .post(requestBody) .build() OkhttpUtils.doHttp(sendRequest).use { response -> // httpClient.newCall(sendRequest).execute().use { response -> - val responseContent = response.body()!!.string() + val responseContent = response.body!!.string() if (!response.isSuccessful) { throw RuntimeException("Fail to send msg to yqwx. $responseContent") } @@ -356,14 +356,14 @@ class WechatWorkService @Autowired constructor( val jsonString = JsonUtil.toJson(requestData) val sendURL = "$wechatWorkApiURL/cgi-bin/tencent/chat/send?access_token=$accessToken" - val requestBody = RequestBody.create(MediaType.parse("application/json"), jsonString) + val requestBody = RequestBody.create("application/json".toMediaTypeOrNull(), jsonString) val sendRequest = Request.Builder() .url(sendURL) .post(requestBody) .build() OkhttpUtils.doHttp(sendRequest).use { response -> // httpClient.newCall(sendRequest).execute().use { response -> - val responseContent = response.body()!!.string() + val responseContent = response.body!!.string() if (!response.isSuccessful) { throw RuntimeException("Fail to send msg to yqwx. $responseContent") } @@ -384,14 +384,14 @@ class WechatWorkService @Autowired constructor( val jsonString = JsonUtil.toJson(requestData) val sendURL = "$wechatWorkApiURL/cgi-bin/tencent/chat/create?access_token=$accessToken" - val requestBody = RequestBody.create(MediaType.parse("application/json"), jsonString) + val requestBody = RequestBody.create("application/json".toMediaTypeOrNull(), jsonString) val sendRequest = Request.Builder() .url(sendURL) .post(requestBody) .build() OkhttpUtils.doHttp(sendRequest).use { response -> // httpClient.newCall(sendRequest).execute().use { response -> - val responseContent = response.body()!!.string() + val responseContent = response.body!!.string() if (!response.isSuccessful) { throw RuntimeException("Fail to send msg to yqwx. $responseContent") } @@ -412,7 +412,7 @@ class WechatWorkService @Autowired constructor( .build() OkhttpUtils.doHttp(sendRequest).use { response -> // httpClient.newCall(sendRequest).execute().use { response -> - val responseContent = response.body()!!.string() + val responseContent = response.body!!.string() if (!response.isSuccessful) { throw RuntimeException("Fail to send msg to yqwx. $responseContent") } @@ -447,14 +447,14 @@ class WechatWorkService @Autowired constructor( val jsonString = if (message is String) message else objectMapper.writeValueAsString(message) logger.info("send to wework send json:$jsonString") - val requestBody = RequestBody.create(MediaType.parse("application/json"), jsonString) + val requestBody = RequestBody.create("application/json".toMediaTypeOrNull(), jsonString) val sendRequest = Request.Builder() .url(sendURL) .post(requestBody) .build() OkhttpUtils.doHttp(sendRequest).use { response -> // httpClient.newCall(sendRequest).execute().use { response -> - val responseContent = response.body()!!.string() + val responseContent = response.body!!.string() logger.info("send to wework responseContent:$responseContent") if (!response.isSuccessful) { @@ -479,7 +479,7 @@ class WechatWorkService @Autowired constructor( val accessToken = getAccessToken() val url = "$uploadMediaApiURL?access_token=$accessToken&type=$mediaType" - val fileBody = RequestBody.create(MediaType.parse("application/octet-stream"), mediaInputStream.readBytes()) + val fileBody = RequestBody.create("application/octet-stream".toMediaTypeOrNull(), mediaInputStream.readBytes()) val requestBody = MultipartBody.Builder() .setType(MultipartBody.FORM) .addFormDataPart("media", mediaName, fileBody) @@ -490,7 +490,7 @@ class WechatWorkService @Autowired constructor( .build() OkhttpUtils.doHttp(uploadRequest).use { response -> // httpClient.newCall(uploadRequest).execute().use { response -> - val responseContent = response.body()!!.string() + val responseContent = response.body!!.string() if (!response.isSuccessful) { throw RuntimeException("Fail to send media to yqwx. $responseContent") } @@ -510,14 +510,14 @@ class WechatWorkService @Autowired constructor( val jsonString = objectMapper.writeValueAsString(userIdList) val accessToken = getAccessToken() val sendURL = "$converUserIdtoUserNameApiURL?access_token=$accessToken" - val requestBody = RequestBody.create(MediaType.parse("application/json"), jsonString) + val requestBody = RequestBody.create("application/json".toMediaTypeOrNull(), jsonString) val sendRequest = Request.Builder() .url(sendURL) .post(requestBody) .build() OkhttpUtils.doHttp(sendRequest).use { response -> // httpClient.newCall(sendRequest).execute().use { response -> - val responseContent = response.body()!!.string() + val responseContent = response.body!!.string() if (!response.isSuccessful) { throw RuntimeException("Fail to send msg to yqwx. $responseContent") } diff --git a/src/backend/ci/core/dispatch-docker/biz-dispatch-docker/src/main/kotlin/com/tencent/devops/dispatch/docker/client/BuildLessClient.kt b/src/backend/ci/core/dispatch-docker/biz-dispatch-docker/src/main/kotlin/com/tencent/devops/dispatch/docker/client/BuildLessClient.kt index 8a79490d476..e1fe5534816 100644 --- a/src/backend/ci/core/dispatch-docker/biz-dispatch-docker/src/main/kotlin/com/tencent/devops/dispatch/docker/client/BuildLessClient.kt +++ b/src/backend/ci/core/dispatch-docker/biz-dispatch-docker/src/main/kotlin/com/tencent/devops/dispatch/docker/client/BuildLessClient.kt @@ -50,7 +50,7 @@ import com.tencent.devops.dispatch.docker.utils.RedisUtils import com.tencent.devops.dispatch.pojo.enums.PipelineTaskStatus import com.tencent.devops.dispatch.pojo.redis.RedisBuild import com.tencent.devops.process.pojo.mq.PipelineBuildLessStartupDispatchEvent -import okhttp3.MediaType +import okhttp3.MediaType.Companion.toMediaTypeOrNull import okhttp3.RequestBody import org.jooq.DSLContext import org.slf4j.LoggerFactory @@ -167,12 +167,12 @@ class BuildLessClient @Autowired constructor( clusterType = clusterType ).delete( RequestBody.create( - MediaType.parse("application/json; charset=utf-8"), - JsonUtil.toJson(buildLessEndInfo) - )).build() + "application/json; charset=utf-8".toMediaTypeOrNull(), + JsonUtil.toJson(buildLessEndInfo) + )).build() OkhttpUtils.doHttp(request).use { resp -> - val responseBody = resp.body()!!.string() + val responseBody = resp.body!!.string() LOG.info("[$buildId|$vmSeqId|$dockerIp] End build less, response: $responseBody") val response: Map = jacksonObjectMapper().readValue(responseBody) if (response["status"] == 0) { @@ -202,17 +202,17 @@ class BuildLessClient @Autowired constructor( clusterType = DockerHostClusterType.BUILD_LESS ).post( RequestBody.create( - MediaType.parse("application/json; charset=utf-8"), + "application/json; charset=utf-8".toMediaTypeOrNull(), JsonUtil.toJson(buildLessStartInfo) ) ).build() val buildLogKey = "${buildLessStartInfo.buildId}|${buildLessStartInfo.vmSeqId}|$retryTime" - LOG.info("Start buildLess|$buildLogKey|$dockerIp|${request.url()}") + LOG.info("Start buildLess|$buildLogKey|$dockerIp|${request.url}") try { OkhttpUtils.doHttp(request).use { resp -> if (resp.isSuccessful) { - val responseBody = resp.body()!!.string() + val responseBody = resp.body!!.string() val response: Map = jacksonObjectMapper().readValue(responseBody) LOG.info("Response buildLess $buildLogKey status: ${response["status"]}") dealWithResponse( @@ -230,7 +230,7 @@ class BuildLessClient @Autowired constructor( retryMax = retryMax, dockerIp = dockerIp, buildLessStartInfo = buildLessStartInfo, - errorMessage = resp.message(), + errorMessage = resp.message, unAvailableIpList = unAvailableIpList ) } diff --git a/src/backend/ci/core/dispatch-docker/biz-dispatch-docker/src/main/kotlin/com/tencent/devops/dispatch/docker/client/DockerHostClient.kt b/src/backend/ci/core/dispatch-docker/biz-dispatch-docker/src/main/kotlin/com/tencent/devops/dispatch/docker/client/DockerHostClient.kt index 29b345dad9d..b3f467d5d41 100644 --- a/src/backend/ci/core/dispatch-docker/biz-dispatch-docker/src/main/kotlin/com/tencent/devops/dispatch/docker/client/DockerHostClient.kt +++ b/src/backend/ci/core/dispatch-docker/biz-dispatch-docker/src/main/kotlin/com/tencent/devops/dispatch/docker/client/DockerHostClient.kt @@ -62,7 +62,7 @@ import com.tencent.devops.dispatch.pojo.redis.RedisBuild import com.tencent.devops.process.engine.common.VMUtils import com.tencent.devops.process.pojo.mq.PipelineBuildLessStartupDispatchEvent import com.tencent.devops.store.pojo.image.enums.ImageRDTypeEnum -import okhttp3.MediaType +import okhttp3.MediaType.Companion.toMediaTypeOrNull import okhttp3.RequestBody import org.jooq.DSLContext import org.slf4j.LoggerFactory @@ -272,12 +272,12 @@ class DockerHostClient @Autowired constructor( clusterType = clusterType ).delete( RequestBody.create( - MediaType.parse("application/json; charset=utf-8"), - JsonUtil.toJson(requestBody) - )).build() + "application/json; charset=utf-8".toMediaTypeOrNull(), + JsonUtil.toJson(requestBody) + )).build() OkhttpUtils.doHttp(request).use { resp -> - val responseBody = resp.body()!!.string() + val responseBody = resp.body!!.string() LOG.info("[$projectId|$pipelineId|$buildId] End build Docker VM $dockerIp responseBody: $responseBody") val response: Map = jacksonObjectMapper().readValue(responseBody) if (response["status"] == 0) { @@ -312,14 +312,17 @@ class DockerHostClient @Autowired constructor( dockerHostIp = dockerIp, dockerHostPort = dockerHostPort, clusterType = clusterType - ).post(RequestBody.create(MediaType.parse("application/json; charset=utf-8"), JsonUtil.toJson(dockerHostBuildInfo))) + ).post(RequestBody.create( + "application/json; charset=utf-8".toMediaTypeOrNull(), + JsonUtil.toJson(dockerHostBuildInfo) + )) .build() - LOG.info("dockerStart|${dockerHostBuildInfo.buildId}|$retryTime|$dockerIp|${request.url()}") + LOG.info("dockerStart|${dockerHostBuildInfo.buildId}|$retryTime|$dockerIp|${request.url}") try { OkhttpUtils.doLongHttp(request).use { resp -> if (resp.isSuccessful) { - val responseBody = resp.body()!!.string() + val responseBody = resp.body!!.string() val response: Map = jacksonObjectMapper().readValue(responseBody) when { response["status"] == 0 -> { @@ -363,7 +366,7 @@ class DockerHostClient @Autowired constructor( dockerIp = dockerIp, dockerHostBuildInfo = dockerHostBuildInfo, driftIpInfo = driftIpInfo, - errorMessage = resp.message(), + errorMessage = resp.message, unAvailableIpList = unAvailableIpList, clusterType = clusterType ) diff --git a/src/backend/ci/core/dispatch-docker/biz-dispatch-docker/src/main/kotlin/com/tencent/devops/dispatch/docker/service/debug/impl/DockerHostDebugServiceImpl.kt b/src/backend/ci/core/dispatch-docker/biz-dispatch-docker/src/main/kotlin/com/tencent/devops/dispatch/docker/service/debug/impl/DockerHostDebugServiceImpl.kt index 426b0d9b51b..8adfe98f10e 100644 --- a/src/backend/ci/core/dispatch-docker/biz-dispatch-docker/src/main/kotlin/com/tencent/devops/dispatch/docker/service/debug/impl/DockerHostDebugServiceImpl.kt +++ b/src/backend/ci/core/dispatch-docker/biz-dispatch-docker/src/main/kotlin/com/tencent/devops/dispatch/docker/service/debug/impl/DockerHostDebugServiceImpl.kt @@ -53,7 +53,7 @@ import com.tencent.devops.dispatch.pojo.enums.PipelineTaskStatus import com.tencent.devops.model.dispatch.tables.records.TDispatchPipelineDockerBuildRecord import com.tencent.devops.store.api.container.ServiceContainerAppResource import com.tencent.devops.store.pojo.app.BuildEnv -import okhttp3.MediaType +import okhttp3.MediaType.Companion.toMediaTypeOrNull import okhttp3.RequestBody import org.jooq.DSLContext import org.slf4j.LoggerFactory @@ -165,12 +165,15 @@ class DockerHostDebugServiceImpl @Autowired constructor( val request = dockerHostProxyService.getDockerHostProxyRequest( dockerHostUri = "/api/docker/debug/end", dockerHostIp = dockerIp - ).post(RequestBody.create(MediaType.parse("application/json; charset=utf-8"), JsonUtil.toJson(requestBody))) + ).post(RequestBody.create( + "application/json; charset=utf-8".toMediaTypeOrNull(), + JsonUtil.toJson(requestBody) + )) .build() - LOG.info("[$projectId|$pipelineId] Stop debug Docker VM $dockerIp url: ${request.url()}") + LOG.info("[$projectId|$pipelineId] Stop debug Docker VM $dockerIp url: ${request.url}") OkhttpUtils.doLongHttp(request).use { resp -> - val responseBody = resp.body()!!.string() + val responseBody = resp.body!!.string() LOG.info("[$projectId|$pipelineId] Stop debug Docker VM $dockerIp responseBody: $responseBody") val response: Map = jacksonObjectMapper().readValue(responseBody) when { @@ -203,7 +206,7 @@ class DockerHostDebugServiceImpl @Autowired constructor( ).get().build() OkhttpUtils.doHttp(request).use { resp -> - val responseBody = resp.body()!!.string() + val responseBody = resp.body!!.string() val response: Map = jacksonObjectMapper().readValue(responseBody) if (response["status"] == 0) { return response["data"] as Boolean @@ -230,7 +233,7 @@ class DockerHostDebugServiceImpl @Autowired constructor( ).get().build() OkhttpUtils.doHttp(request).use { resp -> - val responseBody = resp.body()!!.string() + val responseBody = resp.body!!.string() val response: Map = jacksonObjectMapper().readValue(responseBody) if (response["status"] == 0) { return response["data"] as String @@ -437,12 +440,12 @@ class DockerHostDebugServiceImpl @Autowired constructor( val request = dockerHostProxyService.getDockerHostProxyRequest( dockerHostUri = "/api/docker/debug/start", dockerHostIp = dockerIp - ).post(RequestBody.create(MediaType.parse("application/json; charset=utf-8"), JsonUtil.toJson(requestBody))) + ).post(RequestBody.create("application/json; charset=utf-8".toMediaTypeOrNull(), JsonUtil.toJson(requestBody))) .build() - LOG.info("[$projectId|$pipelineId] Start debug Docker VM $dockerIp url: ${request.url()}") + LOG.info("[$projectId|$pipelineId] Start debug Docker VM $dockerIp url: ${request.url}") OkhttpUtils.doLongHttp(request).use { resp -> - val responseBody = resp.body()!!.string() + val responseBody = resp.body!!.string() LOG.info("[$projectId|$pipelineId] Start debug Docker VM $dockerIp responseBody: $responseBody") val response: Map = jacksonObjectMapper().readValue(responseBody) when { diff --git a/src/backend/ci/core/dispatch-kubernetes/biz-dispatch-kubernetes-bcs/src/main/kotlin/com/tencent/devops/dispatch/bcs/client/BcsBuilderClient.kt b/src/backend/ci/core/dispatch-kubernetes/biz-dispatch-kubernetes-bcs/src/main/kotlin/com/tencent/devops/dispatch/bcs/client/BcsBuilderClient.kt index 754e4181b1c..a92088b9884 100644 --- a/src/backend/ci/core/dispatch-kubernetes/biz-dispatch-kubernetes-bcs/src/main/kotlin/com/tencent/devops/dispatch/bcs/client/BcsBuilderClient.kt +++ b/src/backend/ci/core/dispatch-kubernetes/biz-dispatch-kubernetes-bcs/src/main/kotlin/com/tencent/devops/dispatch/bcs/client/BcsBuilderClient.kt @@ -47,7 +47,7 @@ import com.tencent.devops.dispatch.bcs.pojo.getCodeMessage import com.tencent.devops.dispatch.bcs.pojo.isRunning import com.tencent.devops.dispatch.bcs.pojo.resp.BcsTaskResp import com.tencent.devops.dispatch.kubernetes.pojo.base.DispatchBuildImageReq -import okhttp3.MediaType +import okhttp3.MediaType.Companion.toMediaTypeOrNull import okhttp3.RequestBody import org.slf4j.LoggerFactory import org.springframework.beans.factory.annotation.Autowired @@ -76,7 +76,7 @@ class BcsBuilderClient @Autowired constructor( val request = clientCommon.baseRequest(userId, url).get().build() try { OkhttpUtils.doHttp(request).use { response -> - val responseContent = response.body()!!.string() + val responseContent = response.body!!.string() logger.info("[$buildId]|[$vmSeqId] builderName: $name response: $responseContent") if (response.isSuccessful) { return objectMapper.readValue(responseContent) @@ -92,7 +92,7 @@ class BcsBuilderClient @Autowired constructor( ErrorCodeEnum.VM_STATUS_INTERFACE_ERROR.errorCode, ErrorCodeEnum.VM_STATUS_INTERFACE_ERROR.formatErrorMessage, "${ConstantsMessage.TROUBLE_SHOOTING}获取构建机详情接口异常" + - "(Fail to get builder detail, http response code: ${response.code()}" + "(Fail to get builder detail, http response code: ${response.code}" ) } } catch (e: SocketTimeoutException) { @@ -127,7 +127,7 @@ class BcsBuilderClient @Autowired constructor( val (request, action) = when (param) { is BcsDeleteBuilderParams -> Pair( clientCommon.baseRequest(userId, url) - .delete(RequestBody.create(MediaType.parse("application/json; charset=utf-8"), body)) + .delete(RequestBody.create("application/json; charset=utf-8".toMediaTypeOrNull(), body)) .build(), "delete" ) @@ -139,7 +139,7 @@ class BcsBuilderClient @Autowired constructor( ) is BcsStartBuilderParams -> Pair( clientCommon.baseRequest(userId, "$url/start") - .post(RequestBody.create(MediaType.parse("application/json; charset=utf-8"), body)) + .post(RequestBody.create("application/json; charset=utf-8".toMediaTypeOrNull(), body)) .build(), "start" ) @@ -149,14 +149,14 @@ class BcsBuilderClient @Autowired constructor( logger.info("[$buildId]|[$vmSeqId] request body: $body") try { OkhttpUtils.doHttp(request).use { response -> - val responseContent = response.body()!!.string() + val responseContent = response.body!!.string() if (!response.isSuccessful) { throw BuildFailureException( ErrorCodeEnum.OPERATE_VM_INTERFACE_ERROR.errorType, ErrorCodeEnum.OPERATE_VM_INTERFACE_ERROR.errorCode, ErrorCodeEnum.OPERATE_VM_INTERFACE_ERROR.formatErrorMessage, "${ConstantsMessage.TROUBLE_SHOOTING}操作构建机接口异常" + - "(Fail to $action docker, http response code: ${response.code()}" + "(Fail to $action docker, http response code: ${response.code}" ) } logger.info("[$buildId]|[$vmSeqId] response: $responseContent") @@ -195,20 +195,20 @@ class BcsBuilderClient @Autowired constructor( logger.info("[$buildId]|[$vmSeqId] request url: $url") logger.info("[$buildId]|[$vmSeqId] request body: $body") val request = clientCommon.baseRequest(userId, url) - .post(RequestBody.create(MediaType.parse("application/json; charset=utf-8"), body)) + .post(RequestBody.create("application/json; charset=utf-8".toMediaTypeOrNull(), body)) .build() try { OkhttpUtils.doHttp(request).use { response -> - val responseContent = response.body()!!.string() - logger.info("[$buildId]|[$vmSeqId] http code is ${response.code()}, $responseContent") + val responseContent = response.body!!.string() + logger.info("[$buildId]|[$vmSeqId] http code is ${response.code}, $responseContent") if (!response.isSuccessful) { throw BuildFailureException( ErrorCodeEnum.CREATE_VM_INTERFACE_ERROR.errorType, ErrorCodeEnum.CREATE_VM_INTERFACE_ERROR.errorCode, ErrorCodeEnum.CREATE_VM_INTERFACE_ERROR.formatErrorMessage, "${ConstantsMessage.TROUBLE_SHOOTING}创建构建机接口异常: Fail to createBuilder, http response code: " + - "${response.code()}" + "${response.code}" ) } @@ -294,7 +294,7 @@ class BcsBuilderClient @Autowired constructor( try { OkhttpUtils.doHttp(request).use { response -> - val responseContent = response.body()!!.string() + val responseContent = response.body!!.string() logger.info("response: $responseContent") if (!response.isSuccessful) { // throw OperationException("Fail to get container websocket") @@ -302,7 +302,7 @@ class BcsBuilderClient @Autowired constructor( ErrorCodeEnum.WEBSOCKET_URL_INTERFACE_ERROR.errorType, ErrorCodeEnum.WEBSOCKET_URL_INTERFACE_ERROR.errorCode, ErrorCodeEnum.WEBSOCKET_URL_INTERFACE_ERROR.formatErrorMessage, - "获取websocket接口异常(Fail to getWebsocket, http response code: ${response.code()}" + "获取websocket接口异常(Fail to getWebsocket, http response code: ${response.code}" ) } val bcsResult: BcsResult = objectMapper.readValue(responseContent) @@ -334,21 +334,21 @@ class BcsBuilderClient @Autowired constructor( val request = clientCommon.baseRequest(userId, url) .post( RequestBody.create( - MediaType.parse("application/json; charset=utf-8"), JsonUtil.toJson(buildImageReq) + "application/json; charset=utf-8".toMediaTypeOrNull(), JsonUtil.toJson(buildImageReq) ) ) .build() try { OkhttpUtils.doHttp(request).use { response -> - val responseContent = response.body()!!.string() + val responseContent = response.body!!.string() logger.info("$userId build and push image response: $responseContent") if (!response.isSuccessful) { throw BuildFailureException( ErrorCodeEnum.CREATE_IMAGE_INTERFACE_ERROR.errorType, ErrorCodeEnum.CREATE_IMAGE_INTERFACE_ERROR.errorCode, ErrorCodeEnum.CREATE_IMAGE_INTERFACE_ERROR.formatErrorMessage, - "构建并推送接口异常(Fail to build image, http response code: ${response.code()}" + "构建并推送接口异常(Fail to build image, http response code: ${response.code}" ) } val responseData: BcsResult = objectMapper.readValue(responseContent) diff --git a/src/backend/ci/core/dispatch-kubernetes/biz-dispatch-kubernetes-bcs/src/main/kotlin/com/tencent/devops/dispatch/bcs/client/BcsClientCommon.kt b/src/backend/ci/core/dispatch-kubernetes/biz-dispatch-kubernetes-bcs/src/main/kotlin/com/tencent/devops/dispatch/bcs/client/BcsClientCommon.kt index cea4c89347e..a5fcde0bcd7 100644 --- a/src/backend/ci/core/dispatch-kubernetes/biz-dispatch-kubernetes-bcs/src/main/kotlin/com/tencent/devops/dispatch/bcs/client/BcsClientCommon.kt +++ b/src/backend/ci/core/dispatch-kubernetes/biz-dispatch-kubernetes-bcs/src/main/kotlin/com/tencent/devops/dispatch/bcs/client/BcsClientCommon.kt @@ -29,6 +29,7 @@ package com.tencent.devops.dispatch.bcs.client import com.tencent.devops.dispatch.kubernetes.interfaces.CommonService import okhttp3.Headers +import okhttp3.Headers.Companion.toHeaders import okhttp3.Request import org.springframework.beans.factory.annotation.Autowired import org.springframework.beans.factory.annotation.Value @@ -63,6 +64,6 @@ class BcsClientCommon @Autowired constructor( result.putAll(otherHeaders) } - return Headers.of(result) + return result.toHeaders() } } diff --git a/src/backend/ci/core/dispatch-kubernetes/biz-dispatch-kubernetes-bcs/src/main/kotlin/com/tencent/devops/dispatch/bcs/client/BcsJobClient.kt b/src/backend/ci/core/dispatch-kubernetes/biz-dispatch-kubernetes-bcs/src/main/kotlin/com/tencent/devops/dispatch/bcs/client/BcsJobClient.kt index 2fa9858ba46..a35fa74f9ca 100644 --- a/src/backend/ci/core/dispatch-kubernetes/biz-dispatch-kubernetes-bcs/src/main/kotlin/com/tencent/devops/dispatch/bcs/client/BcsJobClient.kt +++ b/src/backend/ci/core/dispatch-kubernetes/biz-dispatch-kubernetes-bcs/src/main/kotlin/com/tencent/devops/dispatch/bcs/client/BcsJobClient.kt @@ -38,7 +38,7 @@ import com.tencent.devops.dispatch.bcs.pojo.BcsJob import com.tencent.devops.dispatch.bcs.pojo.BcsJobStatus import com.tencent.devops.dispatch.bcs.pojo.BcsResult import com.tencent.devops.dispatch.bcs.pojo.resp.BcsTaskResp -import okhttp3.MediaType +import okhttp3.MediaType.Companion.toMediaTypeOrNull import okhttp3.RequestBody import org.slf4j.LoggerFactory import org.springframework.beans.factory.annotation.Autowired @@ -63,11 +63,11 @@ class BcsJobClient @Autowired constructor( logger.info("createJob request url: $url, body: $body") val request = clientCommon.baseRequest(userId, url).post( RequestBody.create( - MediaType.parse("application/json; charset=utf-8"), + "application/json; charset=utf-8".toMediaTypeOrNull(), body ) ).build() - val responseBody = OkhttpUtils.doHttp(request).body()!!.string() + val responseBody = OkhttpUtils.doHttp(request).body!!.string() logger.info("createJob response: ${JsonUtil.toJson(responseBody)}") return JsonUtil.getObjectMapper().readValue(responseBody) } @@ -77,7 +77,7 @@ class BcsJobClient @Autowired constructor( val request = clientCommon.baseRequest(userId, url).get().build() logger.info("getJobStatus request url: $url, staffName: $userId") OkhttpUtils.doHttp(request).use { response -> - val responseContent = response.body()!!.string() + val responseContent = response.body!!.string() logger.info("response: $responseContent") if (!response.isSuccessful) { throw BuildFailureException( @@ -85,7 +85,7 @@ class BcsJobClient @Autowired constructor( ErrorCodeEnum.SYSTEM_ERROR.errorCode, ErrorCodeEnum.SYSTEM_ERROR.formatErrorMessage, "${ConstantsMessage.TROUBLE_SHOOTING}查询Job status接口异常(Fail to getJobStatus, " + - "http response code: ${response.code()}" + "http response code: ${response.code}" ) } return objectMapper.readValue(responseContent) @@ -101,7 +101,7 @@ class BcsJobClient @Autowired constructor( val request = clientCommon.baseRequest(userId, url).get().build() logger.info("getJobLogs request url: $url, jobName: $jobName, sinceTime: $sinceTime, staffName: $userId") OkhttpUtils.doHttp(request).use { response -> - val responseContent = response.body()!!.string() + val responseContent = response.body!!.string() logger.info("response: $responseContent") if (!response.isSuccessful) { throw BuildFailureException( @@ -109,7 +109,7 @@ class BcsJobClient @Autowired constructor( ErrorCodeEnum.SYSTEM_ERROR.errorCode, ErrorCodeEnum.SYSTEM_ERROR.formatErrorMessage, "${ConstantsMessage.TROUBLE_SHOOTING}获取Job logs接口异常" + - "(Fail to getJobLogs, http response code: ${response.code()}" + "(Fail to getJobLogs, http response code: ${response.code}" ) } return objectMapper.readValue(responseContent) diff --git a/src/backend/ci/core/dispatch-kubernetes/biz-dispatch-kubernetes-bcs/src/main/kotlin/com/tencent/devops/dispatch/bcs/client/BcsTaskClient.kt b/src/backend/ci/core/dispatch-kubernetes/biz-dispatch-kubernetes-bcs/src/main/kotlin/com/tencent/devops/dispatch/bcs/client/BcsTaskClient.kt index 756e1ccf1f1..12baac12250 100644 --- a/src/backend/ci/core/dispatch-kubernetes/biz-dispatch-kubernetes-bcs/src/main/kotlin/com/tencent/devops/dispatch/bcs/client/BcsTaskClient.kt +++ b/src/backend/ci/core/dispatch-kubernetes/biz-dispatch-kubernetes-bcs/src/main/kotlin/com/tencent/devops/dispatch/bcs/client/BcsTaskClient.kt @@ -63,17 +63,17 @@ class BcsTaskClient @Autowired constructor( val request = clientCommon.baseRequest(userId, url).get().build() try { OkhttpUtils.doHttp(request).use { response -> - val responseContent = response.body()!!.string() + val responseContent = response.body!!.string() if (response.isSuccessful) { return objectMapper.readValue(responseContent) } - logger.error("Get task status failed, responseCode: ${response.code()}") + logger.error("Get task status failed, responseCode: ${response.code}") throw BuildFailureException( ErrorCodeEnum.TASK_STATUS_INTERFACE_ERROR.errorType, ErrorCodeEnum.TASK_STATUS_INTERFACE_ERROR.errorCode, ErrorCodeEnum.TASK_STATUS_INTERFACE_ERROR.formatErrorMessage, - "获取BCS TASK状态接口异常:http response code: ${response.code()}" + "获取BCS TASK状态接口异常:http response code: ${response.code}" ) } } catch (e: SocketTimeoutException) { diff --git a/src/backend/ci/core/dispatch-kubernetes/biz-dispatch-kubernetes/src/main/kotlin/com/tencent/devops/dispatch/kubernetes/client/KubernetesBuilderClient.kt b/src/backend/ci/core/dispatch-kubernetes/biz-dispatch-kubernetes/src/main/kotlin/com/tencent/devops/dispatch/kubernetes/client/KubernetesBuilderClient.kt index c37cdd9168b..f391db053c9 100644 --- a/src/backend/ci/core/dispatch-kubernetes/biz-dispatch-kubernetes/src/main/kotlin/com/tencent/devops/dispatch/kubernetes/client/KubernetesBuilderClient.kt +++ b/src/backend/ci/core/dispatch-kubernetes/biz-dispatch-kubernetes/src/main/kotlin/com/tencent/devops/dispatch/kubernetes/client/KubernetesBuilderClient.kt @@ -45,7 +45,7 @@ import com.tencent.devops.dispatch.kubernetes.pojo.StopBuilderParams import com.tencent.devops.dispatch.kubernetes.pojo.TaskResp import com.tencent.devops.dispatch.kubernetes.pojo.getCodeMessage import com.tencent.devops.dispatch.kubernetes.pojo.isRunning -import okhttp3.MediaType +import okhttp3.MediaType.Companion.toMediaTypeOrNull import okhttp3.RequestBody import org.slf4j.LoggerFactory import org.springframework.beans.factory.annotation.Autowired @@ -74,7 +74,7 @@ class KubernetesBuilderClient @Autowired constructor( val request = clientCommon.baseRequest(userId, url).get().build() try { OkhttpUtils.doHttp(request).use { response -> - val responseContent = response.body()!!.string() + val responseContent = response.body!!.string() logger.info("[$buildId]|[$vmSeqId] Get detail builderName: $name response: $responseContent") if (response.isSuccessful) { return objectMapper.readValue(responseContent) @@ -90,7 +90,7 @@ class KubernetesBuilderClient @Autowired constructor( ErrorCodeEnum.VM_STATUS_INTERFACE_ERROR.errorCode, ErrorCodeEnum.VM_STATUS_INTERFACE_ERROR.formatErrorMessage, "${ConstantsMessage.TROUBLE_SHOOTING}获取构建机详情接口异常" + - "(Fail to get builder detail, http response code: ${response.code()}" + "(Fail to get builder detail, http response code: ${response.code}" ) } } catch (e: SocketTimeoutException) { @@ -139,7 +139,7 @@ class KubernetesBuilderClient @Autowired constructor( is StartBuilderParams -> Pair( clientCommon.baseRequest(userId, "$url/start") - .put(RequestBody.create(MediaType.parse("application/json; charset=utf-8"), body)) + .put(RequestBody.create("application/json; charset=utf-8".toMediaTypeOrNull(), body)) .build(), "start" ) @@ -150,14 +150,14 @@ class KubernetesBuilderClient @Autowired constructor( logger.info("[$buildId]|[$vmSeqId] operator builder: $name request body: $body") try { OkhttpUtils.doHttp(request).use { response -> - val responseContent = response.body()!!.string() + val responseContent = response.body!!.string() if (!response.isSuccessful) { throw BuildFailureException( ErrorCodeEnum.OPERATE_VM_INTERFACE_ERROR.errorType, ErrorCodeEnum.OPERATE_VM_INTERFACE_ERROR.errorCode, ErrorCodeEnum.OPERATE_VM_INTERFACE_ERROR.formatErrorMessage, "${ConstantsMessage.TROUBLE_SHOOTING}操作构建机接口异常" + - "(Fail to $action docker, http response code: ${response.code()}" + "(Fail to $action docker, http response code: ${response.code}" ) } logger.info("[$buildId]|[$vmSeqId] operator builder: $name response: $responseContent") @@ -196,20 +196,20 @@ class KubernetesBuilderClient @Autowired constructor( logger.info("[$buildId]|[$vmSeqId] create builder request url: $url") logger.info("[$buildId]|[$vmSeqId] create builder request body: $body") val request = clientCommon.baseRequest(userId, url) - .post(RequestBody.create(MediaType.parse("application/json; charset=utf-8"), body)) + .post(RequestBody.create("application/json; charset=utf-8".toMediaTypeOrNull(), body)) .build() try { OkhttpUtils.doHttp(request).use { response -> - val responseContent = response.body()!!.string() - logger.info("[$buildId]|[$vmSeqId] create builder response: ${response.code()}, $responseContent") + val responseContent = response.body!!.string() + logger.info("[$buildId]|[$vmSeqId] create builder response: ${response.code}, $responseContent") if (!response.isSuccessful) { throw BuildFailureException( ErrorCodeEnum.CREATE_VM_INTERFACE_ERROR.errorType, ErrorCodeEnum.CREATE_VM_INTERFACE_ERROR.errorCode, ErrorCodeEnum.CREATE_VM_INTERFACE_ERROR.formatErrorMessage, "${ConstantsMessage.TROUBLE_SHOOTING}创建构建机接口异常: Fail to createBuilder, http response code: " + - "${response.code()}" + "${response.code}" ) } @@ -296,7 +296,7 @@ class KubernetesBuilderClient @Autowired constructor( try { OkhttpUtils.doHttp(request).use { response -> - val responseContent = response.body()!!.string() + val responseContent = response.body!!.string() logger.info("$projectId|$staffName|$builderName Get websocketUrl response: $responseContent") if (!response.isSuccessful) { // throw OperationException("Fail to get container websocket") @@ -304,7 +304,7 @@ class KubernetesBuilderClient @Autowired constructor( ErrorCodeEnum.WEBSOCKET_URL_INTERFACE_ERROR.errorType, ErrorCodeEnum.WEBSOCKET_URL_INTERFACE_ERROR.errorCode, ErrorCodeEnum.WEBSOCKET_URL_INTERFACE_ERROR.formatErrorMessage, - "获取websocket接口异常(Fail to getWebsocket, http response code: ${response.code()}" + "获取websocket接口异常(Fail to getWebsocket, http response code: ${response.code}" ) } val result: KubernetesResult = objectMapper.readValue(responseContent) diff --git a/src/backend/ci/core/dispatch-kubernetes/biz-dispatch-kubernetes/src/main/kotlin/com/tencent/devops/dispatch/kubernetes/client/KubernetesClientCommon.kt b/src/backend/ci/core/dispatch-kubernetes/biz-dispatch-kubernetes/src/main/kotlin/com/tencent/devops/dispatch/kubernetes/client/KubernetesClientCommon.kt index f1610285753..da04bd4f3c8 100644 --- a/src/backend/ci/core/dispatch-kubernetes/biz-dispatch-kubernetes/src/main/kotlin/com/tencent/devops/dispatch/kubernetes/client/KubernetesClientCommon.kt +++ b/src/backend/ci/core/dispatch-kubernetes/biz-dispatch-kubernetes/src/main/kotlin/com/tencent/devops/dispatch/kubernetes/client/KubernetesClientCommon.kt @@ -29,6 +29,7 @@ package com.tencent.devops.dispatch.kubernetes.client import com.tencent.devops.dispatch.kubernetes.interfaces.CommonService import okhttp3.Headers +import okhttp3.Headers.Companion.toHeaders import okhttp3.Request import org.springframework.beans.factory.annotation.Autowired import org.springframework.beans.factory.annotation.Value @@ -63,6 +64,6 @@ class KubernetesClientCommon @Autowired constructor( result.putAll(otherHeaders) } - return Headers.of(result) + return result.toHeaders() } } diff --git a/src/backend/ci/core/dispatch-kubernetes/biz-dispatch-kubernetes/src/main/kotlin/com/tencent/devops/dispatch/kubernetes/client/KubernetesJobClient.kt b/src/backend/ci/core/dispatch-kubernetes/biz-dispatch-kubernetes/src/main/kotlin/com/tencent/devops/dispatch/kubernetes/client/KubernetesJobClient.kt index 4106baf99cb..7968a2a8329 100644 --- a/src/backend/ci/core/dispatch-kubernetes/biz-dispatch-kubernetes/src/main/kotlin/com/tencent/devops/dispatch/kubernetes/client/KubernetesJobClient.kt +++ b/src/backend/ci/core/dispatch-kubernetes/biz-dispatch-kubernetes/src/main/kotlin/com/tencent/devops/dispatch/kubernetes/client/KubernetesJobClient.kt @@ -39,7 +39,7 @@ import com.tencent.devops.dispatch.kubernetes.pojo.Job import com.tencent.devops.dispatch.kubernetes.pojo.JobStatus import com.tencent.devops.dispatch.kubernetes.pojo.KubernetesResult import com.tencent.devops.dispatch.kubernetes.pojo.TaskResp -import okhttp3.MediaType +import okhttp3.MediaType.Companion.toMediaTypeOrNull import okhttp3.RequestBody import org.slf4j.LoggerFactory import org.springframework.beans.factory.annotation.Autowired @@ -64,11 +64,11 @@ class KubernetesJobClient @Autowired constructor( logger.info("Create job request url: $url, body: $body") val request = clientCommon.baseRequest(userId, url).post( RequestBody.create( - MediaType.parse("application/json; charset=utf-8"), + "application/json; charset=utf-8".toMediaTypeOrNull(), body ) ).build() - val responseBody = OkhttpUtils.doHttp(request).body()!!.string() + val responseBody = OkhttpUtils.doHttp(request).body!!.string() logger.info("Create job response: ${JsonUtil.toJson(responseBody)}") return JsonUtil.getObjectMapper().readValue(responseBody) } @@ -78,7 +78,7 @@ class KubernetesJobClient @Autowired constructor( val request = clientCommon.baseRequest(userId, url).get().build() logger.info("Get job: $jobName status request url: $url, staffName: $userId") OkhttpUtils.doHttp(request).use { response -> - val responseContent = response.body()!!.string() + val responseContent = response.body!!.string() logger.info("Get job: $jobName status response: $responseContent") if (!response.isSuccessful) { throw BuildFailureException( @@ -86,7 +86,7 @@ class KubernetesJobClient @Autowired constructor( ErrorCodeEnum.SYSTEM_ERROR.errorCode, ErrorCodeEnum.SYSTEM_ERROR.formatErrorMessage, "${ConstantsMessage.TROUBLE_SHOOTING}查询Job status接口异常(Fail to getJobStatus, " + - "http response code: ${response.code()}" + "http response code: ${response.code}" ) } return objectMapper.readValue(responseContent) @@ -103,7 +103,7 @@ class KubernetesJobClient @Autowired constructor( logger.info("Get job: $jobName logs request url: $url, jobName: $jobName, " + "sinceTime: $sinceTime, staffName: $userId") OkhttpUtils.doHttp(request).use { response -> - val responseContent = response.body()!!.string() + val responseContent = response.body!!.string() logger.info("Get job: $jobName logs response: $responseContent") if (!response.isSuccessful) { throw BuildFailureException( @@ -111,7 +111,7 @@ class KubernetesJobClient @Autowired constructor( ErrorCodeEnum.SYSTEM_ERROR.errorCode, ErrorCodeEnum.SYSTEM_ERROR.formatErrorMessage, "${ConstantsMessage.TROUBLE_SHOOTING}获取Job logs接口异常" + - "(Fail to getJobLogs, http response code: ${response.code()}" + "(Fail to getJobLogs, http response code: ${response.code}" ) } return objectMapper.readValue(responseContent) @@ -128,21 +128,21 @@ class KubernetesJobClient @Autowired constructor( val request = clientCommon.baseRequest(userId, url) .post( RequestBody.create( - MediaType.parse("application/json; charset=utf-8"), JsonUtil.toJson(buildImageInfo) + "application/json; charset=utf-8".toMediaTypeOrNull(), JsonUtil.toJson(buildImageInfo) ) ) .build() try { OkhttpUtils.doHttp(request).use { response -> - val responseContent = response.body()!!.string() + val responseContent = response.body!!.string() logger.info("$userId build and push image response: $responseContent") if (!response.isSuccessful) { throw BuildFailureException( ErrorCodeEnum.CREATE_IMAGE_INTERFACE_ERROR.errorType, ErrorCodeEnum.CREATE_IMAGE_INTERFACE_ERROR.errorCode, ErrorCodeEnum.CREATE_IMAGE_INTERFACE_ERROR.formatErrorMessage, - "构建并推送接口异常(Fail to build image, http response code: ${response.code()}" + "构建并推送接口异常(Fail to build image, http response code: ${response.code}" ) } val responseData: KubernetesResult = objectMapper.readValue(responseContent) diff --git a/src/backend/ci/core/dispatch-kubernetes/biz-dispatch-kubernetes/src/main/kotlin/com/tencent/devops/dispatch/kubernetes/client/KubernetesTaskClient.kt b/src/backend/ci/core/dispatch-kubernetes/biz-dispatch-kubernetes/src/main/kotlin/com/tencent/devops/dispatch/kubernetes/client/KubernetesTaskClient.kt index 21480bd4585..8eaa4ff6f07 100644 --- a/src/backend/ci/core/dispatch-kubernetes/biz-dispatch-kubernetes/src/main/kotlin/com/tencent/devops/dispatch/kubernetes/client/KubernetesTaskClient.kt +++ b/src/backend/ci/core/dispatch-kubernetes/biz-dispatch-kubernetes/src/main/kotlin/com/tencent/devops/dispatch/kubernetes/client/KubernetesTaskClient.kt @@ -64,18 +64,18 @@ class KubernetesTaskClient @Autowired constructor( val request = clientCommon.baseRequest(userId, url).get().build() try { OkhttpUtils.doHttp(request).use { response -> - val responseContent = response.body()!!.string() + val responseContent = response.body!!.string() if (response.isSuccessful) { logger.info("Get task: $taskId status response: ${JsonUtil.toJson(responseContent)}") return objectMapper.readValue(responseContent) } - logger.error("Get task: $taskId status failed, responseCode: ${response.code()}") + logger.error("Get task: $taskId status failed, responseCode: ${response.code}") throw BuildFailureException( ErrorCodeEnum.TASK_STATUS_INTERFACE_ERROR.errorType, ErrorCodeEnum.TASK_STATUS_INTERFACE_ERROR.errorCode, ErrorCodeEnum.TASK_STATUS_INTERFACE_ERROR.formatErrorMessage, - "获取kubernetes task($taskId)状态接口异常:http response code: ${response.code()}" + "获取kubernetes task($taskId)状态接口异常:http response code: ${response.code}" ) } } catch (e: SocketTimeoutException) { diff --git a/src/backend/ci/core/dockerhost/biz-dockerhost/src/main/kotlin/com/tencent/devops/dockerhost/dispatch/AbstractBuildResourceApi.kt b/src/backend/ci/core/dockerhost/biz-dockerhost/src/main/kotlin/com/tencent/devops/dockerhost/dispatch/AbstractBuildResourceApi.kt index 7e8cf416866..69edf781439 100644 --- a/src/backend/ci/core/dockerhost/biz-dockerhost/src/main/kotlin/com/tencent/devops/dockerhost/dispatch/AbstractBuildResourceApi.kt +++ b/src/backend/ci/core/dockerhost/biz-dockerhost/src/main/kotlin/com/tencent/devops/dockerhost/dispatch/AbstractBuildResourceApi.kt @@ -35,8 +35,8 @@ import com.tencent.devops.common.api.auth.AUTH_HEADER_GATEWAY_TAG import com.tencent.devops.common.api.util.JsonUtil import com.tencent.devops.dockerhost.common.Constants import com.tencent.devops.dockerhost.config.DockerHostConfig -import okhttp3.Headers -import okhttp3.MediaType +import okhttp3.Headers.Companion.toHeaders +import okhttp3.MediaType.Companion.toMediaTypeOrNull import okhttp3.Request import okhttp3.RequestBody import org.slf4j.LoggerFactory @@ -81,44 +81,44 @@ abstract class AbstractBuildResourceApi constructor( fun buildGet(path: String, headers: Map = emptyMap()): Request { val url = buildUrl(path) - return Request.Builder().url(url).headers(Headers.of(getAllHeaders(headers))).get().build() + return Request.Builder().url(url).headers(getAllHeaders(headers).toHeaders()).get().build() } fun buildHeader(path: String, headers: Map = emptyMap()): Request { val url = buildUrl(path) - return Request.Builder().url(url).headers(Headers.of(getAllHeaders(headers))).head().build() + return Request.Builder().url(url).headers(getAllHeaders(headers).toHeaders()).head().build() } fun buildPost(path: String, headers: Map = emptyMap()): Request { - val requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), "") + val requestBody = RequestBody.create("application/json; charset=utf-8".toMediaTypeOrNull(), "") return buildPost(path, requestBody, headers) } fun buildPost(path: String, requestBody: RequestBody, headers: Map = emptyMap()): Request { val url = buildUrl(path) - return Request.Builder().url(url).headers(Headers.of(getAllHeaders(headers))).post(requestBody).build() + return Request.Builder().url(url).headers(getAllHeaders(headers).toHeaders()).post(requestBody).build() } fun buildPut(path: String, headers: Map = emptyMap()): Request { - val requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), "") + val requestBody = RequestBody.create("application/json; charset=utf-8".toMediaTypeOrNull(), "") return buildPut(path, requestBody, headers) } fun buildPut(path: String, requestBody: RequestBody, headers: Map = emptyMap()): Request { val url = buildUrl(path) - return Request.Builder().url(url).headers(Headers.of(getAllHeaders(headers))).put(requestBody).build() + return Request.Builder().url(url).headers(getAllHeaders(headers).toHeaders()).put(requestBody).build() } @Suppress("UNUSED") fun buildDelete(path: String, headers: Map = emptyMap()): Request { val url = buildUrl(path) - return Request.Builder().url(url).headers(Headers.of(getAllHeaders(headers))).delete().build() + return Request.Builder().url(url).headers(getAllHeaders(headers).toHeaders()).delete().build() } @Suppress("UNUSED") fun getJsonRequest(data: Any): RequestBody { return RequestBody.create( - MediaType.parse("application/json; charset=utf-8"), + "application/json; charset=utf-8".toMediaTypeOrNull(), objectMapper.writeValueAsString(data) ) } diff --git a/src/backend/ci/core/dockerhost/biz-dockerhost/src/main/kotlin/com/tencent/devops/dockerhost/dispatch/AlertApi.kt b/src/backend/ci/core/dockerhost/biz-dockerhost/src/main/kotlin/com/tencent/devops/dockerhost/dispatch/AlertApi.kt index 83ee094490a..2efd3e5e609 100644 --- a/src/backend/ci/core/dockerhost/biz-dockerhost/src/main/kotlin/com/tencent/devops/dockerhost/dispatch/AlertApi.kt +++ b/src/backend/ci/core/dockerhost/biz-dockerhost/src/main/kotlin/com/tencent/devops/dockerhost/dispatch/AlertApi.kt @@ -43,7 +43,7 @@ class AlertApi constructor( val path = "/${getUrlPrefix()}/api/dockerhost/alert?level=$level&title=$title&message=$message" val request = buildPost(path) OkhttpUtils.doHttp(request).use { response -> - val responseContent = response.body()!!.string() + val responseContent = response.body!!.string() if (!response.isSuccessful) { logger.warn("BuildDockerResourceApi $path fail. $responseContent") } diff --git a/src/backend/ci/core/dockerhost/biz-dockerhost/src/main/kotlin/com/tencent/devops/dockerhost/dispatch/DockerHostBuildLogResourceApi.kt b/src/backend/ci/core/dockerhost/biz-dockerhost/src/main/kotlin/com/tencent/devops/dockerhost/dispatch/DockerHostBuildLogResourceApi.kt index 47848909a81..34fb256ae22 100644 --- a/src/backend/ci/core/dockerhost/biz-dockerhost/src/main/kotlin/com/tencent/devops/dockerhost/dispatch/DockerHostBuildLogResourceApi.kt +++ b/src/backend/ci/core/dockerhost/biz-dockerhost/src/main/kotlin/com/tencent/devops/dockerhost/dispatch/DockerHostBuildLogResourceApi.kt @@ -32,7 +32,7 @@ import com.tencent.devops.common.api.util.OkhttpUtils import com.tencent.devops.dispatch.docker.pojo.FormatLog import com.tencent.devops.dispatch.docker.pojo.LogType import com.tencent.devops.dockerhost.config.DockerHostConfig -import okhttp3.MediaType +import okhttp3.MediaType.Companion.toMediaTypeOrNull import okhttp3.RequestBody import org.slf4j.LoggerFactory import org.springframework.stereotype.Service @@ -55,12 +55,14 @@ class DockerHostBuildLogResourceApi constructor( logMessageMap = logMap ) val request = buildPost(path = path, - requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), - JsonUtil.toJson(formatLog)) + requestBody = RequestBody.create( + "application/json; charset=utf-8".toMediaTypeOrNull(), + JsonUtil.toJson(formatLog) + ) ) OkhttpUtils.doHttp(request).use { response -> - val responseContent = response.body()!!.string() + val responseContent = response.body!!.string() if (!response.isSuccessful) { logger.error("DockerHostBuildLogResourceApi $path fail. $responseContent") } diff --git a/src/backend/ci/core/dockerhost/biz-dockerhost/src/main/kotlin/com/tencent/devops/dockerhost/dispatch/DockerHostBuildResourceApi.kt b/src/backend/ci/core/dockerhost/biz-dockerhost/src/main/kotlin/com/tencent/devops/dockerhost/dispatch/DockerHostBuildResourceApi.kt index 3664fb2aa21..fa66423d159 100644 --- a/src/backend/ci/core/dockerhost/biz-dockerhost/src/main/kotlin/com/tencent/devops/dockerhost/dispatch/DockerHostBuildResourceApi.kt +++ b/src/backend/ci/core/dockerhost/biz-dockerhost/src/main/kotlin/com/tencent/devops/dockerhost/dispatch/DockerHostBuildResourceApi.kt @@ -40,7 +40,7 @@ import com.tencent.devops.dockerhost.config.DockerHostConfig import com.tencent.devops.dockerhost.utils.CommonUtils import com.tencent.devops.dockerhost.utils.SystemInfoUtil import com.tencent.devops.store.pojo.image.response.ImageRepoInfo -import okhttp3.MediaType +import okhttp3.MediaType.Companion.toMediaTypeOrNull import okhttp3.RequestBody import org.slf4j.LoggerFactory import org.springframework.stereotype.Service @@ -62,11 +62,11 @@ class DockerHostBuildResourceApi constructor( val path = "/${getUrlPrefix()}/api/dockerhost/postlog?buildId=$buildId&red=$red&tag=$tag&jobId=$jobId" val request = buildPost( path = path, - requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), message) + requestBody = RequestBody.create("application/json; charset=utf-8".toMediaTypeOrNull(), message) ) OkhttpUtils.doHttp(request).use { response -> - val responseContent = response.body()!!.string() + val responseContent = response.body!!.string() if (!response.isSuccessful) { logger.error("DockerHostBuildResourceApi $path fail. $responseContent") } @@ -80,7 +80,7 @@ class DockerHostBuildResourceApi constructor( try { val path = "/${getUrlPrefix()}/api/dockerhost/resource-config/pipelines/$pipelineId/vmSeqs/$vmSeqId" OkhttpUtils.doHttp(buildGet(path)).use { response -> - val responseContent = response.body()!!.string() + val responseContent = response.body!!.string() if (!response.isSuccessful) { logger.error("[$pipelineId]|[$vmSeqId] Get resourceConfig $path fail. $responseContent") throw TaskExecuteException( @@ -111,7 +111,7 @@ class DockerHostBuildResourceApi constructor( val path = "/${getUrlPrefix()}/api/dockerhost/qpc/projects/$projectId/builds/$buildId/" + "vmSeqs/$vmSeqId?poolNo=$poolNo" OkhttpUtils.doHttp(buildGet(path)).use { response -> - val responseContent = response.body()!!.string() + val responseContent = response.body!!.string() if (!response.isSuccessful) { logger.error("[$projectId]|[$buildId]|[$vmSeqId] Get resourceConfig $path fail. $responseContent") throw TaskExecuteException( @@ -152,12 +152,12 @@ class DockerHostBuildResourceApi constructor( val request = buildPost( path, - RequestBody.create(MediaType.parse("application/json; charset=utf-8"), JsonUtil.toJson(dockerIpInfoVO)) + RequestBody.create("application/json; charset=utf-8".toMediaTypeOrNull(), JsonUtil.toJson(dockerIpInfoVO)) ) logger.info("Start refreshDockerIpStatus $path") OkhttpUtils.doHttp(request).use { response -> - val responseContent = response.body()!!.string() + val responseContent = response.body!!.string() if (!response.isSuccessful) { logger.error("DockerHostBuildResourceApi $path fail. $responseContent") throw TaskExecuteException( @@ -177,7 +177,7 @@ class DockerHostBuildResourceApi constructor( OkhttpUtils.doHttp(request).use { response -> val contentLength = response.header("Content-Length")?.toLong() if (!response.isSuccessful) { - logger.error("DockerHostBuildResourceApi $path fail. ${response.code()}") + logger.error("DockerHostBuildResourceApi $path fail. ${response.code}") throw TaskExecuteException( errorCode = ErrorCode.SYSTEM_WORKER_INITIALIZATION_ERROR, errorType = ErrorType.SYSTEM, @@ -192,7 +192,7 @@ class DockerHostBuildResourceApi constructor( val request = buildGet(path) OkhttpUtils.doHttp(request).use { response -> - val responseContent = response.body()!!.string() + val responseContent = response.body!!.string() if (!response.isSuccessful) { logger.error("DockerHostBuildResourceApi $path fail. $responseContent") throw TaskExecuteException( diff --git a/src/backend/ci/core/image/biz-image/src/main/kotlin/com/tencent/devops/image/service/ImageArtifactoryService.kt b/src/backend/ci/core/image/biz-image/src/main/kotlin/com/tencent/devops/image/service/ImageArtifactoryService.kt index 5c2104785ea..528c71ac259 100644 --- a/src/backend/ci/core/image/biz-image/src/main/kotlin/com/tencent/devops/image/service/ImageArtifactoryService.kt +++ b/src/backend/ci/core/image/biz-image/src/main/kotlin/com/tencent/devops/image/service/ImageArtifactoryService.kt @@ -41,7 +41,7 @@ import com.tencent.devops.image.pojo.ImageItem import com.tencent.devops.image.pojo.ImageListResp import com.tencent.devops.image.pojo.ImagePageData import okhttp3.Credentials -import okhttp3.MediaType +import okhttp3.MediaType.Companion.toMediaTypeOrNull import okhttp3.Request import okhttp3.RequestBody import org.joda.time.DateTime @@ -57,7 +57,7 @@ class ImageArtifactoryService @Autowired constructor( ) { companion object { private val logger = LoggerFactory.getLogger(ImageArtifactoryService::class.java) - private val JSON = MediaType.parse("application/json;charset=utf-8") + private val JSON = "application/json;charset=utf-8".toMediaTypeOrNull() } private val credential: String @@ -334,11 +334,11 @@ class ImageArtifactoryService @Autowired constructor( try { // val response = call.execute() if (!response.isSuccessful) { - logger.error("get tag info failed, statusCode: ${response.code()}") + logger.error("get tag info failed, statusCode: ${response.code}") throw RuntimeException("get tag info failed") } - val responseBody = response.body()?.string() + val responseBody = response.body?.string() logger.info("responseBody: $responseBody") val responseData: Map = jacksonObjectMapper().readValue(responseBody!!) @@ -390,11 +390,11 @@ class ImageArtifactoryService @Autowired constructor( try { // val response = call.execute() if (!response.isSuccessful) { - logger.error("sql search failed, statusCode: ${response.code()}") + logger.error("sql search failed, statusCode: ${response.code}") throw RuntimeException("aql search failed") } - val responseBody = response.body()?.string() + val responseBody = response.body?.string() logger.info("responseBody: $responseBody") return parseImages(responseBody!!) } catch (e: Exception) { @@ -510,8 +510,8 @@ class ImageArtifactoryService @Autowired constructor( OkhttpUtils.doHttp(request).use { response -> try { // val response = call.execute() - if (!response.isSuccessful && response.code() != 404) { - val responseBody = response.body()?.string() + if (!response.isSuccessful && response.code != 404) { + val responseBody = response.body?.string() logger.error("delete item failed, responseBody: ", responseBody) throw OperationException("delete Item failed") } @@ -538,10 +538,10 @@ class ImageArtifactoryService @Autowired constructor( try { // val response = call.execute() if (!response.isSuccessful) { - if (response.code() == 404) { + if (response.code == 404) { return false } else { - val responseBody = response.body()?.string() + val responseBody = response.body?.string() logger.error("check item failed, responseBody: ", responseBody) throw OperationException("check item failed") } @@ -564,7 +564,7 @@ class ImageArtifactoryService @Autowired constructor( // .writeTimeout(60L, TimeUnit.SECONDS) // .build() val request = Request.Builder().url(url) - .post(RequestBody.create(MediaType.parse("application/json; charset=utf-8"), "")) + .post(RequestBody.create("application/json; charset=utf-8".toMediaTypeOrNull(), "")) .header("Authorization", credential) .build() // val call = okHttpClient.newCall(request) @@ -572,7 +572,7 @@ class ImageArtifactoryService @Autowired constructor( try { // val response = call.execute() if (!response.isSuccessful) { - val responseBody = response.body()?.string() + val responseBody = response.body?.string() logger.error("copy item failed, responseBody: $responseBody}") throw RuntimeException("aql search failed") } @@ -593,7 +593,7 @@ class ImageArtifactoryService @Autowired constructor( // .writeTimeout(60L, TimeUnit.SECONDS) // .build() val request = Request.Builder().url(url) - .put(RequestBody.create(MediaType.parse("application/json; charset=utf-8"), "")) + .put(RequestBody.create("application/json; charset=utf-8".toMediaTypeOrNull(), "")) .header("Authorization", credential) .build() // val call = okHttpClient.newCall(request) @@ -601,7 +601,7 @@ class ImageArtifactoryService @Autowired constructor( try { // val response = call.execute() if (!response.isSuccessful) { - val responseBody = response.body()?.string() + val responseBody = response.body?.string() logger.error("set item properties failed, responseBody: $responseBody}") throw RuntimeException("set item properties failed") } diff --git a/src/backend/ci/core/notify/biz-notify-blueking/src/main/kotlin/com/tencent/devops/notify/blueking/sdk/utils/NotifyUtils.kt b/src/backend/ci/core/notify/biz-notify-blueking/src/main/kotlin/com/tencent/devops/notify/blueking/sdk/utils/NotifyUtils.kt index 7aaacabed4e..c2efe4e863e 100644 --- a/src/backend/ci/core/notify/biz-notify-blueking/src/main/kotlin/com/tencent/devops/notify/blueking/sdk/utils/NotifyUtils.kt +++ b/src/backend/ci/core/notify/biz-notify-blueking/src/main/kotlin/com/tencent/devops/notify/blueking/sdk/utils/NotifyUtils.kt @@ -32,7 +32,7 @@ import com.tencent.devops.notify.blueking.sdk.pojo.ApiReq import com.tencent.devops.notify.blueking.sdk.pojo.ApiResp import com.tencent.devops.notify.blueking.sdk.pojo.NotifyProperties import com.tencent.devops.notify.constant.NotifyMessageCode.ERROR_NOTIFY_SEND_FAIL -import okhttp3.MediaType +import okhttp3.MediaType.Companion.toMediaTypeOrNull import okhttp3.Request import okhttp3.RequestBody import org.slf4j.LoggerFactory @@ -62,7 +62,7 @@ class NotifyUtils constructor( body.bk_app_secret = appSecret val jsonbody = ObjectMapper().writeValueAsString(body) - val requestBody = RequestBody.create(MediaType.parse("application/json"), jsonbody.toString()) + val requestBody = RequestBody.create("application/json".toMediaTypeOrNull(), jsonbody.toString()) val url = host + uri logger.info("notify post url: $url") logger.info("notify post body: $jsonbody") @@ -83,18 +83,18 @@ class NotifyUtils constructor( try { val response = okHttpClient.newCall(request).execute() if (response.isSuccessful) { - val responseStr = response.body()!!.string() + val responseStr = response.body!!.string() logger.info("notify response: $responseStr") resultBean = ObjectMapper().readValue(responseStr, ApiResp::class.java) } else { - logger.error("NOTIFY_REQUEST_FAILED|url=${request.url().url()}|response=($response)") + logger.error("NOTIFY_REQUEST_FAILED|url=${request.url.toUrl()}|response=($response)") } if (!resultBean.result!!) { - logger.error("NOTIFY_SEND_MSG_FAILED|url=${request.url().url()}|message=${resultBean.message}") + logger.error("NOTIFY_SEND_MSG_FAILED|url=${request.url.toUrl()}|message=${resultBean.message}") } return resultBean } catch (ignore: Exception) { - logger.error("NOTIFY_SEND_MSG_FAILED|url=${request.url().url()}|message=${ignore.message}", ignore) + logger.error("NOTIFY_SEND_MSG_FAILED|url=${request.url.toUrl()}|message=${ignore.message}", ignore) throw ErrorCodeException( errorCode = ERROR_NOTIFY_SEND_FAIL, defaultMessage = "notify send msg failed: ${ignore.message}" diff --git a/src/backend/ci/core/notify/biz-notify-tencentcloud/src/main/kotlin/com/tencent/devops/notify/tencentcloud/service/inner/TencentCloudEmailServiceImpl.kt b/src/backend/ci/core/notify/biz-notify-tencentcloud/src/main/kotlin/com/tencent/devops/notify/tencentcloud/service/inner/TencentCloudEmailServiceImpl.kt index fc2fdab9e75..f24babdf187 100644 --- a/src/backend/ci/core/notify/biz-notify-tencentcloud/src/main/kotlin/com/tencent/devops/notify/tencentcloud/service/inner/TencentCloudEmailServiceImpl.kt +++ b/src/backend/ci/core/notify/biz-notify-tencentcloud/src/main/kotlin/com/tencent/devops/notify/tencentcloud/service/inner/TencentCloudEmailServiceImpl.kt @@ -179,10 +179,10 @@ class TencentCloudEmailServiceImpl @Autowired constructor( headers: Map ): EmailResponse { val response = OkhttpUtils.doPost(url = url, jsonParam = body, headers = headers) - val responseContent = response.body()!!.string() + val responseContent = response.body!!.string() if (!response.isSuccessful) { throw RemoteServiceException( - httpStatus = response.code(), + httpStatus = response.code, responseContent = responseContent, errorMessage = "send tencent cloud email message failed" ) diff --git a/src/backend/ci/core/notify/biz-notify-wework/src/main/kotlin/com/tencent/devops/notify/wework/service/inner/WeworkServiceImpl.kt b/src/backend/ci/core/notify/biz-notify-wework/src/main/kotlin/com/tencent/devops/notify/wework/service/inner/WeworkServiceImpl.kt index 7594286e7a0..115be56e88d 100644 --- a/src/backend/ci/core/notify/biz-notify-wework/src/main/kotlin/com/tencent/devops/notify/wework/service/inner/WeworkServiceImpl.kt +++ b/src/backend/ci/core/notify/biz-notify-wework/src/main/kotlin/com/tencent/devops/notify/wework/service/inner/WeworkServiceImpl.kt @@ -95,7 +95,13 @@ class WeworkServiceImpl( val mediaId = uploadMedia(mediaType, mediaInputStream, mediaName) val requestBodies = (toUser.map { getSendMessageRequest(mediaType = mediaType, mediaId = mediaId, toUser = it) } + - toParty.map { getSendMessageRequest(mediaType = mediaType, mediaId = mediaId, toParty = it) }) + toParty.map { + getSendMessageRequest( + mediaType = mediaType, + mediaId = mediaId, + toParty = it + ) + }) .filter { it.isPresent } doSendRequest(requestBodies) }.fold({ @@ -120,13 +126,13 @@ class WeworkServiceImpl( textType = WeworkTextType.text ) } + - toParty.map { - getSendMessageRequest( - content = message, - toUser = it, - textType = WeworkTextType.text - ) - }).filter { it.isPresent } + toParty.map { + getSendMessageRequest( + content = message, + toUser = it, + textType = WeworkTextType.text + ) + }).filter { it.isPresent } doSendRequest(requestBodies) }.fold({ LOG.info("send message success, $weworkNotifyTextMessage") @@ -164,19 +170,19 @@ class WeworkServiceImpl( val url = buildUrl("${weWorkConfiguration.apiUrl}/cgi-bin/message/send?access_token=${getAccessToken()}") val requestBody = JsonUtil.toJson(abstractSendMessageRequest) return OkhttpUtils.doPost(url, requestBody).use { - val responseBody = it.body()?.string() ?: "" + val responseBody = it.body?.string() ?: "" kotlin.runCatching { val sendMessageResp = JsonUtil.to(responseBody, jacksonTypeRef()) if (!it.isSuccessful || 0 != sendMessageResp.errCode) { throw RemoteServiceException( - httpStatus = it.code(), + httpStatus = it.code, responseContent = responseBody, errorMessage = "send wework message failed", errorCode = sendMessageResp.errCode ) } }.fold({ Optional.empty() }, { e -> - LOG.warn("${it.request()}|send wework message failed, $responseBody") + LOG.warn("${it.request}|send wework message failed, $responseBody") Optional.of(e) }) } @@ -186,6 +192,7 @@ class WeworkServiceImpl( * 非文本消息时,默认 mediaId 不为空 * 文本消息时,默认 content 不为空 */ + @SuppressWarnings("ComplexMethod") private fun getSendMessageRequest( mediaType: WeworkMediaType? = null, mediaId: String? = null, @@ -212,6 +219,7 @@ class WeworkServiceImpl( ) ) } + WeworkMediaType.image -> { Optional.of( ImageSendMessageRequest( @@ -226,6 +234,7 @@ class WeworkServiceImpl( ) ) } + WeworkMediaType.video -> { Optional.of( VideoSendMessageRequest( @@ -240,6 +249,7 @@ class WeworkServiceImpl( ) ) } + WeworkMediaType.voice -> { Optional.of( VoiceSendMessageRequest( @@ -270,6 +280,7 @@ class WeworkServiceImpl( text = TextMessageContent(content) ) ) + WeworkTextType.markdown -> Optional.of( MarkdownSendMessageRequest( agentId = agentId, @@ -303,6 +314,7 @@ class WeworkServiceImpl( .map { it.joinToString(separator = "|") } Pair(toUser, emptyList()) } + WeworkReceiverType.group -> { val toParty = HashSet(this).chunked(maxGroupNum).map { it.joinToString(separator = "|") } Pair(emptyList(), toParty) @@ -324,14 +336,14 @@ class WeworkServiceImpl( fileFieldName = "media", fileName = mediaName ).use { - val responseBody = it.body()?.string() ?: "{}" + val responseBody = it.body?.string() ?: "{}" return kotlin.runCatching { val uploadMediaResp = JsonUtil.to(responseBody, jacksonTypeRef()) val mediaId = uploadMediaResp.mediaId if (!it.isSuccessful || mediaId.isNullOrBlank()) { - LOG.warn("${it.request()}|upload media($mediaName) to wework failed, $responseBody") + LOG.warn("${it.request}|upload media($mediaName) to wework failed, $responseBody") throw RemoteServiceException( - httpStatus = it.code(), + httpStatus = it.code, responseContent = responseBody, errorMessage = "upload media($mediaName) to wework failed", errorCode = uploadMediaResp.errCode @@ -339,7 +351,7 @@ class WeworkServiceImpl( } mediaId }.onFailure { _ -> - LOG.warn("${it.request()}|upload media($mediaName) to wework failed, $responseBody") + LOG.warn("${it.request}|upload media($mediaName) to wework failed, $responseBody") }.getOrThrow() } } finally { @@ -364,16 +376,16 @@ class WeworkServiceImpl( OkhttpUtils.doGet( buildUrl( "${weWorkConfiguration.apiUrl}/cgi-bin" + - "/gettoken?corpId=${weWorkConfiguration.corpId}&corpSecret=${weWorkConfiguration.corpSecret}" + "/gettoken?corpId=${weWorkConfiguration.corpId}&corpSecret=${weWorkConfiguration.corpSecret}" ) ).use { - val responseBody = it.body()?.string() ?: "{}" + val responseBody = it.body?.string() ?: "{}" return kotlin.runCatching { val accessTokenResp = JsonUtil.to(responseBody, jacksonTypeRef()) if (!it.isSuccessful && accessTokenResp.isOk()) { - LOG.warn("${it.request()}|failed to get wework access token: $responseBody") + LOG.warn("${it.request}|failed to get wework access token: $responseBody") throw RemoteServiceException( - httpStatus = it.code(), + httpStatus = it.code, responseContent = responseBody, errorMessage = "failed to get wework access token: $responseBody", errorCode = accessTokenResp.errCode @@ -391,7 +403,7 @@ class WeworkServiceImpl( } accessToken }.onFailure { _ -> - LOG.warn("${it.request()}|failed to get wework access token: $responseBody") + LOG.warn("${it.request}|failed to get wework access token: $responseBody") }.getOrThrow() } } diff --git a/src/backend/ci/core/openapi/biz-openapi/src/main/kotlin/com/tencent/devops/openapi/resources/apigw/v3/ApigwLogResourceV3Impl.kt b/src/backend/ci/core/openapi/biz-openapi/src/main/kotlin/com/tencent/devops/openapi/resources/apigw/v3/ApigwLogResourceV3Impl.kt index 6f2c2cd5151..f5d8edacece 100644 --- a/src/backend/ci/core/openapi/biz-openapi/src/main/kotlin/com/tencent/devops/openapi/resources/apigw/v3/ApigwLogResourceV3Impl.kt +++ b/src/backend/ci/core/openapi/biz-openapi/src/main/kotlin/com/tencent/devops/openapi/resources/apigw/v3/ApigwLogResourceV3Impl.kt @@ -178,7 +178,7 @@ class ApigwLogResourceV3Impl @Autowired constructor( headers = headers ) return Response - .ok(response.body()!!.byteStream(), MediaType.APPLICATION_OCTET_STREAM_TYPE) + .ok(response.body!!.byteStream(), MediaType.APPLICATION_OCTET_STREAM_TYPE) .header("content-disposition", "attachment; filename = $pipelineId-$buildId-log.txt") .header("Cache-Control", "no-cache") .build() diff --git a/src/backend/ci/core/openapi/biz-openapi/src/main/kotlin/com/tencent/devops/openapi/resources/apigw/v4/ApigwLogResourceV4Impl.kt b/src/backend/ci/core/openapi/biz-openapi/src/main/kotlin/com/tencent/devops/openapi/resources/apigw/v4/ApigwLogResourceV4Impl.kt index 4f5370ff0d2..24201f35634 100644 --- a/src/backend/ci/core/openapi/biz-openapi/src/main/kotlin/com/tencent/devops/openapi/resources/apigw/v4/ApigwLogResourceV4Impl.kt +++ b/src/backend/ci/core/openapi/biz-openapi/src/main/kotlin/com/tencent/devops/openapi/resources/apigw/v4/ApigwLogResourceV4Impl.kt @@ -180,7 +180,7 @@ class ApigwLogResourceV4Impl @Autowired constructor( headers = headers ) return Response - .ok(response.body()!!.byteStream(), MediaType.APPLICATION_OCTET_STREAM_TYPE) + .ok(response.body!!.byteStream(), MediaType.APPLICATION_OCTET_STREAM_TYPE) .header("content-disposition", "attachment; filename = $pipelineId-$buildId-log.txt") .header("Cache-Control", "no-cache") .build() diff --git a/src/backend/ci/core/plugin/codecc-plugin/biz-codecc/src/main/kotlin/com/tencent/devops/plugin/codecc/service/CodeccService.kt b/src/backend/ci/core/plugin/codecc-plugin/biz-codecc/src/main/kotlin/com/tencent/devops/plugin/codecc/service/CodeccService.kt index fb94c7811b5..b4b1512f655 100644 --- a/src/backend/ci/core/plugin/codecc-plugin/biz-codecc/src/main/kotlin/com/tencent/devops/plugin/codecc/service/CodeccService.kt +++ b/src/backend/ci/core/plugin/codecc-plugin/biz-codecc/src/main/kotlin/com/tencent/devops/plugin/codecc/service/CodeccService.kt @@ -43,7 +43,7 @@ import com.tencent.devops.plugin.codecc.pojo.CodeccBuildInfo import com.tencent.devops.plugin.codecc.pojo.CodeccCallback import com.tencent.devops.process.api.service.ServiceBuildResource import com.tencent.devops.process.api.service.ServicePipelineResource -import okhttp3.MediaType +import okhttp3.MediaType.Companion.toMediaTypeOrNull import okhttp3.Request import okhttp3.RequestBody import org.jooq.DSLContext @@ -179,7 +179,7 @@ class CodeccService @Autowired constructor( } private fun getCodeccBlueShield(request: BlueShieldRequest): BlueShieldResponse { - val mediaType = MediaType.parse("application/json") + val mediaType = "application/json".toMediaTypeOrNull() val json = objectMapper.writeValueAsString(request) val requestBody = RequestBody.create(mediaType, json) val url = "http://$codeccHost/blueShield/dataMeasure" @@ -193,11 +193,11 @@ class CodeccService @Autowired constructor( try { OkhttpUtils.doHttp(httpReq).use { response -> - val body = response.body()!!.string() + val body = response.body!!.string() logger.info("codecc blueShield response: $body") if (!response.isSuccessful) { throw ErrorCodeException( - errorCode = response.code().toString(), + errorCode = response.code.toString(), defaultMessage = "get codecc blueShield response fail $body" ) } diff --git a/src/backend/ci/core/plugin/codecc-plugin/common-codecc/src/main/kotlin/com/tencent/devops/plugin/codecc/CodeccApi.kt b/src/backend/ci/core/plugin/codecc-plugin/common-codecc/src/main/kotlin/com/tencent/devops/plugin/codecc/CodeccApi.kt index 736793ecd1b..ec0c11dab88 100644 --- a/src/backend/ci/core/plugin/codecc-plugin/common-codecc/src/main/kotlin/com/tencent/devops/plugin/codecc/CodeccApi.kt +++ b/src/backend/ci/core/plugin/codecc-plugin/common-codecc/src/main/kotlin/com/tencent/devops/plugin/codecc/CodeccApi.kt @@ -35,7 +35,7 @@ import com.tencent.devops.common.api.pojo.Result import com.tencent.devops.common.api.util.JsonUtil import com.tencent.devops.common.api.util.OkhttpUtils import com.tencent.devops.plugin.codecc.pojo.CodeccMeasureInfo -import okhttp3.MediaType +import okhttp3.MediaType.Companion.toMediaTypeOrNull import okhttp3.Request import okhttp3.RequestBody import org.slf4j.LoggerFactory @@ -63,7 +63,7 @@ open class CodeccApi constructor( ): String { val jsonBody = objectMapper.writeValueAsString(body) val requestBody = RequestBody.create( - MediaType.parse("application/json; charset=utf-8"), jsonBody + "application/json; charset=utf-8".toMediaTypeOrNull(), jsonBody ) val builder = Request.Builder() @@ -92,7 +92,7 @@ open class CodeccApi constructor( val request = builder.build() OkhttpUtils.doHttp(request).use { response -> - val responseBody = response.body()!!.string() + val responseBody = response.body!!.string() if (!response.isSuccessful) { throw RemoteServiceException("Fail to invoke codecc request") } diff --git a/src/backend/ci/core/process/biz-base/src/main/kotlin/com/tencent/devops/process/engine/atom/plugin/MarketBuildUtils.kt b/src/backend/ci/core/process/biz-base/src/main/kotlin/com/tencent/devops/process/engine/atom/plugin/MarketBuildUtils.kt index 4ccc11613a9..05f0362857f 100644 --- a/src/backend/ci/core/process/biz-base/src/main/kotlin/com/tencent/devops/process/engine/atom/plugin/MarketBuildUtils.kt +++ b/src/backend/ci/core/process/biz-base/src/main/kotlin/com/tencent/devops/process/engine/atom/plugin/MarketBuildUtils.kt @@ -137,7 +137,7 @@ object MarketBuildUtils { } OkhttpUtils.doHttp(request.build()).use { response -> - val body = response.body()!!.string() + val body = response.body!!.string() logger.info("before delete execute result: $body") } } diff --git a/src/backend/ci/core/process/biz-process/src/main/kotlin/com/tencent/devops/process/engine/control/CallBackControl.kt b/src/backend/ci/core/process/biz-process/src/main/kotlin/com/tencent/devops/process/engine/control/CallBackControl.kt index 35b2dda2c7b..5aaa42b04ed 100644 --- a/src/backend/ci/core/process/biz-process/src/main/kotlin/com/tencent/devops/process/engine/control/CallBackControl.kt +++ b/src/backend/ci/core/process/biz-process/src/main/kotlin/com/tencent/devops/process/engine/control/CallBackControl.kt @@ -60,7 +60,7 @@ import com.tencent.devops.process.pojo.ProjectPipelineCallBackHistory import com.tencent.devops.project.api.service.ServiceAllocIdResource import io.github.resilience4j.circuitbreaker.CallNotPermittedException import io.github.resilience4j.circuitbreaker.CircuitBreakerRegistry -import okhttp3.MediaType +import okhttp3.MediaType.Companion.toMediaTypeOrNull import okhttp3.OkHttpClient import okhttp3.Request import okhttp3.RequestBody @@ -440,7 +440,7 @@ class CallBackControl @Autowired constructor( companion object { private val logger = LoggerFactory.getLogger(CallBackControl::class.java) - private val JSON = MediaType.parse("application/json;charset=utf-8") + private val JSON = "application/json;charset=utf-8".toMediaTypeOrNull() const val MAX_RETRY_COUNT = 3 private fun anySslSocketFactory(): SSLSocketFactory { diff --git a/src/backend/ci/core/process/biz-process/src/main/kotlin/com/tencent/devops/process/engine/service/ProjectPipelineCallBackService.kt b/src/backend/ci/core/process/biz-process/src/main/kotlin/com/tencent/devops/process/engine/service/ProjectPipelineCallBackService.kt index 86659871c91..1c429877439 100644 --- a/src/backend/ci/core/process/biz-process/src/main/kotlin/com/tencent/devops/process/engine/service/ProjectPipelineCallBackService.kt +++ b/src/backend/ci/core/process/biz-process/src/main/kotlin/com/tencent/devops/process/engine/service/ProjectPipelineCallBackService.kt @@ -52,7 +52,7 @@ import com.tencent.devops.process.pojo.CreateCallBackResult import com.tencent.devops.process.pojo.ProjectPipelineCallBackHistory import com.tencent.devops.process.pojo.setting.PipelineModelVersion import com.tencent.devops.project.api.service.ServiceAllocIdResource -import okhttp3.MediaType +import okhttp3.MediaType.Companion.toMediaTypeOrNull import okhttp3.Request import okhttp3.RequestBody import org.jooq.DSLContext @@ -79,7 +79,7 @@ class ProjectPipelineCallBackService @Autowired constructor( companion object { private val logger = LoggerFactory.getLogger(ProjectPipelineCallBackService::class.java) - private val JSON = MediaType.parse("application/json;charset=utf-8") + private val JSON = "application/json;charset=utf-8".toMediaTypeOrNull() } fun createCallBack( @@ -324,19 +324,19 @@ class ProjectPipelineCallBackService @Autowired constructor( var status = ProjectPipelineCallbackStatus.SUCCESS try { OkhttpUtils.doHttp(request).use { response -> - if (response.code() != 200) { - logger.warn("[${record.projectId}]|CALL_BACK|url=${record.callBackUrl}| code=${response.code()}") + if (response.code != 200) { + logger.warn("[${record.projectId}]|CALL_BACK|url=${record.callBackUrl}| code=${response.code}") throw ErrorCodeException( - statusCode = response.code(), + statusCode = response.code, errorCode = ProcessMessageCode.ERROR_CALLBACK_REPLY_FAIL, defaultMessage = "回调重试失败" ) } else { - logger.info("[${record.projectId}]|CALL_BACK|url=${record.callBackUrl}| code=${response.code()}") + logger.info("[${record.projectId}]|CALL_BACK|url=${record.callBackUrl}| code=${response.code}") } - responseCode = response.code() - responseBody = response.body()?.string() - errorMsg = response.message() + responseCode = response.code + responseBody = response.body?.string() + errorMsg = response.message } } catch (e: Exception) { logger.error("[$projectId]|[$userId]|CALL_BACK|url=${record.callBackUrl} error", e) @@ -350,7 +350,7 @@ class ProjectPipelineCallBackService @Autowired constructor( events = record.events, status = status.name, errorMsg = errorMsg, - requestHeaders = request.headers().names().map { + requestHeaders = request.headers.names().map { CallBackHeader( name = it, value = request.header(it) ?: "" diff --git a/src/backend/ci/core/process/biz-process/src/main/kotlin/com/tencent/devops/process/service/PipelineAtomReplaceCronService.kt b/src/backend/ci/core/process/biz-process/src/main/kotlin/com/tencent/devops/process/service/PipelineAtomReplaceCronService.kt index bedf7c1c59b..2d0383ca8e8 100644 --- a/src/backend/ci/core/process/biz-process/src/main/kotlin/com/tencent/devops/process/service/PipelineAtomReplaceCronService.kt +++ b/src/backend/ci/core/process/biz-process/src/main/kotlin/com/tencent/devops/process/service/PipelineAtomReplaceCronService.kt @@ -866,7 +866,7 @@ class PipelineAtomReplaceCronService @Autowired constructor( toFieldDefaultValue = paramReplaceInfo.toParamValue ) val response = OkhttpUtils.doPost(paramConvertUrl, JsonUtil.toJson(atomReplaceParamConvertRequest)) - val responseContent = response.body()!!.string() + val responseContent = response.body!!.string() val errorMessage = "$fromParamName convert $toParamName fail" if (!response.isSuccessful) { throw ErrorCodeException( diff --git a/src/backend/ci/core/repository/biz-repository/src/main/kotlin/com/tencent/devops/repository/service/github/GithubOAuthService.kt b/src/backend/ci/core/repository/biz-repository/src/main/kotlin/com/tencent/devops/repository/service/github/GithubOAuthService.kt index 78e649cd4a0..818d99c6282 100644 --- a/src/backend/ci/core/repository/biz-repository/src/main/kotlin/com/tencent/devops/repository/service/github/GithubOAuthService.kt +++ b/src/backend/ci/core/repository/biz-repository/src/main/kotlin/com/tencent/devops/repository/service/github/GithubOAuthService.kt @@ -41,7 +41,7 @@ import com.tencent.devops.repository.pojo.github.GithubOauth import com.tencent.devops.repository.pojo.github.GithubOauthCallback import com.tencent.devops.repository.pojo.github.GithubToken import com.tencent.devops.scm.config.GitConfig -import okhttp3.MediaType +import okhttp3.MediaType.Companion.toMediaTypeOrNull import okhttp3.Request import okhttp3.RequestBody import org.apache.commons.lang3.RandomStringUtils @@ -136,14 +136,14 @@ class GithubOAuthService @Autowired constructor( val request = Request.Builder() .url(url) .header("Accept", "application/json") - .post(RequestBody.create(MediaType.parse("application/x-www-form-urlencoded;charset=utf-8"), "")) + .post(RequestBody.create("application/x-www-form-urlencoded;charset=utf-8".toMediaTypeOrNull(), "")) .build() OkhttpUtils.doHttp(request).use { response -> - val data = response.body()!!.string() + val data = response.body!!.string() if (!response.isSuccessful) { - logger.info("Github get code(${response.code()}) and response($data)") + logger.info("Github get code(${response.code}) and response($data)") throw CustomException( - Response.Status.fromStatusCode(response.code()) + Response.Status.fromStatusCode(response.code) ?: Response.Status.BAD_REQUEST, "获取Github access_token失败: $data" ) diff --git a/src/backend/ci/core/repository/biz-repository/src/main/kotlin/com/tencent/devops/repository/service/github/GithubService.kt b/src/backend/ci/core/repository/biz-repository/src/main/kotlin/com/tencent/devops/repository/service/github/GithubService.kt index 323d188eaa3..efa5254202b 100644 --- a/src/backend/ci/core/repository/biz-repository/src/main/kotlin/com/tencent/devops/repository/service/github/GithubService.kt +++ b/src/backend/ci/core/repository/biz-repository/src/main/kotlin/com/tencent/devops/repository/service/github/GithubService.kt @@ -52,7 +52,7 @@ import com.tencent.devops.repository.pojo.github.GithubTag import com.tencent.devops.scm.config.GitConfig import com.tencent.devops.scm.exception.GithubApiException import com.tencent.devops.scm.pojo.Project -import okhttp3.MediaType +import okhttp3.MediaType.Companion.toMediaTypeOrNull import okhttp3.Request import okhttp3.RequestBody import org.slf4j.LoggerFactory @@ -229,11 +229,11 @@ class GithubService @Autowired constructor( logger.info("github content url: $url") if (!it.isSuccessful) { throw CustomException( - status = Response.Status.fromStatusCode(it.code()) ?: Response.Status.BAD_REQUEST, - message = it.body()!!.toString() + status = Response.Status.fromStatusCode(it.code) ?: Response.Status.BAD_REQUEST, + message = it.body!!.toString() ) } - return it.body()!!.string() + return it.body!!.string() } } @@ -279,13 +279,13 @@ class GithubService @Autowired constructor( private fun buildPost(token: String, path: String, body: String): Request { return request(token, path) - .post(RequestBody.create(MediaType.parse("application/json; charset=utf-8"), body)) + .post(RequestBody.create("application/json; charset=utf-8".toMediaTypeOrNull(), body)) .build() } private fun buildPatch(token: String, path: String, body: String): Request { return request(token, path) - .patch(RequestBody.create(MediaType.parse("application/json; charset=utf-8"), body)) + .patch(RequestBody.create("application/json; charset=utf-8".toMediaTypeOrNull(), body)) .build() } @@ -304,9 +304,9 @@ class GithubService @Autowired constructor( private fun getBody(operation: String, request: Request): String { OkhttpUtils.doHttp(request).use { response -> - val code = response.code() - val message = response.message() - val body = response.body()?.string() ?: "" + val code = response.code + val message = response.message + val body = response.body?.string() ?: "" if (logger.isDebugEnabled) { logger.debug("getBody operation($operation). response code($code) message($message) body($body)") } @@ -319,9 +319,9 @@ class GithubService @Autowired constructor( private fun callMethod(operation: String, request: Request, classOfT: Class): T { OkhttpUtils.doHttp(request).use { response -> - val code = response.code() - val message = response.message() - val body = response.body()?.string() ?: "" + val code = response.code + val message = response.message + val body = response.body?.string() ?: "" if (logger.isDebugEnabled) { logger.debug("callMethod operation($operation). response code($code) message($message) body($body)") } diff --git a/src/backend/ci/core/repository/biz-repository/src/main/kotlin/com/tencent/devops/repository/service/scm/GitService.kt b/src/backend/ci/core/repository/biz-repository/src/main/kotlin/com/tencent/devops/repository/service/scm/GitService.kt index 4cbeff41191..843181be026 100644 --- a/src/backend/ci/core/repository/biz-repository/src/main/kotlin/com/tencent/devops/repository/service/scm/GitService.kt +++ b/src/backend/ci/core/repository/biz-repository/src/main/kotlin/com/tencent/devops/repository/service/scm/GitService.kt @@ -88,7 +88,7 @@ import com.tencent.devops.scm.pojo.Project import com.tencent.devops.scm.pojo.TapdWorkItem import com.tencent.devops.scm.utils.code.git.GitUtils import com.tencent.devops.store.pojo.common.BK_FRONTEND_DIR_NAME -import okhttp3.MediaType +import okhttp3.MediaType.Companion.toMediaTypeOrNull import okhttp3.Request import okhttp3.RequestBody import org.slf4j.LoggerFactory @@ -153,7 +153,7 @@ class GitService @Autowired constructor( .build() OkhttpUtils.doHttp(request).use { response -> - val data = response.body()!!.string() + val data = response.body!!.string() val repoList = JsonParser().parse(data).asJsonArray repoList.forEach { val obj = it.asJsonObject @@ -216,7 +216,7 @@ class GitService @Autowired constructor( .build() OkhttpUtils.doHttp(request).use { response -> - val data = response.body()?.string() ?: return@use + val data = response.body?.string() ?: return@use val repoList = JsonParser().parse(data).asJsonArray if (!repoList.isJsonNull) { repoList.forEach { @@ -266,7 +266,7 @@ class GitService @Autowired constructor( .build() OkhttpUtils.doHttp(request).use { response -> - val data = response.body()?.string() ?: return@use + val data = response.body?.string() ?: return@use val branList = JsonParser().parse(data).asJsonArray if (!branList.isJsonNull) { branList.forEach { @@ -324,7 +324,7 @@ class GitService @Autowired constructor( .build() OkhttpUtils.doHttp(request).use { response -> - val data = response.body()?.string() ?: return@use + val data = response.body?.string() ?: return@use val tagList = JsonParser().parse(data).asJsonArray if (!tagList.isJsonNull) { tagList.forEach { @@ -378,10 +378,10 @@ class GitService @Autowired constructor( "&redirect_uri=${gitConfig.gitHookUrl}" val request = Request.Builder() .url(url) - .post(RequestBody.create(MediaType.parse("application/x-www-form-urlencoded;charset=utf-8"), "")) + .post(RequestBody.create("application/x-www-form-urlencoded;charset=utf-8".toMediaTypeOrNull(), "")) .build() OkhttpUtils.doHttp(request).use { response -> - val data = response.body()!!.string() + val data = response.body!!.string() return objectMapper.readValue(data, GitToken::class.java) } } finally { @@ -407,11 +407,11 @@ class GitService @Autowired constructor( logger.info("getToken url>> $tokenUrl") val request = Request.Builder() .url(tokenUrl) - .post(RequestBody.create(MediaType.parse("application/x-www-form-urlencoded;charset=utf-8"), "")) + .post(RequestBody.create("application/x-www-form-urlencoded;charset=utf-8".toMediaTypeOrNull(), "")) .build() OkhttpUtils.doHttp(request).use { response -> - val data = response.body()!!.string() + val data = response.body!!.string() return objectMapper.readValue(data, GitToken::class.java) } } finally { @@ -432,7 +432,7 @@ class GitService @Autowired constructor( .get() .build() OkhttpUtils.doHttp(request).use { response -> - val data = response.body()!!.string() + val data = response.body!!.string() return objectMapper.readValue(data, GitUserInfo::class.java) } } finally { @@ -497,7 +497,7 @@ class GitService @Autowired constructor( val data = it.stringLimit(readLimit = MAX_FILE_SIZE, errorMsg = "请求文件不能超过1M") if (!it.isSuccessful) { throw CustomException( - status = Response.Status.fromStatusCode(it.code()) ?: Response.Status.BAD_REQUEST, + status = Response.Status.fromStatusCode(it.code) ?: Response.Status.BAD_REQUEST, message = "fail to get git file content with: $url($data)" ) } @@ -571,10 +571,10 @@ class GitService @Autowired constructor( } val request = Request.Builder() .url(url.toString()) - .post(RequestBody.create(MediaType.parse("application/json;charset=utf-8"), JsonUtil.toJson(params))) + .post(RequestBody.create("application/json;charset=utf-8".toMediaTypeOrNull(), JsonUtil.toJson(params))) .build() OkhttpUtils.doHttp(request).use { response -> - val data = response.body()!!.string() + val data = response.body!!.string() val dataMap = JsonUtil.toMap(data) val atomRepositoryUrl = dataMap["http_url_to_repo"] if (StringUtils.isEmpty(atomRepositoryUrl)) { @@ -718,10 +718,10 @@ class GitService @Autowired constructor( params["access_level"] = gitAccessLevel.level val request = Request.Builder() .url(url.toString()) - .post(RequestBody.create(MediaType.parse("application/json;charset=utf-8"), JsonUtil.toJson(params))) + .post(RequestBody.create("application/json;charset=utf-8".toMediaTypeOrNull(), JsonUtil.toJson(params))) .build() OkhttpUtils.doHttp(request).use { response -> - val data = response.body()!!.string() + val data = response.body!!.string() if (!StringUtils.isEmpty(data)) { val dataMap = JsonUtil.toMap(data) val message = dataMap["message"] @@ -777,7 +777,7 @@ class GitService @Autowired constructor( .delete() .build() OkhttpUtils.doHttp(request).use { response -> - val data = response.body()!!.string() + val data = response.body!!.string() logger.info("deleteGitProjectMember response>> $data") if (!StringUtils.isEmpty(data)) { val dataMap = JsonUtil.toMap(data) @@ -814,7 +814,7 @@ class GitService @Autowired constructor( .get() .build() OkhttpUtils.doHttp(request).use { - val data = it.body()!!.string() + val data = it.body!!.string() logger.info("getGitProjectMemberInfo response>> $data") if (!StringUtils.isEmpty(data)) { val dataMap = JsonUtil.toMap(data) @@ -838,7 +838,7 @@ class GitService @Autowired constructor( .delete() .build() OkhttpUtils.doHttp(request).use { - val data = it.body()!!.string() + val data = it.body!!.string() logger.info("deleteGitProject response>> $data") if (!StringUtils.isEmpty(data)) { val dataMap = JsonUtil.toMap(data) @@ -867,7 +867,7 @@ class GitService @Autowired constructor( .get() .build() OkhttpUtils.doHttp(request).use { - val data = it.body()!!.string() + val data = it.body!!.string() logger.info("getGitUserInfo response>> $data") if (!it.isSuccessful) return MessageCodeUtil.generateResponseDataObject(CommonMessageCode.SYSTEM_ERROR) if (!StringUtils.isEmpty(data)) { @@ -892,7 +892,7 @@ class GitService @Autowired constructor( .get() .build() OkhttpUtils.doHttp(request).use { - val data = it.body()!!.string() + val data = it.body!!.string() logger.info("GitProjectInfo response>> $data") if (!it.isSuccessful) return MessageCodeUtil.generateResponseDataObject(CommonMessageCode.SYSTEM_ERROR) return Result(JsonUtil.to(data, GitProjectInfo::class.java)) @@ -924,7 +924,7 @@ class GitService @Autowired constructor( .get() .build() OkhttpUtils.doHttp(request).use { - val data = it.body()!!.string() + val data = it.body!!.string() logger.info("getGitRepositoryTreeInfo response>> $data") if (!StringUtils.isEmpty(data)) { var message: String? = null @@ -959,13 +959,13 @@ class GitService @Autowired constructor( .url(url.toString()) .put( RequestBody.create( - MediaType.parse("application/json;charset=utf-8"), + "application/json;charset=utf-8".toMediaTypeOrNull(), JsonUtil.toJson(updateGitProjectInfo) ) ) .build() OkhttpUtils.doHttp(request).use { - val data = it.body()!!.string() + val data = it.body!!.string() logger.info("updateGitProjectInfo response>> $data") val dataMap = JsonUtil.toMap(data) val message = dataMap["message"] @@ -1008,14 +1008,14 @@ class GitService @Autowired constructor( .url(url.toString()) .post( RequestBody.create( - MediaType.parse("application/json;charset=utf-8"), + "application/json;charset=utf-8".toMediaTypeOrNull(), JsonUtil.toJson(mapOf()) ) ) .build() OkhttpUtils.doHttp(request).use { if (!it.isSuccessful) { - val data = it.body()!!.string() + val data = it.body!!.string() logger.info("moveProjectToGroup response>> $data") val dataMap = JsonUtil.toMap(data) val message = dataMap["message"] @@ -1059,11 +1059,11 @@ class GitService @Autowired constructor( OkhttpUtils.doHttp(request).use { if (!it.isSuccessful) { throw CustomException( - status = Response.Status.fromStatusCode(it.code()) ?: Response.Status.BAD_REQUEST, - message = "get merge info error for $repoName, $mrId(${it.code()}): ${it.message()}" + status = Response.Status.fromStatusCode(it.code) ?: Response.Status.BAD_REQUEST, + message = "get merge info error for $repoName, $mrId(${it.code}): ${it.message}" ) } - val data = it.body()!!.string() + val data = it.body!!.string() logger.info("get mr info response body: $data") return JsonUtil.to(data, GitMrInfo::class.java) } @@ -1090,11 +1090,11 @@ class GitService @Autowired constructor( OkhttpUtils.doHttp(request).use { if (!it.isSuccessful) { throw CustomException( - status = Response.Status.fromStatusCode(it.code()) ?: Response.Status.BAD_REQUEST, - message = "get merge reviewers info error for $id, $mrId(${it.code()}): ${it.message()}" + status = Response.Status.fromStatusCode(it.code) ?: Response.Status.BAD_REQUEST, + message = "get merge reviewers info error for $id, $mrId(${it.code}): ${it.message}" ) } - val data = it.body()!!.string() + val data = it.body!!.string() return JsonUtil.to(data, GitMrReviewInfo::class.java) } } @@ -1125,11 +1125,11 @@ class GitService @Autowired constructor( OkhttpUtils.doHttp(request).use { if (!it.isSuccessful) { throw CustomException( - status = Response.Status.fromStatusCode(it.code()) ?: Response.Status.BAD_REQUEST, - message = "get merge changes request info error for $id, $mrId(${it.code()}): ${it.message()}" + status = Response.Status.fromStatusCode(it.code) ?: Response.Status.BAD_REQUEST, + message = "get merge changes request info error for $id, $mrId(${it.code}): ${it.message}" ) } - val data = it.body()!!.string() + val data = it.body!!.string() return JsonUtil.to(data, GitMrChangeInfo::class.java) } } @@ -1183,11 +1183,11 @@ class GitService @Autowired constructor( OkhttpUtils.doHttp(request).use { if (!it.isSuccessful) { throw CustomException( - status = Response.Status.fromStatusCode(it.code()) ?: Response.Status.BAD_REQUEST, - message = "get repo members for $userId, $repoName fail(${it.code()}): ${it.message()}" + status = Response.Status.fromStatusCode(it.code) ?: Response.Status.BAD_REQUEST, + message = "get repo members for $userId, $repoName fail(${it.code}): ${it.message}" ) } - val data = it.body()!!.string() + val data = it.body!!.string() return JsonUtil.to(data) } } @@ -1230,11 +1230,11 @@ class GitService @Autowired constructor( OkhttpUtils.doHttp(request).use { if (!it.isSuccessful) { throw CustomException( - status = Response.Status.fromStatusCode(it.code()) ?: Response.Status.BAD_REQUEST, - message = "get repo all members for $userId, $repoName fail(${it.code()}): ${it.message()}" + status = Response.Status.fromStatusCode(it.code) ?: Response.Status.BAD_REQUEST, + message = "get repo all members for $userId, $repoName fail(${it.code}): ${it.message}" ) } - val data = it.body()!!.string() + val data = it.body!!.string() return JsonUtil.to(data) } } @@ -1256,7 +1256,7 @@ class GitService @Autowired constructor( .get() .build() OkhttpUtils.doHttp(request).use { - val data = it.body()!!.string() + val data = it.body!!.string() if (!it.isSuccessful) return MessageCodeUtil.generateResponseDataObject(CommonMessageCode.SYSTEM_ERROR) if (!StringUtils.isEmpty(data)) { val dataMap = JsonUtil.toMap(data) @@ -1303,11 +1303,11 @@ class GitService @Autowired constructor( OkhttpUtils.doHttp(request).use { if (!it.isSuccessful) { throw CustomException( - status = Response.Status.fromStatusCode(it.code()) ?: Response.Status.BAD_REQUEST, - message = "getProjectGroupInfo $id, $includeSubgroups(${it.code()}): ${it.message()}" + status = Response.Status.fromStatusCode(it.code) ?: Response.Status.BAD_REQUEST, + message = "getProjectGroupInfo $id, $includeSubgroups(${it.code}): ${it.message}" ) } - val data = it.body()!!.string() + val data = it.body!!.string() logger.info("getProjectGroupInfo response body: $data") return JsonUtil.to(data, GitProjectGroupInfo::class.java) } @@ -1332,13 +1332,13 @@ class GitService @Autowired constructor( .url(url.toString()) .post( RequestBody.create( - MediaType.parse("application/json;charset=utf-8"), + "application/json;charset=utf-8".toMediaTypeOrNull(), JsonUtil.toJson(params) ) ) .build() OkhttpUtils.doHttp(request).use { - val data = it.body()!!.string() + val data = it.body!!.string() logger.info("createGitTag response>> $data") val dataMap = JsonUtil.toMap(data) val message = dataMap["message"] @@ -1467,11 +1467,11 @@ class GitService @Autowired constructor( .get() .build() OkhttpUtils.doHttp(request).use { - val data = it.body()!!.string() + val data = it.body!!.string() if (!it.isSuccessful) { throw CustomException( - status = Response.Status.fromStatusCode(it.code()) ?: Response.Status.BAD_REQUEST, - message = "get repo member error for $gitProjectId(${it.code()}): ${it.message()}" + status = Response.Status.fromStatusCode(it.code) ?: Response.Status.BAD_REQUEST, + message = "get repo member error for $gitProjectId(${it.code}): ${it.message}" ) } return Result(JsonUtil.to(data, object : TypeReference>() {})) @@ -1498,7 +1498,7 @@ class GitService @Autowired constructor( .get() .build() OkhttpUtils.doHttp(request).use { response -> - val body = response.body()!!.string() + val body = response.body!!.string() logger.info("[$rtxUserId]|[$gitProjectId]| Get gitUserId response body: $body") val userInfo = JsonUtil.to(body, Map::class.java) return Result(userInfo["id"].toString()) @@ -1536,7 +1536,7 @@ class GitService @Autowired constructor( .get() .build() OkhttpUtils.doHttp(request).use { - val data = it.body()!!.string() + val data = it.body!!.string() if (!it.isSuccessful) throw RuntimeException("fail to getGitCIAllMembers with: $url($data)") return Result(JsonUtil.to(data, object : TypeReference>() {})) } @@ -1577,11 +1577,11 @@ class GitService @Autowired constructor( logger.info("[url=$url]|getFileInfo with response=$response") if (!response.isSuccessful) { throw CustomException( - status = Response.Status.fromStatusCode(response.code()) ?: Response.Status.BAD_REQUEST, - message = "(${response.code()})${response.message()}" + status = Response.Status.fromStatusCode(response.code) ?: Response.Status.BAD_REQUEST, + message = "(${response.code})${response.message}" ) } - val data = response.body()!!.string() + val data = response.body!!.string() val result = try { JsonUtil.to(data, GitCodeFileInfo::class.java) } catch (e: Throwable) { @@ -1669,11 +1669,11 @@ class GitService @Autowired constructor( OkhttpUtils.doHttp(request).use { if (!it.isSuccessful) { throw CustomException( - status = Response.Status.fromStatusCode(it.code()) ?: Response.Status.BAD_REQUEST, - message = "(${it.code()})${it.message()}" + status = Response.Status.fromStatusCode(it.code) ?: Response.Status.BAD_REQUEST, + message = "(${it.code})${it.message}" ) } - val data = it.body()!!.string() + val data = it.body!!.string() return Result(JsonUtil.getObjectMapper().readValue(data) as List) } } finally { @@ -1738,11 +1738,11 @@ class GitService @Autowired constructor( OkhttpUtils.doHttp(request).use { if (!it.isSuccessful) { throw CustomException( - status = Response.Status.fromStatusCode(it.code()) ?: Response.Status.BAD_REQUEST, - message = "(${it.code()})${it.message()}" + status = Response.Status.fromStatusCode(it.code) ?: Response.Status.BAD_REQUEST, + message = "(${it.code})${it.message}" ) } - val data = it.body()!!.string() + val data = it.body!!.string() return Result(JsonUtil.getObjectMapper().readValue(data) as List) } } finally { @@ -1769,15 +1769,15 @@ class GitService @Autowired constructor( .url(url.toString()) .put( RequestBody.create( - MediaType.parse("application/json;charset=utf-8"), "{}" + "application/json;charset=utf-8".toMediaTypeOrNull(), "{}" ) ) .build() OkhttpUtils.doHttp(request).use { if (!it.isSuccessful) { - return Result(it.code(), "enableCi fail ${it.message()}") + return Result(it.code, "enableCi fail ${it.message}") } - val data = it.body()!!.string() + val data = it.body!!.string() logger.info("enableCi response>> $data") val dataMap = JsonUtil.toMap(data) val code = dataMap["code"] @@ -1802,7 +1802,7 @@ class GitService @Autowired constructor( .url(url.toString()) .post( RequestBody.create( - MediaType.parse("application/json;charset=utf-8"), + "application/json;charset=utf-8".toMediaTypeOrNull(), JsonUtil.toJson(gitCreateFile) ) ) @@ -1845,7 +1845,7 @@ class GitService @Autowired constructor( .build() logger.info("getProjectList: $url") OkhttpUtils.doHttp(request).use { response -> - val data = response.body()?.string() ?: return@use + val data = response.body?.string() ?: return@use val repoList = JsonParser().parse(data).asJsonArray if (!repoList.isJsonNull) { return Result(JsonUtil.to(data, object : TypeReference>() {})) diff --git a/src/backend/ci/core/repository/biz-repository/src/main/kotlin/com/tencent/devops/repository/utils/scm/GitCodeUtils.kt b/src/backend/ci/core/repository/biz-repository/src/main/kotlin/com/tencent/devops/repository/utils/scm/GitCodeUtils.kt index 96dc5170ad3..3e4b7e0a317 100644 --- a/src/backend/ci/core/repository/biz-repository/src/main/kotlin/com/tencent/devops/repository/utils/scm/GitCodeUtils.kt +++ b/src/backend/ci/core/repository/biz-repository/src/main/kotlin/com/tencent/devops/repository/utils/scm/GitCodeUtils.kt @@ -42,14 +42,14 @@ object GitCodeUtils { fun handleErrorMessage( response: Response ): CustomException { - val data = response.body()?.string() ?: return CustomException( - status = HttpResp.Status.fromStatusCode(response.code()) ?: HttpResp.Status.BAD_REQUEST, - message = response.message() + val data = response.body?.string() ?: return CustomException( + status = HttpResp.Status.fromStatusCode(response.code) ?: HttpResp.Status.BAD_REQUEST, + message = response.message ) val resp = JsonUtil.getObjectMapper().readValue(data) as GitCodeErrorResp return CustomException( - status = HttpResp.Status.fromStatusCode(response.code()) ?: HttpResp.Status.BAD_REQUEST, - message = resp.message ?: response.message() + status = HttpResp.Status.fromStatusCode(response.code) ?: HttpResp.Status.BAD_REQUEST, + message = resp.message ?: response.message ) } } diff --git a/src/backend/ci/core/store/biz-store/src/main/kotlin/com/tencent/devops/store/utils/AtomReleaseTxtAnalysisUtil.kt b/src/backend/ci/core/store/biz-store/src/main/kotlin/com/tencent/devops/store/utils/AtomReleaseTxtAnalysisUtil.kt index ceea37ed092..2721cd455be 100644 --- a/src/backend/ci/core/store/biz-store/src/main/kotlin/com/tencent/devops/store/utils/AtomReleaseTxtAnalysisUtil.kt +++ b/src/backend/ci/core/store/biz-store/src/main/kotlin/com/tencent/devops/store/utils/AtomReleaseTxtAnalysisUtil.kt @@ -207,7 +207,7 @@ object AtomReleaseTxtAnalysisUtil { "?userId=$userId&projectCode=$projectCode&atomId=$atomId&atomCode=$atomCode" + "&version=$version&releaseType=$releaseType&os=$os" OkhttpUtils.uploadFile(serviceUrl, file).use { response -> - response.body()!!.string() + response.body!!.string() if (!response.isSuccessful) { return MessageCodeUtil.generateResponseDataObject(CommonMessageCode.SYSTEM_ERROR) } diff --git a/src/backend/ci/core/stream/biz-stream/src/main/kotlin/com/tencent/devops/stream/service/StreamLogService.kt b/src/backend/ci/core/stream/biz-stream/src/main/kotlin/com/tencent/devops/stream/service/StreamLogService.kt index c53121b9e98..c70b8a91e08 100644 --- a/src/backend/ci/core/stream/biz-stream/src/main/kotlin/com/tencent/devops/stream/service/StreamLogService.kt +++ b/src/backend/ci/core/stream/biz-stream/src/main/kotlin/com/tencent/devops/stream/service/StreamLogService.kt @@ -136,7 +136,7 @@ class StreamLogService @Autowired constructor( val response = OkhttpUtils.doLongGet(path.toString(), headers) return Response - .ok(response.body()!!.byteStream(), MediaType.APPLICATION_OCTET_STREAM_TYPE) + .ok(response.body!!.byteStream(), MediaType.APPLICATION_OCTET_STREAM_TYPE) .header("content-disposition", "attachment; filename = ${pipeline.pipelineId}-$buildId-log.txt") .header("Cache-Control", "no-cache") .header("X-DEVOPS-PROJECT-ID", "gitciproject") diff --git a/src/backend/ci/core/stream/biz-stream/src/main/kotlin/com/tencent/devops/stream/service/StreamPipelineBadgeService.kt b/src/backend/ci/core/stream/biz-stream/src/main/kotlin/com/tencent/devops/stream/service/StreamPipelineBadgeService.kt index fa02831e8df..c7aaeb9d026 100644 --- a/src/backend/ci/core/stream/biz-stream/src/main/kotlin/com/tencent/devops/stream/service/StreamPipelineBadgeService.kt +++ b/src/backend/ci/core/stream/biz-stream/src/main/kotlin/com/tencent/devops/stream/service/StreamPipelineBadgeService.kt @@ -58,9 +58,9 @@ class StreamPipelineBadgeService @Autowired constructor( val url = "$badgeServerUrl?label=$pipelineName&message=${type.text}&status=${type.name}&logo=${type.logo}" OkhttpUtils.doGet(url).use { resp -> if (!resp.isSuccessful) throw RuntimeException( - "get badge error code: ${resp.code()} message: ${resp.message()}" + "get badge error code: ${resp.code} message: ${resp.message}" ) - return resp.body()!!.string() + return resp.body!!.string() } } diff --git a/src/backend/ci/core/worker/worker-agent/src/main/kotlin/com/tencent/devops/agent/Application.kt b/src/backend/ci/core/worker/worker-agent/src/main/kotlin/com/tencent/devops/agent/Application.kt index ba09ff4bcd1..d5ef53240e7 100644 --- a/src/backend/ci/core/worker/worker-agent/src/main/kotlin/com/tencent/devops/agent/Application.kt +++ b/src/backend/ci/core/worker/worker-agent/src/main/kotlin/com/tencent/devops/agent/Application.kt @@ -142,7 +142,7 @@ private fun waitBuildLessJobStart() { private fun doResponse( resp: Response ): Boolean { - val responseBody = resp.body()?.string() ?: "" + val responseBody = resp.body?.string() ?: "" println("${LocalDateTime.now()} Get buildLessTask response: $responseBody") return if (resp.isSuccessful && responseBody.isNotBlank()) { val buildLessTask: Map = jacksonObjectMapper().readValue(responseBody) @@ -156,7 +156,7 @@ private fun doResponse( } true } else { - println("${LocalDateTime.now()} No buildLessTask, resp: ${resp.body()} continue loop...") + println("${LocalDateTime.now()} No buildLessTask, resp: ${resp.body} continue loop...") false } } diff --git a/src/backend/ci/core/worker/worker-api-sdk/src/main/kotlin/com/tencent/devops/worker/common/api/archive/BkRepoArchiveResourceApi.kt b/src/backend/ci/core/worker/worker-api-sdk/src/main/kotlin/com/tencent/devops/worker/common/api/archive/BkRepoArchiveResourceApi.kt index ded59656223..e25c835a156 100644 --- a/src/backend/ci/core/worker/worker-api-sdk/src/main/kotlin/com/tencent/devops/worker/common/api/archive/BkRepoArchiveResourceApi.kt +++ b/src/backend/ci/core/worker/worker-api-sdk/src/main/kotlin/com/tencent/devops/worker/common/api/archive/BkRepoArchiveResourceApi.kt @@ -41,7 +41,7 @@ import com.tencent.devops.worker.common.api.AbstractBuildResourceApi import com.tencent.devops.worker.common.api.ApiPriority import com.tencent.devops.worker.common.logger.LoggerService import com.tencent.devops.worker.common.utils.TaskUtil -import okhttp3.MediaType +import okhttp3.MediaType.Companion.toMediaTypeOrNull import okhttp3.MultipartBody import okhttp3.RequestBody import java.io.File @@ -102,7 +102,7 @@ class BkRepoArchiveResourceApi : AbstractBuildResourceApi(), ArchiveSDKApi { val url = "/bkrepo/api/build/generic/${buildVariables.projectId}/custom/$bkRepoPath" val request = buildPut( url, - RequestBody.create(MediaType.parse("application/octet-stream"), file), + RequestBody.create("application/octet-stream".toMediaTypeOrNull(), file), bkrepoResourceApi.getUploadHeader(file, buildVariables, true), useFileDevnetGateway = TaskUtil.isVmBuildEnv(buildVariables.containerType) ) @@ -162,7 +162,7 @@ class BkRepoArchiveResourceApi : AbstractBuildResourceApi(), ArchiveSDKApi { "${buildVariables.buildId}/${file.name}" val request = buildPut( url, - RequestBody.create(MediaType.parse("application/octet-stream"), file), + RequestBody.create("application/octet-stream".toMediaTypeOrNull(), file), bkrepoResourceApi.getUploadHeader(file, buildVariables, true), useFileDevnetGateway = TaskUtil.isVmBuildEnv(buildVariables.containerType) ) diff --git a/src/backend/ci/core/worker/worker-api-sdk/src/main/kotlin/com/tencent/devops/worker/common/api/archive/BkRepoResourceApi.kt b/src/backend/ci/core/worker/worker-api-sdk/src/main/kotlin/com/tencent/devops/worker/common/api/archive/BkRepoResourceApi.kt index fbb79364b53..3aec6deab4b 100644 --- a/src/backend/ci/core/worker/worker-api-sdk/src/main/kotlin/com/tencent/devops/worker/common/api/archive/BkRepoResourceApi.kt +++ b/src/backend/ci/core/worker/worker-api-sdk/src/main/kotlin/com/tencent/devops/worker/common/api/archive/BkRepoResourceApi.kt @@ -59,7 +59,7 @@ import com.tencent.devops.worker.common.api.archive.pojo.TokenType import com.tencent.devops.worker.common.utils.IosUtils import com.tencent.devops.worker.common.utils.TaskUtil import net.dongliu.apk.parser.ApkFile -import okhttp3.MediaType +import okhttp3.MediaType.Companion.toMediaTypeOrNull import okhttp3.RequestBody import org.apache.commons.lang3.StringUtils import org.slf4j.LoggerFactory @@ -119,16 +119,16 @@ class BkRepoResourceApi : AbstractBuildResourceApi() { val request = buildPost( path = url, requestBody = RequestBody.create( - MediaType.parse("application/json; charset=utf-8"), + "application/json; charset=utf-8".toMediaTypeOrNull(), objectMapper.writeValueAsString(requestData) ), headers = mapOf(BKREPO_UID to userId) ) OkhttpUtils.doHttp(request).use { response -> - val responseContent = response.body()!!.string() + val responseContent = response.body!!.string() if (!response.isSuccessful) { - logger.error("http request failed, code: ${response.code()}, responseContent: $responseContent") - throw RemoteServiceException("http request failed: $responseContent", response.code()) + logger.error("http request failed, code: ${response.code}, responseContent: $responseContent") + throw RemoteServiceException("http request failed: $responseContent", response.code) } val responseData = objectMapper.readValue>>(responseContent) @@ -153,7 +153,7 @@ class BkRepoResourceApi : AbstractBuildResourceApi() { val url = "/generic/temporary/upload/$projectId/$repoName/${urlEncode(destFullPath)}?token=$token" val request = buildPut( url, - RequestBody.create(MediaType.parse("application/octet-stream"), file), + RequestBody.create("application/octet-stream".toMediaTypeOrNull(), file), getUploadHeader(file, buildVariables, parseAppMetadata), useFileDevnetGateway = TaskUtil.isVmBuildEnv(buildVariables.containerType) ) @@ -261,7 +261,7 @@ class BkRepoResourceApi : AbstractBuildResourceApi() { val url = "/bkrepo/api/build/generic/$projectId/$repoName/${urlEncode(destFullPath)}" val request = buildPut( path = url, - requestBody = RequestBody.create(MediaType.parse("application/octet-stream"), file), + requestBody = RequestBody.create("application/octet-stream".toMediaTypeOrNull(), file), headers = getUploadHeader(file, buildVariables, parseAppMetadata), useFileDevnetGateway = true ) @@ -366,7 +366,7 @@ class BkRepoResourceApi : AbstractBuildResourceApi() { val pipelineNameRequest = buildPost( "/bkrepo/api/build/repository/api/metadata/$projectId/$repoName/$pipelineId", RequestBody.create( - MediaType.parse("application/json; charset=utf-8"), + "application/json; charset=utf-8".toMediaTypeOrNull(), JsonUtil.toJson(mapOf("metadata" to mapOf(METADATA_DISPLAY_NAME to pipelineName))) ), headers @@ -377,7 +377,7 @@ class BkRepoResourceApi : AbstractBuildResourceApi() { val buildNumRequest = buildPost( "/bkrepo/api/build/repository/api/metadata/$projectId/$repoName/$pipelineId/$buildId", RequestBody.create( - MediaType.parse("application/json; charset=utf-8"), + "application/json; charset=utf-8".toMediaTypeOrNull(), JsonUtil.toJson(mapOf("metadata" to mapOf(METADATA_DISPLAY_NAME to buildNum))) ), headers @@ -445,16 +445,16 @@ class BkRepoResourceApi : AbstractBuildResourceApi() { val request = buildPost( url, RequestBody.create( - MediaType.parse("application/json; charset=utf-8"), + "application/json; charset=utf-8".toMediaTypeOrNull(), requestBody ), mutableMapOf("X-BKREPO-UID" to userId) ) OkhttpUtils.doHttp(request).use { response -> - val responseContent = response.body()!!.string() + val responseContent = response.body!!.string() if (!response.isSuccessful) { logger.error("query failed, responseContent: $responseContent") - throw RemoteServiceException("query failed: $responseContent", response.code()) + throw RemoteServiceException("query failed: $responseContent", response.code) } val responseData = objectMapper.readValue>(responseContent) diff --git a/src/backend/ci/core/worker/worker-api-sdk/src/main/kotlin/com/tencent/devops/worker/common/api/atom/AtomArchiveResourceApi.kt b/src/backend/ci/core/worker/worker-api-sdk/src/main/kotlin/com/tencent/devops/worker/common/api/atom/AtomArchiveResourceApi.kt index e580ff6c535..b95cba483fc 100644 --- a/src/backend/ci/core/worker/worker-api-sdk/src/main/kotlin/com/tencent/devops/worker/common/api/atom/AtomArchiveResourceApi.kt +++ b/src/backend/ci/core/worker/worker-api-sdk/src/main/kotlin/com/tencent/devops/worker/common/api/atom/AtomArchiveResourceApi.kt @@ -53,7 +53,7 @@ import com.tencent.devops.worker.common.api.archive.ARCHIVE_PROPS_SOURCE import com.tencent.devops.worker.common.api.archive.ARCHIVE_PROPS_USER_ID import com.tencent.devops.worker.common.api.archive.ArtifactoryBuildResourceApi import com.tencent.devops.worker.common.logger.LoggerService -import okhttp3.MediaType +import okhttp3.MediaType.Companion.toMediaTypeOrNull import okhttp3.MultipartBody import okhttp3.RequestBody import java.io.File @@ -100,7 +100,7 @@ class AtomArchiveResourceApi : AbstractBuildResourceApi(), AtomArchiveSDKApi { ): Result { val path = "/ms/store/api/build/market/atom/env/$projectCode/$atomCode/$atomVersion" val body = RequestBody.create( - MediaType.parse("application/json; charset=utf-8"), + "application/json; charset=utf-8".toMediaTypeOrNull(), objectMapper.writeValueAsString(atomEnvRequest) ) val request = buildPut(path, body) @@ -160,7 +160,7 @@ class AtomArchiveResourceApi : AbstractBuildResourceApi(), AtomArchiveSDKApi { url.append(";$ARCHIVE_PROPS_SOURCE=pipeline") } - val request = buildPut(url.toString(), RequestBody.create(MediaType.parse("application/octet-stream"), file)) + val request = buildPut(url.toString(), RequestBody.create("application/octet-stream".toMediaTypeOrNull(), file)) val responseContent = request(request, "归档插件文件失败") try { val obj = JsonParser().parse(responseContent).asJsonObject @@ -248,7 +248,7 @@ class AtomArchiveResourceApi : AbstractBuildResourceApi(), AtomArchiveSDKApi { ): Result { val path = "/ms/store/api/build/store/docking/platforms/types/ATOM/codes/$atomCode/add" val body = RequestBody.create( - MediaType.parse("application/json; charset=utf-8"), + "application/json; charset=utf-8".toMediaTypeOrNull(), objectMapper.writeValueAsString(platformCodes) ) val request = buildPost(path, body) diff --git a/src/backend/ci/core/worker/worker-api-sdk/src/main/kotlin/com/tencent/devops/worker/common/api/dispatch/CodeccDownloadResourceApi.kt b/src/backend/ci/core/worker/worker-api-sdk/src/main/kotlin/com/tencent/devops/worker/common/api/dispatch/CodeccDownloadResourceApi.kt index 6157d686f88..69d826f05b0 100644 --- a/src/backend/ci/core/worker/worker-api-sdk/src/main/kotlin/com/tencent/devops/worker/common/api/dispatch/CodeccDownloadResourceApi.kt +++ b/src/backend/ci/core/worker/worker-api-sdk/src/main/kotlin/com/tencent/devops/worker/common/api/dispatch/CodeccDownloadResourceApi.kt @@ -43,7 +43,7 @@ class CodeccDownloadResourceApi : AbstractBuildResourceApi(), CodeccDownloadApi val request = buildGet(path) val response = requestForResponse(request) - if (response.code() == HttpStatus.NOT_MODIFIED.value) { + if (response.code == HttpStatus.NOT_MODIFIED.value) { return Response.Builder().request(request) .protocol(Protocol.HTTP_1_1) .message("") @@ -63,7 +63,7 @@ class CodeccDownloadResourceApi : AbstractBuildResourceApi(), CodeccDownloadApi val path = "/dispatch/api/build/codecc/coverity/script?osType=${osType.name}&fileMd5=$fileMd5" val request = buildGet(path) val response = requestForResponse(request) - if (response.code() == HttpStatus.NOT_MODIFIED.value) { + if (response.code == HttpStatus.NOT_MODIFIED.value) { return Response.Builder().request(request) .protocol(Protocol.HTTP_1_1) .message("") @@ -83,7 +83,7 @@ class CodeccDownloadResourceApi : AbstractBuildResourceApi(), CodeccDownloadApi val path = "/dispatch/api/build/codecc/tools/script?osType=${osType.name}&fileMd5=$fileMd5" val request = buildGet(path) val response = requestForResponse(request) - if (response.code() == HttpStatus.NOT_MODIFIED.value) { + if (response.code == HttpStatus.NOT_MODIFIED.value) { return Response.Builder().request(request) .protocol(Protocol.HTTP_1_1) .message("") diff --git a/src/backend/ci/core/worker/worker-api-sdk/src/main/kotlin/com/tencent/devops/worker/common/api/docker/DockerResourceApi.kt b/src/backend/ci/core/worker/worker-api-sdk/src/main/kotlin/com/tencent/devops/worker/common/api/docker/DockerResourceApi.kt index 3664032e9bb..d8fe9280668 100644 --- a/src/backend/ci/core/worker/worker-api-sdk/src/main/kotlin/com/tencent/devops/worker/common/api/docker/DockerResourceApi.kt +++ b/src/backend/ci/core/worker/worker-api-sdk/src/main/kotlin/com/tencent/devops/worker/common/api/docker/DockerResourceApi.kt @@ -32,7 +32,7 @@ import com.tencent.devops.common.api.auth.AUTH_HEADER_USER_ID import com.tencent.devops.common.api.pojo.Result import com.tencent.devops.store.pojo.image.request.ImageBaseInfoUpdateRequest import com.tencent.devops.worker.common.api.AbstractBuildResourceApi -import okhttp3.MediaType +import okhttp3.MediaType.Companion.toMediaTypeOrNull import okhttp3.RequestBody class DockerResourceApi : AbstractBuildResourceApi(), DockerSDKApi { @@ -49,7 +49,7 @@ class DockerResourceApi : AbstractBuildResourceApi(), DockerSDKApi { ): Result { val path = "/ms/store/api/build/market/image/projectCodes/$projectCode/imageCodes/$imageCode/versions/$version" val body = RequestBody.create( - MediaType.parse("application/json; charset=utf-8"), + "application/json; charset=utf-8".toMediaTypeOrNull(), objectMapper.writeValueAsString(imageBaseInfoUpdateRequest) ) val headMap = mapOf(AUTH_HEADER_USER_ID to userId) diff --git a/src/backend/ci/core/worker/worker-api-sdk/src/main/kotlin/com/tencent/devops/worker/common/api/log/LogResourceApi.kt b/src/backend/ci/core/worker/worker-api-sdk/src/main/kotlin/com/tencent/devops/worker/common/api/log/LogResourceApi.kt index 4a3cc25db2a..b3fc01fe69e 100644 --- a/src/backend/ci/core/worker/worker-api-sdk/src/main/kotlin/com/tencent/devops/worker/common/api/log/LogResourceApi.kt +++ b/src/backend/ci/core/worker/worker-api-sdk/src/main/kotlin/com/tencent/devops/worker/common/api/log/LogResourceApi.kt @@ -33,16 +33,15 @@ import com.tencent.devops.common.log.pojo.TaskBuildLogProperty import com.tencent.devops.common.log.pojo.enums.LogStorageMode import com.tencent.devops.common.log.pojo.message.LogMessage import com.tencent.devops.worker.common.api.AbstractBuildResourceApi -import okhttp3.MediaType +import okhttp3.MediaType.Companion.toMediaTypeOrNull import okhttp3.RequestBody -import java.lang.StringBuilder class LogResourceApi : AbstractBuildResourceApi(), LogSDKApi { override fun addLogMultiLine(buildId: String, logMessages: List): Result { val path = "/log/api/build/logs/multi?buildId=$buildId" val requestBody = RequestBody.create( - MediaType.parse("application/json; charset=utf-8"), + "application/json; charset=utf-8".toMediaTypeOrNull(), objectMapper.writeValueAsString(logMessages) ) val request = buildPost(path, requestBody) @@ -69,7 +68,7 @@ class LogResourceApi : AbstractBuildResourceApi(), LogSDKApi { if (!jobId.isNullOrBlank()) path.append("&jobId=$jobId") if (executeCount != null) path.append("&executeCount=$executeCount") if (logMode != null) path.append("&logMode=${logMode.name}") - val requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), "") + val requestBody = RequestBody.create("application/json; charset=utf-8".toMediaTypeOrNull(), "") val request = buildPut(path.toString(), requestBody) val responseContent = request(request, "上报结束状态失败") return objectMapper.readValue(responseContent) @@ -82,7 +81,7 @@ class LogResourceApi : AbstractBuildResourceApi(), LogSDKApi { val path = StringBuilder("/log/api/build/logs/mode") path.append("?executeCount=$executeCount") val requestBody = RequestBody.create( - MediaType.parse("application/json; charset=utf-8"), + "application/json; charset=utf-8".toMediaTypeOrNull(), objectMapper.writeValueAsString(propertyList) ) val request = buildPost(path.toString(), requestBody) diff --git a/src/backend/ci/core/worker/worker-api-sdk/src/main/kotlin/com/tencent/devops/worker/common/api/process/BuildResourceApi.kt b/src/backend/ci/core/worker/worker-api-sdk/src/main/kotlin/com/tencent/devops/worker/common/api/process/BuildResourceApi.kt index 557f771e9bd..c98aca193f2 100644 --- a/src/backend/ci/core/worker/worker-api-sdk/src/main/kotlin/com/tencent/devops/worker/common/api/process/BuildResourceApi.kt +++ b/src/backend/ci/core/worker/worker-api-sdk/src/main/kotlin/com/tencent/devops/worker/common/api/process/BuildResourceApi.kt @@ -37,7 +37,7 @@ import com.tencent.devops.process.pojo.BuildTemplateAcrossInfo import com.tencent.devops.process.pojo.BuildVariables import com.tencent.devops.process.pojo.pipeline.ModelDetail import com.tencent.devops.worker.common.api.AbstractBuildResourceApi -import okhttp3.MediaType +import okhttp3.MediaType.Companion.toMediaTypeOrNull import okhttp3.RequestBody class BuildResourceApi : AbstractBuildResourceApi(), BuildSDKApi { @@ -73,7 +73,7 @@ class BuildResourceApi : AbstractBuildResourceApi(), BuildSDKApi { override fun completeTask(result: BuildTaskResult): Result { val path = "/ms/process/api/build/builds/complete" val requestBody = RequestBody.create( - MediaType.parse("application/json; charset=utf-8"), + "application/json; charset=utf-8".toMediaTypeOrNull(), objectMapper.writeValueAsString(result) ) val request = buildPost(path, requestBody) diff --git a/src/backend/ci/core/worker/worker-api-sdk/src/main/kotlin/com/tencent/devops/worker/common/api/quality/QualityGatewayResourceApi.kt b/src/backend/ci/core/worker/worker-api-sdk/src/main/kotlin/com/tencent/devops/worker/common/api/quality/QualityGatewayResourceApi.kt index 9aced85bda2..e0f448bbbba 100644 --- a/src/backend/ci/core/worker/worker-api-sdk/src/main/kotlin/com/tencent/devops/worker/common/api/quality/QualityGatewayResourceApi.kt +++ b/src/backend/ci/core/worker/worker-api-sdk/src/main/kotlin/com/tencent/devops/worker/common/api/quality/QualityGatewayResourceApi.kt @@ -30,7 +30,7 @@ package com.tencent.devops.worker.common.api.quality import com.tencent.devops.common.api.pojo.Result import com.tencent.devops.worker.common.api.AbstractBuildResourceApi import com.tencent.devops.worker.common.logger.LoggerService -import okhttp3.MediaType +import okhttp3.MediaType.Companion.toMediaTypeOrNull import okhttp3.RequestBody import org.slf4j.LoggerFactory @@ -48,8 +48,10 @@ class QualityGatewayResourceApi : QualityGatewaySDKApi, AbstractBuildResourceApi try { val path = "/ms/quality/api/build/metadata/saveHisMetadata?" + "elementType=$elementType&taskId=$taskId&taskName=$taskName" - val requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), - objectMapper.writeValueAsString(data)) + val requestBody = RequestBody.create( + "application/json; charset=utf-8".toMediaTypeOrNull(), + objectMapper.writeValueAsString(data) + ) val request = buildPost(path, requestBody) val responseContent = request(request, "保存脚本元数据失败") return Result(responseContent) diff --git a/src/backend/ci/core/worker/worker-api-sdk/src/main/kotlin/com/tencent/devops/worker/common/api/report/BkRepoReportResourceApi.kt b/src/backend/ci/core/worker/worker-api-sdk/src/main/kotlin/com/tencent/devops/worker/common/api/report/BkRepoReportResourceApi.kt index d09685c1464..d65b991f94b 100644 --- a/src/backend/ci/core/worker/worker-api-sdk/src/main/kotlin/com/tencent/devops/worker/common/api/report/BkRepoReportResourceApi.kt +++ b/src/backend/ci/core/worker/worker-api-sdk/src/main/kotlin/com/tencent/devops/worker/common/api/report/BkRepoReportResourceApi.kt @@ -39,7 +39,7 @@ import com.tencent.devops.worker.common.api.archive.BkRepoResourceApi import com.tencent.devops.worker.common.logger.LoggerService import com.tencent.devops.worker.common.logger.LoggerService.elementId import com.tencent.devops.worker.common.utils.TaskUtil -import okhttp3.MediaType +import okhttp3.MediaType.Companion.toMediaTypeOrNull import okhttp3.RequestBody import java.io.File @@ -72,8 +72,10 @@ class BkRepoReportResourceApi : AbstractBuildResourceApi(), ReportSDKApi { val request = if (reportEmail == null) { buildPost(path) } else { - val requestBody = RequestBody.create(MediaType.parse( - "application/json; charset=utf-8"), objectMapper.writeValueAsString(reportEmail)) + val requestBody = RequestBody.create( + "application/json; charset=utf-8".toMediaTypeOrNull(), + objectMapper.writeValueAsString(reportEmail) + ) buildPost(path, requestBody) } val responseContent = request(request, "创建报告失败") @@ -109,7 +111,7 @@ class BkRepoReportResourceApi : AbstractBuildResourceApi(), ReportSDKApi { val request = buildPut( path = url, - requestBody = RequestBody.create(MediaType.parse("application/octet-stream"), file), + requestBody = RequestBody.create("application/octet-stream".toMediaTypeOrNull(), file), headers = bkrepoResourceApi.getUploadHeader(file, buildVariables, parseAppMetadata = false), useFileDevnetGateway = TaskUtil.isVmBuildEnv(buildVariables.containerType) ) diff --git a/src/backend/ci/core/worker/worker-api-sdk/src/main/kotlin/com/tencent/devops/worker/common/api/report/ReportResourceApi.kt b/src/backend/ci/core/worker/worker-api-sdk/src/main/kotlin/com/tencent/devops/worker/common/api/report/ReportResourceApi.kt index f2dccdcf582..63ff1352a7a 100644 --- a/src/backend/ci/core/worker/worker-api-sdk/src/main/kotlin/com/tencent/devops/worker/common/api/report/ReportResourceApi.kt +++ b/src/backend/ci/core/worker/worker-api-sdk/src/main/kotlin/com/tencent/devops/worker/common/api/report/ReportResourceApi.kt @@ -38,7 +38,7 @@ import com.tencent.devops.process.pojo.report.ReportEmail import com.tencent.devops.worker.common.api.AbstractBuildResourceApi import com.tencent.devops.worker.common.logger.LoggerService import com.tencent.devops.worker.common.utils.TaskUtil -import okhttp3.MediaType +import okhttp3.MediaType.Companion.toMediaTypeOrNull import okhttp3.MultipartBody import okhttp3.RequestBody import org.slf4j.LoggerFactory @@ -110,7 +110,7 @@ class ReportResourceApi : AbstractBuildResourceApi(), ReportSDKApi { buildPost(path) } else { val requestBody = RequestBody.create( - MediaType.parse("application/json; charset=utf-8"), + "application/json; charset=utf-8".toMediaTypeOrNull(), objectMapper.writeValueAsString(reportEmail) ) buildPost(path, requestBody) diff --git a/src/backend/ci/core/worker/worker-common/src/main/kotlin/com/tencent/devops/plugin/worker/task/archive/BuildPushDockerImageTask.kt b/src/backend/ci/core/worker/worker-common/src/main/kotlin/com/tencent/devops/plugin/worker/task/archive/BuildPushDockerImageTask.kt index 417b5ab7f47..248f1bacf69 100644 --- a/src/backend/ci/core/worker/worker-common/src/main/kotlin/com/tencent/devops/plugin/worker/task/archive/BuildPushDockerImageTask.kt +++ b/src/backend/ci/core/worker/worker-common/src/main/kotlin/com/tencent/devops/plugin/worker/task/archive/BuildPushDockerImageTask.kt @@ -46,7 +46,7 @@ import com.tencent.devops.worker.common.logger.LoggerService import com.tencent.devops.worker.common.task.ITask import com.tencent.devops.worker.common.task.TaskClassType import com.tencent.devops.worker.common.task.script.CommandFactory -import okhttp3.MediaType +import okhttp3.MediaType.Companion.toMediaTypeOrNull import okhttp3.Request import okhttp3.RequestBody import org.slf4j.LoggerFactory @@ -186,7 +186,7 @@ class BuildPushDockerImageTask : ITask() { .get() .build() OkhttpUtils.doHttp(request).use { response -> - val responseBody = response.body()!!.string() + val responseBody = response.body!!.string() logger.info("responseBody: $responseBody") if (!response.isSuccessful) { LoggerService.addErrorLine("启动构建镜像失败!请联系【蓝盾助手】") @@ -241,10 +241,10 @@ class BuildPushDockerImageTask : ITask() { logger.info("request body: $requestBody") val request = Request.Builder().url(url) - .post(RequestBody.create(MediaType.parse("application/json; charset=utf-8"), requestBody)) + .post(RequestBody.create("application/json; charset=utf-8".toMediaTypeOrNull(), requestBody)) .build() OkhttpUtils.doHttp(request).use { response -> - val responseBody = response.body()!!.string() + val responseBody = response.body!!.string() logger.info("responseBody: $responseBody") if (!response.isSuccessful) { logger.error("failed to get start docker build") diff --git a/src/backend/ci/core/worker/worker-common/src/main/kotlin/com/tencent/devops/plugin/worker/task/image/MarketCheckImageTask.kt b/src/backend/ci/core/worker/worker-common/src/main/kotlin/com/tencent/devops/plugin/worker/task/image/MarketCheckImageTask.kt index a809045c309..87002279d25 100644 --- a/src/backend/ci/core/worker/worker-common/src/main/kotlin/com/tencent/devops/plugin/worker/task/image/MarketCheckImageTask.kt +++ b/src/backend/ci/core/worker/worker-common/src/main/kotlin/com/tencent/devops/plugin/worker/task/image/MarketCheckImageTask.kt @@ -28,27 +28,27 @@ package com.tencent.devops.plugin.worker.task.image import com.fasterxml.jackson.core.type.TypeReference +import com.tencent.devops.common.api.exception.TaskExecuteException +import com.tencent.devops.common.api.pojo.ErrorCode +import com.tencent.devops.common.api.pojo.ErrorType import com.tencent.devops.common.api.pojo.Result import com.tencent.devops.common.api.util.JsonUtil import com.tencent.devops.common.api.util.OkhttpUtils import com.tencent.devops.common.pipeline.pojo.element.market.MarketCheckImageElement import com.tencent.devops.dockerhost.pojo.CheckImageRequest import com.tencent.devops.dockerhost.pojo.CheckImageResponse -import com.tencent.devops.common.api.pojo.ErrorCode +import com.tencent.devops.dockerhost.utils.ENV_DOCKER_HOST_IP +import com.tencent.devops.dockerhost.utils.ENV_DOCKER_HOST_PORT import com.tencent.devops.process.pojo.BuildTask import com.tencent.devops.process.pojo.BuildVariables -import com.tencent.devops.common.api.pojo.ErrorType import com.tencent.devops.process.utils.PIPELINE_START_USER_ID import com.tencent.devops.store.pojo.image.request.ImageBaseInfoUpdateRequest import com.tencent.devops.worker.common.api.ApiFactory import com.tencent.devops.worker.common.api.docker.DockerSDKApi -import com.tencent.devops.common.api.exception.TaskExecuteException -import com.tencent.devops.dockerhost.utils.ENV_DOCKER_HOST_IP -import com.tencent.devops.dockerhost.utils.ENV_DOCKER_HOST_PORT import com.tencent.devops.worker.common.logger.LoggerService import com.tencent.devops.worker.common.task.ITask import com.tencent.devops.worker.common.task.TaskClassType -import okhttp3.MediaType +import okhttp3.MediaType.Companion.toMediaTypeOrNull import okhttp3.Request import okhttp3.RequestBody import org.slf4j.LoggerFactory @@ -75,9 +75,9 @@ class MarketCheckImageTask : ITask() { val dockerHostIp = System.getenv(ENV_DOCKER_HOST_IP) val dockerHostPort = System.getenv(ENV_DOCKER_HOST_PORT) val path = "/api/docker/build/image/buildIds/${buildTask.buildId}/" + - "check?containerId=${buildVariables.containerId}&containerHashId=${buildVariables.containerHashId}" + "check?containerId=${buildVariables.containerId}&containerHashId=${buildVariables.containerHashId}" val body = RequestBody.create( - MediaType.parse("application/json; charset=utf-8"), + "application/json; charset=utf-8".toMediaTypeOrNull(), JsonUtil.toJson(checkImageRequest) ) val url = "http://$dockerHostIp:$dockerHostPort$path" @@ -86,13 +86,15 @@ class MarketCheckImageTask : ITask() { .post(body) .build() val response = OkhttpUtils.doLongHttp(request) - val responseContent = response.body()?.string() + val responseContent = response.body?.string() if (!response.isSuccessful) { - logger.warn("Fail to request($request) with code ${response.code()} ," + - " message ${response.message()} and response ($responseContent)") - LoggerService.addErrorLine(response.message()) + logger.warn( + "Fail to request($request) with code ${response.code} ," + + " message ${response.message} and response ($responseContent)" + ) + LoggerService.addErrorLine(response.message) throw TaskExecuteException( - errorMsg = "checkImage fail: message ${response.message()} and response ($responseContent)", + errorMsg = "checkImage fail: message ${response.message} and response ($responseContent)", errorCode = ErrorCode.USER_TASK_OPERATE_FAIL, errorType = ErrorType.USER ) diff --git a/src/backend/ci/core/worker/worker-common/src/main/kotlin/com/tencent/devops/worker/common/api/AbstractBuildResourceApi.kt b/src/backend/ci/core/worker/worker-common/src/main/kotlin/com/tencent/devops/worker/common/api/AbstractBuildResourceApi.kt index 92b6140b32e..6f5498a775f 100644 --- a/src/backend/ci/core/worker/worker-common/src/main/kotlin/com/tencent/devops/worker/common/api/AbstractBuildResourceApi.kt +++ b/src/backend/ci/core/worker/worker-common/src/main/kotlin/com/tencent/devops/worker/common/api/AbstractBuildResourceApi.kt @@ -46,8 +46,8 @@ import com.tencent.devops.worker.common.env.BuildEnv import com.tencent.devops.worker.common.env.BuildType import com.tencent.devops.worker.common.logger.LoggerService import com.tencent.devops.worker.common.utils.ArchiveUtils -import okhttp3.Headers -import okhttp3.MediaType +import okhttp3.Headers.Companion.toHeaders +import okhttp3.MediaType.Companion.toMediaTypeOrNull import okhttp3.OkHttpClient import okhttp3.Request import okhttp3.RequestBody @@ -92,9 +92,9 @@ abstract class AbstractBuildResourceApi : WorkerRestApiSDK { val httpClient = builder.build() val retryFlag = try { val response = httpClient.newCall(request).execute() - logger.info("Request($request) with code ${response.code()}") + logger.info("Request($request) with code ${response.code}") - if (retryCodes.contains(response.code())) { // 网关502,503,可重试 + if (retryCodes.contains(response.code)) { // 网关502,503,可重试 true } else { ErrorMsgLogUtil.resetErrorMsg() // #5806 成功时将异常信息清理掉 @@ -118,7 +118,7 @@ abstract class AbstractBuildResourceApi : WorkerRestApiSDK { } } catch (re: SocketTimeoutException) { if (re.message == "connect timed out" || - (request.method() == "GET" && re.message == "timeout") + (request.method == "GET" && re.message == "timeout") ) { logger.warn("SocketTimeoutException(${re.message})|request($request), try to retry $retryCount") if (retryCount <= 0) { @@ -165,14 +165,14 @@ abstract class AbstractBuildResourceApi : WorkerRestApiSDK { writeTimeoutInSec = writeTimeoutInSec ).use { response -> if (!response.isSuccessful) { - val responseContent = response.body()?.string() + val responseContent = response.body?.string() logger.warn( - "Fail to request($request) with code ${response.code()} ," + - " message ${response.message()} and response ($responseContent)" + "Fail to request($request) with code ${response.code} ," + + " message ${response.message} and response ($responseContent)" ) - throw RemoteServiceException(errorMessage, response.code(), responseContent) + throw RemoteServiceException(errorMessage, response.code, responseContent) } - return response.body()!!.string() + return response.body!!.string() } } @@ -191,21 +191,23 @@ abstract class AbstractBuildResourceApi : WorkerRestApiSDK { readTimeoutInSec = readTimeoutInSec, writeTimeoutInSec = writeTimeoutInSec ).use { response -> - if (response.code() == HTTP_404) { + if (response.code == HTTP_404) { throw RemoteServiceException("file does not exist") } if (!response.isSuccessful) { - LoggerService.addNormalLine(response.body()!!.string()) + LoggerService.addNormalLine(response.body!!.string()) throw RemoteServiceException("Failed to get file") } val dest = destPath.toPath() if (Files.notExists(dest.parent)) Files.createDirectories(dest.parent) LoggerService.addNormalLine("${LOG_DEBUG_FLAG}save file >>>> ${destPath.canonicalPath}") - val body = response.body() ?: return + val body = response.body ?: return val contentLength = body.contentLength() if (contentLength != -1L) { - LoggerService.addNormalLine("download ${dest.fileName} " + - ArchiveUtils.humanReadableByteCountBin(contentLength)) + LoggerService.addNormalLine( + "download ${dest.fileName} " + + ArchiveUtils.humanReadableByteCountBin(contentLength) + ) } // body copy时可能会出现readTimeout,即便http请求已正常响应 @@ -232,9 +234,9 @@ abstract class AbstractBuildResourceApi : WorkerRestApiSDK { } companion object { - val JsonMediaType = MediaType.parse("application/json; charset=utf-8") - val OctetMediaType = MediaType.parse("application/octet-stream") - val MultipartFormData = MediaType.parse("multipart/form-data") + val JsonMediaType = "application/json; charset=utf-8".toMediaTypeOrNull() + val OctetMediaType = "application/octet-stream".toMediaTypeOrNull() + val MultipartFormData = "multipart/form-data".toMediaTypeOrNull() private const val EMPTY = "" private const val DEFAULT_RETRY_TIME = 5 private const val sleepTimeMills = 500L @@ -263,11 +265,13 @@ abstract class AbstractBuildResourceApi : WorkerRestApiSDK { map[AUTH_HEADER_DEVOPS_AGENT_ID] = AgentEnv.getAgentId() // map[AUTH_HEADER_AGENT_SECRET_KEY] = AgentEnv.getAgentSecretKey() } + BuildType.DOCKER -> { map[AUTH_HEADER_DEVOPS_PROJECT_ID] = AgentEnv.getProjectId() map[AUTH_HEADER_DEVOPS_AGENT_ID] = AgentEnv.getAgentId() map[AUTH_HEADER_DEVOPS_AGENT_SECRET_KEY] = AgentEnv.getAgentSecretKey() } + else -> Unit } logger.info("Get the request header - $map") @@ -313,7 +317,7 @@ abstract class AbstractBuildResourceApi : WorkerRestApiSDK { useFileDevnetGateway: Boolean? = null ): Request { val url = buildUrl(path, useFileDevnetGateway) - return Request.Builder().url(url).headers(Headers.of(getAllHeaders(headers))).get().build() + return Request.Builder().url(url).headers(getAllHeaders(headers).toHeaders()).get().build() } fun buildPost( @@ -332,7 +336,7 @@ abstract class AbstractBuildResourceApi : WorkerRestApiSDK { useFileDevnetGateway: Boolean? = null ): Request { val url = buildUrl(path, useFileDevnetGateway) - return Request.Builder().url(url).headers(Headers.of(getAllHeaders(headers))).post(requestBody).build() + return Request.Builder().url(url).headers(getAllHeaders(headers).toHeaders()).post(requestBody).build() } fun buildPut( @@ -351,13 +355,13 @@ abstract class AbstractBuildResourceApi : WorkerRestApiSDK { useFileDevnetGateway: Boolean? = null ): Request { val url = buildUrl(path, useFileDevnetGateway) - return Request.Builder().url(url).headers(Headers.of(getAllHeaders(headers))).put(requestBody).build() + return Request.Builder().url(url).headers(getAllHeaders(headers).toHeaders()).put(requestBody).build() } @Suppress("UNUSED") fun buildDelete(path: String, headers: Map = emptyMap()): Request { val url = buildUrl(path) - return Request.Builder().url(url).headers(Headers.of(getAllHeaders(headers))).delete().build() + return Request.Builder().url(url).headers(getAllHeaders(headers).toHeaders()).delete().build() } fun getJsonRequest(data: Any): RequestBody { diff --git a/src/backend/ci/core/worker/worker-common/src/main/kotlin/com/tencent/devops/worker/common/api/engine/impl/EngineBuildResourceApi.kt b/src/backend/ci/core/worker/worker-common/src/main/kotlin/com/tencent/devops/worker/common/api/engine/impl/EngineBuildResourceApi.kt index 093b8a0ca87..f726c4658a8 100644 --- a/src/backend/ci/core/worker/worker-common/src/main/kotlin/com/tencent/devops/worker/common/api/engine/impl/EngineBuildResourceApi.kt +++ b/src/backend/ci/core/worker/worker-common/src/main/kotlin/com/tencent/devops/worker/common/api/engine/impl/EngineBuildResourceApi.kt @@ -37,7 +37,7 @@ import com.tencent.devops.process.pojo.BuildVariables import com.tencent.devops.worker.common.api.AbstractBuildResourceApi import com.tencent.devops.worker.common.api.ApiPriority import com.tencent.devops.worker.common.api.engine.EngineBuildSDKApi -import okhttp3.MediaType +import okhttp3.MediaType.Companion.toMediaTypeOrNull import okhttp3.RequestBody @Suppress("UNUSED", "TooManyFunctions") @@ -83,7 +83,7 @@ open class EngineBuildResourceApi : AbstractBuildResourceApi(), EngineBuildSDKAp override fun completeTask(result: BuildTaskResult, retryCount: Int): Result { val path = getRequestUrl(path = "api/build/worker/complete", retryCount = retryCount) val requestBody = RequestBody.create( - MediaType.parse("application/json; charset=utf-8"), + "application/json; charset=utf-8".toMediaTypeOrNull(), objectMapper.writeValueAsString(result) ) val request = buildPost(path, requestBody) @@ -147,7 +147,7 @@ open class EngineBuildResourceApi : AbstractBuildResourceApi(), EngineBuildSDKAp override fun submitError(errorInfo: ErrorInfo): Result { val path = getRequestUrl(path = "api/build/worker/submit_error") val requestBody = RequestBody.create( - MediaType.parse("application/json; charset=utf-8"), + "application/json; charset=utf-8".toMediaTypeOrNull(), objectMapper.writeValueAsString(errorInfo) ) val request = buildPost(path, requestBody)