Commit 75d05a68 authored by 毛梦良's avatar 毛梦良

Merge branch 'mml-dev-v6.0' into 'dev-v6.0'

提交

See merge request PaaS/devops!4
parents 78e423f3 d008d355
......@@ -7,3 +7,4 @@ EnableDocs = true
sqlconn =
nameSpace = paas
configPath = /etc/kubeconfig/config
defaultCredentialName = k2admin
\ No newline at end of file
......@@ -5,6 +5,7 @@ import (
"devops/dto"
"devops/utils"
"encoding/json"
"errors"
"github.com/astaxie/beego"
"io/ioutil"
"net/http"
......@@ -25,24 +26,15 @@ func (c *CredentialController) URLMapping() {
// @Title getAllCredentials
// @Description get AllCredentials
// @Param lang query string true "api result language type"
// @Param body body dto.GetPageListBaseRequestDto true ""
// @Success 200 {object} dto.GetPageListBaseResponseDto
// @Success 200 {object} dto.BaseResultResponseDto
// @Failure 300 {object} dto.BaseResponseDto
// @router /getAllCredentials [post]
func (c *CredentialController) GetAllCredentials() {
lang := c.GetString("lang")
infoLogger.Println("语言: ", lang)
var requestDto dto.GetPageListBaseRequestDto
var errorResponseDto = dto.BaseResponseDto{300, utils.GetI18nLang(lang, "sysError")}
var successResponseDto = dto.GetPageListBaseResponseDto{}
if err := json.Unmarshal(c.Ctx.Input.RequestBody, &requestDto); err != nil {
errorLogger.Println(err)
errorResponseDto.Message = utils.GetI18nLang(lang, "requestParamIncorrectFormat")
c.Data["json"] = errorResponseDto
c.ServeJSON()
return
}
infoLogger.Println("清理本地镜像请求参数: ", requestDto)
var successResponseDto = dto.BaseResultResponseDto{}
successResponseDto.Status = 200
// 生成ApiToken
//apiToken := generateApiToken()
......@@ -50,38 +42,45 @@ func (c *CredentialController) GetAllCredentials() {
//infoLogger.Printf("调用生成ApiToken接口返回值:%s", apiToken)
const BaseURL = "http://jenkins.poc.paas.com"
const BaseUrl = "http://jenkins.poc.paas.com"
httpClient := &http.Client{
Transport: &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
},
Timeout: 10 * time.Second,
CheckRedirect: func(req *http.Request, via []*http.Request) error {
return http.ErrUseLastResponse
},
}
getAllJobUrl := BaseURL + "/blue/rest/organizations/jenkins/pipelines/"
req, _ := http.NewRequest("GET", getAllJobUrl, nil)
req.SetBasicAuth("admin", "K2pass!")
getAllJobUrl := BaseUrl + "/blue/rest/organizations/jenkins/pipelines/"
getAllJobReq, _ := http.NewRequest("GET", getAllJobUrl, nil)
getAllJobRes, err := httpClient.Do(req)
getAllJobRes, err := httpClient.Do(getAllJobReq)
if err != nil {
errorLogger.Println(err)
errorLogger.Println("调用获取所有job接口失败:", err.Error())
errorResponseDto.Message = "获取所有job失败"
c.Data["json"] = errorResponseDto
c.ServeJSON()
return
}
getAllJobResByte, err := ioutil.ReadAll(getAllJobRes.Body)
if err != nil {
errorLogger.Printf("解析调用登录接口返回参数失败:%s", err.Error())
//errorResponseDto.Message = utils.GetI18nLang(lang,
// "getUserAllNameSpaces_parseCallInterfaceToGetUserAllNameSpacesResultFail")
//c.Data["json"] = errorResponseDto
//c.ServeJSON()
//return
errorLogger.Printf("解析调用获取所有job接口返回参数失败:%s", err.Error())
errorResponseDto.Message = "解析调用获取所有job接口返回参数失败"
c.Data["json"] = errorResponseDto
c.ServeJSON()
return
}
//infoLogger.Printf("调用登录接口返回值:%s", string(reqByte))
var resMap []map[string]interface{}
if err := json.Unmarshal(getAllJobResByte, &resMap); err != nil {
errorLogger.Println("解析获取所有job接口返回数据失败:", err.Error())
errorResponseDto.Message = "解析获取所有job接口返回数据失败"
c.Data["json"] = errorResponseDto
c.ServeJSON()
return
}
allJobCount := len(resMap)
......@@ -102,50 +101,25 @@ func (c *CredentialController) GetAllCredentials() {
}
infoLogger.Println("job name:", jobName)
getAllCredentialsParams := "url=&credentialsId="
getAllCredentialsUrl := BaseURL + "/job/" + jobName +
"/descriptorByName/hudson.plugins.git.UserRemoteConfig/fillCredentialsIdItems?" + getAllCredentialsParams
getAllCredentialsReq, _ := http.NewRequest("POST", getAllCredentialsUrl, nil)
req.SetBasicAuth("admin", "K2pass!")
req.Header.Set("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8")
getAllCredentialsRes, err := httpClient.Do(getAllCredentialsReq)
if err != nil {
errorLogger.Println(err)
}
infoLogger.Println(getAllCredentialsRes)
getAllCredentialsResByte, err := ioutil.ReadAll(getAllCredentialsRes.Body)
// 获取所有凭据
allCredentials, err := GetCredentials(jobName)
if err != nil {
errorLogger.Printf("解析调用获取所有凭据接口返回参数失败:%s", err.Error())
//errorResponseDto.Message = utils.GetI18nLang(lang,
// "getUserAllNameSpaces_parseCallInterfaceToGetUserAllNameSpacesResultFail")
//c.Data["json"] = errorResponseDto
//c.ServeJSON()
//return
errorLogger.Println("调用获取所有凭据接口失败:", err.Error())
errorResponseDto.Message = "获取所有凭据接口失败"
c.Data["json"] = errorResponseDto
c.ServeJSON()
return
}
//infoLogger.Printf("调用登录接口返回值:%s", string(reqByte))
var getAllCredentialsResMap map[string]interface{}
if err := json.Unmarshal(getAllCredentialsResByte, &getAllCredentialsResMap); err != nil {
errorLogger.Println("解析获取获取所有凭据接口返回数据失败:", err.Error())
if len(allCredentials) > 0 {
successResponseDto.Result = allCredentials
c.Data["json"] = successResponseDto
c.ServeJSON()
return
}
allCredentialsName := []string{}
allCredentials := getAllCredentialsResMap["values"].([]interface{})
if len(allCredentials) > 1 {
allCredentials = allCredentials[1:]
for _, c := range allCredentials {
credential := c.(map[string]interface{})
name := credential["name"].(string)
infoLogger.Println("credential name:", name)
allCredentialsName = append(allCredentialsName, name)
}
} else {
//执行创建凭据
defaultCredentialName := beego.AppConfig.String("defaultCredentialName")
//执行创建凭据 默认名称k2admin 密码K2pass!!
createCredentialsParams := "_.scope=GLOBAL&_.username=k2admin&_.password=K2pass%21%21&_.id=&_.description=" +
"&stapler-class=com.cloudbees.plugins.credentials.impl.UsernamePasswordCredentialsImpl&%24class=" +
"com.cloudbees.plugins.credentials.impl.UsernamePasswordCredentialsImpl&stapler-class=" +
......@@ -165,30 +139,131 @@ func (c *CredentialController) GetAllCredentials() {
"org.jenkinsci.plugins.plaincredentials.impl.StringCredentialsImpl&stapler-class=" +
"com.cloudbees.plugins.credentials.impl.CertificateCredentialsImpl&%24class=" +
"com.cloudbees.plugins.credentials.impl.CertificateCredentialsImpl&json=" +
"%7B%22%22%3A+%220%22%2C+%22credentials%22%3A+%7B%22scope%22%3A+%22GLOBAL%22%2C+%22username%22%3A+%22k2admin%22%2C+%22password%22%3A+%22K2pass%21%21%22%2C+%22%24redact%22%3A+%22password%22%2C+%22id%22%3A+%22%22%2C+%22description%22%3A+%22%22%2C+%22stapler-class%22%3A+%22com.cloudbees.plugins.credentials.impl.UsernamePasswordCredentialsImpl%22%2C+%22%24class%22%3A+%22com.cloudbees.plugins.credentials.impl.UsernamePasswordCredentialsImpl%22%7D%7D&Submit=%E7%A1%AE%E5%AE%9A"
getAllCredentialsUrl := BaseURL + "/credentials/store/system/domain/_/createCredentials?" + createCredentialsParams
"%7B%22%22%3A+%220%22%2C+%22credentials%22%3A+%7B%22scope%22%3A+%22GLOBAL%22%2C+%22username%22%3A+%22" +
defaultCredentialName + "%22%2C+%22password%22%3A+%22K2pass%21%21%22%2C+%22%24redact%22%3A+%22password%22%2C+" +
"%22id%22%3A+%22%22%2C+%22description%22%3A+%22%22%2C+%22stapler-class%22%3A+%22" +
"com.cloudbees.plugins.credentials.impl.UsernamePasswordCredentialsImpl%22%2C+%22%24class%22%3A+%22" +
"com.cloudbees.plugins.credentials.impl.UsernamePasswordCredentialsImpl%22%7D%7D&Submit=%E7%A1%AE%E5%AE%9A"
getAllCredentialsUrl := BaseUrl + "/credentials/store/system/domain/_/createCredentials?" + createCredentialsParams
getAllCredentialsReq, _ := http.NewRequest("POST", getAllCredentialsUrl, nil)
req.SetBasicAuth("admin", "K2pass!")
req.Header.Set("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8")
getAllCredentialsReq.Header.Set("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8")
getAllCredentialsRes, err := httpClient.Do(getAllCredentialsReq)
if err != nil {
errorLogger.Println(err)
errorLogger.Printf("执行创建默认凭据:%s失败:%s", defaultCredentialName, err.Error())
errorResponseDto.Message = "执行创建默认凭据失败"
c.Data["json"] = errorResponseDto
c.ServeJSON()
return
}
infoLogger.Println(getAllCredentialsRes)
infoLogger.Printf("执行创建默认凭据:%s返回状态码:%s", defaultCredentialName, getAllCredentialsRes.Status)
if getAllCredentialsRes.StatusCode != http.StatusFound {
errorResponseDto.Message = "执行创建默认凭据失败"
c.Data["json"] = errorResponseDto
c.ServeJSON()
return
}
infoLogger.Printf("执行创建默认凭据%s成功", defaultCredentialName)
//successResponseDto.Result = result
//successResponseDto.PageInfo = dto.PageInfoBaseResponseDto{
// TotalRecords: totalRecords,
// TotalPages: totalPages,
//if jobName == "temp-job"{
// deleteUrl := BaseUrl + "/job/" + jobName + "/doDelete"
// req, _ := http.NewRequest("POST", deleteUrl, nil)
// req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
//
// deleteRes, err := httpClient.Do(req)
// if err != nil {
// errorLogger.Printf("执行删除临时job:%s失败:%s", jobName, err.Error())
// errorResponseDto.Message = "执行删除临时job失败"
// c.Data["json"] = errorResponseDto
// c.ServeJSON()
// return
// }
// infoLogger.Printf("执行删除临时job:%s返回状态码:%s", jobName, deleteRes.Status)
// if deleteRes.StatusCode != http.StatusFound {
// errorResponseDto.Message = "执行删除临时job失败"
// c.Data["json"] = errorResponseDto
// c.ServeJSON()
// return
// }
// infoLogger.Printf("执行删除job:%s成功", jobName)
//}
// 获取所有凭据
allCredentials, err = GetCredentials(jobName)
if err != nil {
errorLogger.Println("调用获取所有凭据接口失败:", err.Error())
errorResponseDto.Message = "获取所有凭据接口失败"
c.Data["json"] = errorResponseDto
c.ServeJSON()
return
}
successResponseDto.Result = allCredentials
c.Data["json"] = successResponseDto
c.ServeJSON()
}
func CreateCredential() {
// 获取所有凭据
func GetCredentials(jobName string) ([]dto.GetAllCredentialsResultResponseDto, error) {
result := []dto.GetAllCredentialsResultResponseDto{}
const BaseURL = "http://jenkins.poc.paas.com"
httpClient := &http.Client{
Transport: &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
},
Timeout: 10 * time.Second,
CheckRedirect: func(req *http.Request, via []*http.Request) error {
return http.ErrUseLastResponse
},
}
getAllCredentialsParams := "url=&credentialsId="
getAllCredentialsUrl := BaseURL + "/job/" + jobName +
"/descriptorByName/hudson.plugins.git.UserRemoteConfig/fillCredentialsIdItems?" + getAllCredentialsParams
getAllCredentialsReq, _ := http.NewRequest("POST", getAllCredentialsUrl, nil)
getAllCredentialsReq.Header.Set("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8")
getAllCredentialsRes, err := httpClient.Do(getAllCredentialsReq)
if err != nil {
errorLogger.Println("调用获取所有凭据接口失败:", err.Error())
return result, errors.New("调用获取所有凭据接口失败")
}
getAllCredentialsResByte, err := ioutil.ReadAll(getAllCredentialsRes.Body)
if err != nil {
errorLogger.Printf("解析调用获取所有凭据接口返回参数失败:%s", err.Error())
return result, errors.New("解析调用获取所有凭据接口返回参数失败")
}
var getAllCredentialsResMap map[string]interface{}
if err := json.Unmarshal(getAllCredentialsResByte, &getAllCredentialsResMap); err != nil {
errorLogger.Println("解析获取获取所有凭据接口返回数据失败:", err.Error())
return result, errors.New("解析调用获取所有凭据接口返回参数失败")
}
allCredentials := getAllCredentialsResMap["values"].([]interface{})
if len(allCredentials) > 1 {
allCredentials = allCredentials[1:]
for _, c := range allCredentials {
credential := c.(map[string]interface{})
name := credential["name"].(string)
infoLogger.Println("credential name:", name)
value := credential["value"].(string)
infoLogger.Println("credential value:", value)
result = append(result, dto.GetAllCredentialsResultResponseDto{
name,
value,
})
}
}
return result, nil
}
......@@ -82,32 +82,31 @@ func (c *JobController) GetJobList() {
getAllJobUrl := BaseURL + "/blue/rest/organizations/jenkins/pipelines/"
req, _ := http.NewRequest("GET", getAllJobUrl, nil)
req.SetBasicAuth("admin", "K2pass!")
getAllJobRes, err := httpClient.Do(req)
if err != nil {
errorLogger.Println(err)
//if loginRes.StatusCode == http.StatusFound{
// infoLogger.Println(loginRes.Location())
//}
errorLogger.Println("调用获取所有job接口失败:", err.Error())
errorResponseDto.Message = "获取所有job失败"
c.Data["json"] = errorResponseDto
c.ServeJSON()
return
}
infoLogger.Println(getAllJobRes)
getAllJobResByte, err := ioutil.ReadAll(getAllJobRes.Body)
if err != nil {
errorLogger.Printf("解析调用登录接口返回参数失败:%s", err.Error())
//errorResponseDto.Message = utils.GetI18nLang(lang,
// "getUserAllNameSpaces_parseCallInterfaceToGetUserAllNameSpacesResultFail")
//c.Data["json"] = errorResponseDto
//c.ServeJSON()
//return
errorLogger.Printf("解析调用获取所有job接口返回参数失败:%s", err.Error())
errorResponseDto.Message = "解析调用获取所有job接口返回参数失败"
c.Data["json"] = errorResponseDto
c.ServeJSON()
return
}
//infoLogger.Printf("调用登录接口返回值:%s", string(reqByte))
var resMap []map[string]interface{}
if err := json.Unmarshal(getAllJobResByte, &resMap); err != nil {
errorLogger.Println("解析获取所有job接口返回数据失败:", err.Error())
errorResponseDto.Message = "解析获取所有job接口返回数据失败"
c.Data["json"] = errorResponseDto
c.ServeJSON()
return
}
totalRecords := len(resMap)
......@@ -170,13 +169,10 @@ func (c *JobController) GetJobList() {
infoLogger.Println("job lastBuildUserName:", lastBuildUserName)
endTime := latestRunMap["endTime"].(string)
infoLogger.Println("job endTime:", endTime)
endTimeStr = utils.ParseDate(endTime, false)
infoLogger.Println("job endTime:", endTime, " ", endTimeStr)
durationInMillis := int64(latestRunMap["durationInMillis"].(float64))
durationInMillisTimeStr, _ = utils.ParseMilliSecondsDateToString(lang, durationInMillis)
infoLogger.Println("job durationInMillis:", durationInMillis, " ", durationInMillisTimeStr)
}
......@@ -644,14 +640,14 @@ func (c *JobController) CreatePipelineJob() {
//执行创建job
execCreatePipelineJobRes := ExecCreatePipelineJob(requestDto.JobName)
if execCreatePipelineJobRes.Status == 300 {
errorLogger.Printf("执行创建%s job失败:%s", jobName, execCreatePipelineJobRes.Message)
errorLogger.Printf("执行创建job:%s失败:%s", jobName, execCreatePipelineJobRes.Message)
responseDto.Message = execCreatePipelineJobRes.Message
c.Data["json"] = responseDto
c.ServeJSON()
return
}
infoLogger.Printf("执行配置%s job", jobName)
infoLogger.Printf("执行配置job:%s", jobName)
//执行配置job
......@@ -696,17 +692,16 @@ func ExecCreatePipelineJob(jobName string) dto.BaseResponseDto {
url.QueryEscape(string(paramsByte))
infoLogger.Println(paramsStr)
req, _ := http.NewRequest("POST", createUrl+"?"+paramsStr, nil)
req.SetBasicAuth("admin", "K2pass!")
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
createRes, err := httpClient.Do(req)
if err != nil {
errorLogger.Printf("执行创建%s job失败:%s", jobName, err.Error())
errorLogger.Printf("执行创建job:%s失败:%s", jobName, err.Error())
responseDto.Message = "执行创建job失败"
return responseDto
}
infoLogger.Printf("执行创建%s job返回结果:%v", jobName, createRes)
infoLogger.Printf("执行创建job:%s返回结果:%v", jobName, createRes)
errorRes := createRes.Header.Get("X-Error")
infoLogger.Printf("返回错误信息:%s", errorRes)
if errorRes != "" && strings.Contains(errorRes, "A job already exists with the name "+jobName) {
......@@ -717,7 +712,7 @@ func ExecCreatePipelineJob(jobName string) dto.BaseResponseDto {
responseDto.Message = "执行创建job失败"
return responseDto
}
infoLogger.Printf("执行创建%s job成功", jobName)
infoLogger.Printf("执行创建job:%s成功", jobName)
responseDto.Status = 200
responseDto.Message = "成功"
......@@ -744,7 +739,7 @@ func (c *JobController) StartRunPipelineJob() {
c.ServeJSON()
return
}
infoLogger.Println("启动构建job请求参数: ", requestDto)
infoLogger.Println("启动运行job请求参数: ", requestDto)
jobName := requestDto.JobName
if strings.TrimSpace(jobName) == "" {
errorLogger.Println("job名称不能为空")
......@@ -765,22 +760,21 @@ func (c *JobController) StartRunPipelineJob() {
}
req, _ := http.NewRequest("POST", buildUrl, nil)
req.SetBasicAuth("admin", "K2pass!")
req.Header.Set("Content-Type", "application/json;charset=utf-8")
startRes, err := httpClient.Do(req)
if err != nil {
errorLogger.Println(err)
errorLogger.Printf("启动构建%s job失败:%s", jobName, err.Error())
responseDto.Message = "启动构建job失败"
errorLogger.Printf("启动运行job:%s失败:%s", jobName, err.Error())
responseDto.Message = "启动运行job失败"
c.Data["json"] = responseDto
c.ServeJSON()
return
}
infoLogger.Printf("启动构建%sjob 返回状态码:%s", jobName, startRes.Status)
infoLogger.Printf("启动运行job:%s返回状态码:%s", jobName, startRes.Status)
if startRes.StatusCode != http.StatusFound {
responseDto.Message = "启动构建job失败"
responseDto.Message = "启动运行job失败"
if startRes.StatusCode == http.StatusNotFound {
responseDto.Message = "job不存在"
}
......@@ -788,7 +782,7 @@ func (c *JobController) StartRunPipelineJob() {
c.ServeJSON()
return
}
infoLogger.Printf("启动构建%s job成功", jobName)
infoLogger.Printf("启动运行job:%s成功", jobName)
responseDto.Status = 200
responseDto.Message = "成功"
......@@ -840,19 +834,17 @@ func (c *JobController) DeletePipelineJob() {
}
req, _ := http.NewRequest("POST", buildUrl, nil)
req.SetBasicAuth("admin", "K2pass!")
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
deleteRes, err := httpClient.Do(req)
if err != nil {
errorLogger.Println(err)
errorLogger.Printf("执行删除%s job失败:%s", jobName, err.Error())
errorLogger.Printf("执行删除job:%s失败:%s", jobName, err.Error())
responseDto.Message = "执行删除job失败"
c.Data["json"] = responseDto
c.ServeJSON()
return
}
infoLogger.Printf("执行删除%s job返回状态码:%s", jobName, deleteRes.Status)
infoLogger.Printf("执行删除job:%s返回状态码:%s", jobName, deleteRes.Status)
if deleteRes.StatusCode != http.StatusFound {
responseDto.Message = "执行删除job失败"
if deleteRes.StatusCode == http.StatusNotFound {
......@@ -862,7 +854,7 @@ func (c *JobController) DeletePipelineJob() {
c.ServeJSON()
return
}
infoLogger.Printf("执行删除%s job成功", jobName)
infoLogger.Printf("执行删除job:%s成功", jobName)
responseDto.Status = 200
responseDto.Message = "成功"
......
package dto
type GetCredentialsResponseDto struct {
JobName string `json:"jobName"` //job 名称
LastStatus string `json:"lastStatus"` //最近状态
LastBuildUserName string `json:"lastBuildUserName"` //最近构建人名称
Description string `json:"description"` //描述信息
LastUpdateTime string `json:"lastUpdateTime"` //最近更新时间即最近job结束时间
DurationInMillis string `json:"durationInMillis"` //上次持续时间
type GetAllCredentialsResultResponseDto struct {
CredentialId string `json:"credentialId"` //凭据id
CredentialName string `json:"credentialName"` //凭据名称
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment