Merge pull request #1666 from goodrain/dind-perf

merge: dind-perf into main
This commit is contained in:
yangkaa 2023-06-06 23:07:57 +08:00 committed by GitHub
commit 2f45c815ec
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
23 changed files with 613 additions and 262 deletions

View File

@ -48,7 +48,7 @@ import (
"github.com/sirupsen/logrus"
)
//V2Routes v2Routes
// V2Routes v2Routes
type V2Routes struct {
ClusterController
NodesController
@ -66,7 +66,7 @@ type V2Routes struct {
HelmStruct
}
//Show test
// Show test
func (v2 *V2Routes) Show(w http.ResponseWriter, r *http.Request) {
// swagger:operation GET /v2/show v2 getApiVersion
//
@ -86,12 +86,12 @@ func (v2 *V2Routes) Show(w http.ResponseWriter, r *http.Request) {
w.Write([]byte(cmd.GetVersion()))
}
//Health show health status
// Health show health status
func (v2 *V2Routes) Health(w http.ResponseWriter, r *http.Request) {
httputil.ReturnSuccess(r, w, map[string]string{"status": "health", "info": "api service health"})
}
//AlertManagerWebHook -
// AlertManagerWebHook -
func (v2 *V2Routes) AlertManagerWebHook(w http.ResponseWriter, r *http.Request) {
fmt.Println("=======>webhook")
in, err := ioutil.ReadAll(r.Body)
@ -106,18 +106,18 @@ func (v2 *V2Routes) AlertManagerWebHook(w http.ResponseWriter, r *http.Request)
}
//Version -
// Version -
func (v2 *V2Routes) Version(w http.ResponseWriter, r *http.Request) {
httputil.ReturnSuccess(r, w, map[string]string{"version": os.Getenv("RELEASE_DESC")})
}
//TenantStruct tenant struct
// TenantStruct tenant struct
type TenantStruct struct {
StatusCli *client.AppRuntimeSyncClient
MQClient mqclient.MQClient
}
//AllTenantResources GetResources
// AllTenantResources GetResources
func (t *TenantStruct) AllTenantResources(w http.ResponseWriter, r *http.Request) {
tenants, err := handler.GetTenantManager().GetTenants("")
if err != nil {
@ -142,7 +142,7 @@ func (t *TenantStruct) AllTenantResources(w http.ResponseWriter, r *http.Request
httputil.ReturnSuccess(r, w, ts.Data)
}
//TenantResources TenantResources
// TenantResources TenantResources
func (t *TenantStruct) TenantResources(w http.ResponseWriter, r *http.Request) {
// swagger:operation POST /v2/resources/tenants v2 tenantResources
//
@ -181,7 +181,7 @@ func (t *TenantStruct) TenantResources(w http.ResponseWriter, r *http.Request) {
return
}
//ServiceResources ServiceResources
// ServiceResources ServiceResources
func (t *TenantStruct) ServiceResources(w http.ResponseWriter, r *http.Request) {
// swagger:operation POST /v2/resources/services v2 serviceResources
//
@ -213,7 +213,7 @@ func (t *TenantStruct) ServiceResources(w http.ResponseWriter, r *http.Request)
return
}
//TenantsQuery TenantsQuery
// TenantsQuery TenantsQuery
func (t *TenantStruct) TenantsQuery(w http.ResponseWriter, r *http.Request) {
// swagger:operation GET /v2/tenants/query/{tenant_name} v2 tenants
//
@ -253,7 +253,7 @@ func (t *TenantStruct) TenantsQuery(w http.ResponseWriter, r *http.Request) {
return
}
//TenantsGetByName TenantsGetByName
// TenantsGetByName TenantsGetByName
func (t *TenantStruct) TenantsGetByName(w http.ResponseWriter, r *http.Request) {
// swagger:operation GET /v2/tenants/{tenant_name}/res v2 tenants
//
@ -302,7 +302,7 @@ func (t *TenantStruct) TenantsGetByName(w http.ResponseWriter, r *http.Request)
return
}
//TenantsWithResource TenantsWithResource
// TenantsWithResource TenantsWithResource
func (t *TenantStruct) TenantsWithResource(w http.ResponseWriter, r *http.Request) {
// swagger:operation GET /v2/resources/tenants/res/page/{curPage}/size/{pageLen} v2 PagedTenantResList
//
@ -360,7 +360,7 @@ func (t *TenantStruct) TenantsWithResource(w http.ResponseWriter, r *http.Reques
return
}
//SumTenants 统计租户数量
// SumTenants 统计租户数量
func (t *TenantStruct) SumTenants(w http.ResponseWriter, r *http.Request) {
// swagger:operation GET /v2/resources/tenants/sum v2 sumTenants
//
@ -389,7 +389,7 @@ func (t *TenantStruct) SumTenants(w http.ResponseWriter, r *http.Request) {
httputil.ReturnSuccess(r, w, rc)
}
//Tenant one tenant controller
// Tenant one tenant controller
func (t *TenantStruct) Tenant(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case "GET":
@ -401,7 +401,7 @@ func (t *TenantStruct) Tenant(w http.ResponseWriter, r *http.Request) {
}
}
//Tenants Tenant
// Tenants Tenant
func (t *TenantStruct) Tenants(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case "POST":
@ -411,7 +411,7 @@ func (t *TenantStruct) Tenants(w http.ResponseWriter, r *http.Request) {
}
}
//AddTenant AddTenant
// AddTenant AddTenant
func (t *TenantStruct) AddTenant(w http.ResponseWriter, r *http.Request) {
// swagger:operation POST /v2/tenants v2 addTenant
//
@ -508,7 +508,7 @@ func (t *TenantStruct) AddTenant(w http.ResponseWriter, r *http.Request) {
return
}
//GetTenants GetTenants
// GetTenants GetTenants
func (t *TenantStruct) GetTenants(w http.ResponseWriter, r *http.Request) {
// swagger:operation GET /v2/tenants v2 getTenants
//
@ -560,7 +560,7 @@ func (t *TenantStruct) GetTenants(w http.ResponseWriter, r *http.Request) {
httputil.ReturnSuccess(r, w, re)
}
//DeleteTenant DeleteTenant
// DeleteTenant DeleteTenant
func (t *TenantStruct) DeleteTenant(w http.ResponseWriter, r *http.Request) {
tenantID := r.Context().Value(ctxutil.ContextKey("tenant_id")).(string)
@ -581,8 +581,8 @@ func (t *TenantStruct) DeleteTenant(w http.ResponseWriter, r *http.Request) {
httputil.ReturnSuccess(r, w, nil)
}
//UpdateTenant UpdateTenant
//support update tenant limit memory
// UpdateTenant UpdateTenant
// support update tenant limit memory
func (t *TenantStruct) UpdateTenant(w http.ResponseWriter, r *http.Request) {
var ts api_model.UpdateTenantStruct
ok := httputil.ValidatorRequestStructAndErrorResponse(r, w, &ts.Body, nil)
@ -598,14 +598,14 @@ func (t *TenantStruct) UpdateTenant(w http.ResponseWriter, r *http.Request) {
httputil.ReturnSuccess(r, w, tenant)
}
//GetTenant get one tenant
// GetTenant get one tenant
func (t *TenantStruct) GetTenant(w http.ResponseWriter, r *http.Request) {
tenant := r.Context().Value(ctxutil.ContextKey("tenant")).(*dbmodel.Tenants)
list := handler.GetTenantManager().BindTenantsResource([]*dbmodel.Tenants{tenant})
httputil.ReturnSuccess(r, w, list[0])
}
//ServicesCount Get all apps and status
// ServicesCount Get all apps and status
func (t *TenantStruct) ServicesCount(w http.ResponseWriter, r *http.Request) {
allStatus := t.StatusCli.GetAllStatus()
var closed int
@ -625,7 +625,7 @@ func (t *TenantStruct) ServicesCount(w http.ResponseWriter, r *http.Request) {
httputil.ReturnSuccess(r, w, serviceCount)
}
//ServicesInfo GetServiceInfo
// ServicesInfo GetServiceInfo
func (t *TenantStruct) ServicesInfo(w http.ResponseWriter, r *http.Request) {
// swagger:operation GET /v2/tenants/{tenant_name}/services v2 getServiceInfo
//
@ -657,7 +657,7 @@ func (t *TenantStruct) ServicesInfo(w http.ResponseWriter, r *http.Request) {
return
}
//CreateService create Service
// CreateService create Service
func (t *TenantStruct) CreateService(w http.ResponseWriter, r *http.Request) {
var ss api_model.ServiceStruct
if !httputil.ValidatorRequestStructAndErrorResponse(r, w, &ss, nil) {
@ -694,8 +694,10 @@ func (t *TenantStruct) CreateService(w http.ResponseWriter, r *http.Request) {
tenantID := r.Context().Value(ctxutil.ContextKey("tenant_id")).(string)
ss.TenantID = tenantID
if err := handler.GetServiceManager().ServiceCreate(&ss); err != nil {
// The creation of a component should be idempotent, and if it has been successfully created,
// the error that the component already exists should not be thrown.
if strings.Contains(err.Error(), "is exist in tenant") {
httputil.ReturnError(r, w, 400, fmt.Sprintf("create service error, %v", err))
httputil.ReturnSuccess(r, w, nil)
return
}
httputil.ReturnError(r, w, 500, fmt.Sprintf("create service error, %v", err))
@ -705,7 +707,7 @@ func (t *TenantStruct) CreateService(w http.ResponseWriter, r *http.Request) {
httputil.ReturnSuccess(r, w, nil)
}
//UpdateService create Service
// UpdateService create Service
func (t *TenantStruct) UpdateService(w http.ResponseWriter, r *http.Request) {
// swagger:operation PUT /v2/tenants/{tenant_name}/services/{service_alias} v2 updateService
//
@ -763,7 +765,7 @@ func (t *TenantStruct) UpdateService(w http.ResponseWriter, r *http.Request) {
httputil.ReturnSuccess(r, w, nil)
}
//SetLanguage SetLanguage
// SetLanguage SetLanguage
func (t *TenantStruct) SetLanguage(w http.ResponseWriter, r *http.Request) {
// swagger:operation POST /v2/tenants/{tenant_name}/services/{service_alias}/language v2 setLanguage
//
@ -803,7 +805,7 @@ func (t *TenantStruct) SetLanguage(w http.ResponseWriter, r *http.Request) {
return
}
//StatusService StatusService
// StatusService StatusService
func (t *TenantStruct) StatusService(w http.ResponseWriter, r *http.Request) {
// swagger:operation GET /v2/tenants/{tenant_name}/services/{service_alias}/status v2 serviceStatus
//
@ -835,12 +837,12 @@ func (t *TenantStruct) StatusService(w http.ResponseWriter, r *http.Request) {
return
}
//PostStatusService PostStatusService
// PostStatusService PostStatusService
func (t *TenantStruct) PostStatusService(w http.ResponseWriter, r *http.Request) {
logrus.Debugf("in status service serviceID")
}
//StatusServiceList service list status
// StatusServiceList service list status
func (t *TenantStruct) StatusServiceList(w http.ResponseWriter, r *http.Request) {
// swagger:operation POST /v2/tenants/{tenant_name}/services_status v2 serviceStatuslist
//
@ -875,7 +877,7 @@ func (t *TenantStruct) StatusServiceList(w http.ResponseWriter, r *http.Request)
httputil.ReturnSuccess(r, w, info)
}
//Label -
// Label -
func (t *TenantStruct) Label(w http.ResponseWriter, r *http.Request) {
var req api_model.LabelsStruct
ok := httputil.ValidatorRequestStructAndErrorResponse(r, w, &req, nil)
@ -934,7 +936,7 @@ func (t *TenantStruct) DeleteLabel(w http.ResponseWriter, r *http.Request, label
httputil.ReturnSuccess(r, w, nil)
}
//UpdateLabel Update updates labels
// UpdateLabel Update updates labels
func (t *TenantStruct) UpdateLabel(w http.ResponseWriter, r *http.Request, labels *api_model.LabelsStruct) {
serviceID := r.Context().Value(ctxutil.ContextKey("service_id")).(string)
if err := handler.GetServiceManager().UpdateLabel(labels, serviceID); err != nil {
@ -944,12 +946,12 @@ func (t *TenantStruct) UpdateLabel(w http.ResponseWriter, r *http.Request, label
httputil.ReturnSuccess(r, w, nil)
}
//StatusContainerID StatusContainerID
// StatusContainerID StatusContainerID
func (t *TenantStruct) StatusContainerID(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("status container IDs list"))
}
//SingleServiceInfo SingleServiceInfo
// SingleServiceInfo SingleServiceInfo
func (t *TenantStruct) SingleServiceInfo(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case "DELETE":
@ -959,7 +961,7 @@ func (t *TenantStruct) SingleServiceInfo(w http.ResponseWriter, r *http.Request)
}
}
//GetSingleServiceInfo GetSingleServiceInfo
// GetSingleServiceInfo GetSingleServiceInfo
func (t *TenantStruct) GetSingleServiceInfo(w http.ResponseWriter, r *http.Request) {
// swagger:operation GET /v2/tenants/{tenant_name}/services/{service_alias} v2 getService
//
@ -994,7 +996,7 @@ func (t *TenantStruct) GetSingleServiceInfo(w http.ResponseWriter, r *http.Reque
httputil.ReturnSuccess(r, w, result)
}
//DeleteSingleServiceInfo DeleteService
// DeleteSingleServiceInfo DeleteService
// swagger:operation DELETE /v2/tenants/{tenant_name}/services/{service_alias} v2 deleteService
//
// 删除应用
@ -1011,10 +1013,11 @@ func (t *TenantStruct) GetSingleServiceInfo(w http.ResponseWriter, r *http.Reque
// - application/xml
//
// responses:
// default:
// schema:
// "$ref": "#/responses/commandResponse"
// description: 统一返回格式
//
// default:
// schema:
// "$ref": "#/responses/commandResponse"
// description: 统一返回格式
func (t *TenantStruct) DeleteSingleServiceInfo(w http.ResponseWriter, r *http.Request) {
serviceID := r.Context().Value(ctxutil.ContextKey("service_id")).(string)
tenantID := r.Context().Value(ctxutil.ContextKey("tenant_id")).(string)
@ -1035,7 +1038,7 @@ func (t *TenantStruct) DeleteSingleServiceInfo(w http.ResponseWriter, r *http.Re
httputil.ReturnSuccess(r, w, nil)
}
//Dependency Dependency
// Dependency Dependency
func (t *TenantStruct) Dependency(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case "DELETE":
@ -1045,7 +1048,7 @@ func (t *TenantStruct) Dependency(w http.ResponseWriter, r *http.Request) {
}
}
//AddDependency AddDependency
// AddDependency AddDependency
// swagger:operation POST /v2/tenants/{tenant_name}/services/{service_alias}/dependency v2 addDependency
//
// 增加应用依赖关系
@ -1062,10 +1065,11 @@ func (t *TenantStruct) Dependency(w http.ResponseWriter, r *http.Request) {
// - application/xml
//
// responses:
// default:
// schema:
// "$ref": "#/responses/commandResponse"
// description: 统一返回格式
//
// default:
// schema:
// "$ref": "#/responses/commandResponse"
// description: 统一返回格式
func (t *TenantStruct) AddDependency(w http.ResponseWriter, r *http.Request) {
rules := validator.MapData{
"dep_service_id": []string{"required"},
@ -1089,7 +1093,7 @@ func (t *TenantStruct) AddDependency(w http.ResponseWriter, r *http.Request) {
httputil.ReturnSuccess(r, w, nil)
}
//DeleteDependency DeleteDependency
// DeleteDependency DeleteDependency
// swagger:operation DELETE /v2/tenants/{tenant_name}/services/{service_alias}/dependency v2 deleteDependency
//
// 删除应用依赖关系
@ -1106,10 +1110,11 @@ func (t *TenantStruct) AddDependency(w http.ResponseWriter, r *http.Request) {
// - application/xml
//
// responses:
// default:
// schema:
// "$ref": "#/responses/commandResponse"
// description: 统一返回格式
//
// default:
// schema:
// "$ref": "#/responses/commandResponse"
// description: 统一返回格式
func (t *TenantStruct) DeleteDependency(w http.ResponseWriter, r *http.Request) {
logrus.Debugf("trans delete depend service ")
rules := validator.MapData{
@ -1133,7 +1138,7 @@ func (t *TenantStruct) DeleteDependency(w http.ResponseWriter, r *http.Request)
httputil.ReturnSuccess(r, w, nil)
}
//Env Env
// Env Env
func (t *TenantStruct) Env(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case "DELETE":
@ -1145,7 +1150,7 @@ func (t *TenantStruct) Env(w http.ResponseWriter, r *http.Request) {
}
}
//AddEnv AddEnv
// AddEnv AddEnv
// swagger:operation POST /v2/tenants/{tenant_name}/services/{service_alias}/env v2 addEnv
//
// 增加环境变量
@ -1162,10 +1167,11 @@ func (t *TenantStruct) Env(w http.ResponseWriter, r *http.Request) {
// - application/xml
//
// responses:
// default:
// schema:
// "$ref": "#/responses/commandResponse"
// description: 统一返回格式
//
// default:
// schema:
// "$ref": "#/responses/commandResponse"
// description: 统一返回格式
func (t *TenantStruct) AddEnv(w http.ResponseWriter, r *http.Request) {
var envM api_model.AddTenantServiceEnvVar
if !httputil.ValidatorRequestStructAndErrorResponse(r, w, &envM, nil) {
@ -1194,7 +1200,7 @@ func (t *TenantStruct) AddEnv(w http.ResponseWriter, r *http.Request) {
httputil.ReturnSuccess(r, w, nil)
}
//UpdateEnv UpdateEnv
// UpdateEnv UpdateEnv
// swagger:operation PUT /v2/tenants/{tenant_name}/services/{service_alias}/env v2 update Env
//
// 修改环境变量
@ -1211,10 +1217,11 @@ func (t *TenantStruct) AddEnv(w http.ResponseWriter, r *http.Request) {
// - application/xml
//
// responses:
// default:
// schema:
// "$ref": "#/responses/commandResponse"
// description: 统一返回格式
//
// default:
// schema:
// "$ref": "#/responses/commandResponse"
// description: 统一返回格式
func (t *TenantStruct) UpdateEnv(w http.ResponseWriter, r *http.Request) {
var envM api_model.AddTenantServiceEnvVar
if !httputil.ValidatorRequestStructAndErrorResponse(r, w, &envM, nil) {
@ -1239,7 +1246,7 @@ func (t *TenantStruct) UpdateEnv(w http.ResponseWriter, r *http.Request) {
httputil.ReturnSuccess(r, w, nil)
}
//DeleteEnv DeleteEnv
// DeleteEnv DeleteEnv
// swagger:operation DELETE /v2/tenants/{tenant_name}/services/{service_alias}/env v2 deleteEnv
//
// 删除环境变量
@ -1256,10 +1263,11 @@ func (t *TenantStruct) UpdateEnv(w http.ResponseWriter, r *http.Request) {
// - application/xml
//
// responses:
// default:
// schema:
// "$ref": "#/responses/commandResponse"
// description: 统一返回格式
//
// default:
// schema:
// "$ref": "#/responses/commandResponse"
// description: 统一返回格式
func (t *TenantStruct) DeleteEnv(w http.ResponseWriter, r *http.Request) {
var envM api_model.DelTenantServiceEnvVar
if !httputil.ValidatorRequestStructAndErrorResponse(r, w, &envM, nil) {
@ -1290,7 +1298,7 @@ func (t *TenantStruct) DeleteEnv(w http.ResponseWriter, r *http.Request) {
httputil.ReturnSuccess(r, w, nil)
}
//Ports 应用端口控制器
// Ports 应用端口控制器
func (t *TenantStruct) Ports(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case "DELETE":
@ -1302,7 +1310,7 @@ func (t *TenantStruct) Ports(w http.ResponseWriter, r *http.Request) {
}
}
//PutPorts PortVar
// PutPorts PortVar
// swagger:operation PUT /v2/tenants/{tenant_name}/services/{service_alias}/ports v2 updatePort
//
// 更新应用端口信息(旧)
@ -1319,10 +1327,11 @@ func (t *TenantStruct) Ports(w http.ResponseWriter, r *http.Request) {
// - application/xml
//
// responses:
// default:
// schema:
// "$ref": "#/responses/commandResponse"
// description: 统一返回格式
//
// default:
// schema:
// "$ref": "#/responses/commandResponse"
// description: 统一返回格式
func (t *TenantStruct) PutPorts(w http.ResponseWriter, r *http.Request) {
tenantID := r.Context().Value(ctxutil.ContextKey("tenant_id")).(string)
serviceID := r.Context().Value(ctxutil.ContextKey("service_id")).(string)
@ -1337,7 +1346,7 @@ func (t *TenantStruct) PutPorts(w http.ResponseWriter, r *http.Request) {
httputil.ReturnSuccess(r, w, nil)
}
//AddPortVar PortVar
// AddPortVar PortVar
// swagger:operation POST /v2/tenants/{tenant_name}/services/{service_alias}/ports v2 addPort
//
// 增加应用端口,默认关闭对内和对外选项,需要开启使用相应接口
@ -1354,10 +1363,11 @@ func (t *TenantStruct) PutPorts(w http.ResponseWriter, r *http.Request) {
// - application/xml
//
// responses:
// default:
// schema:
// "$ref": "#/responses/commandResponse"
// description: 统一返回格式
//
// default:
// schema:
// "$ref": "#/responses/commandResponse"
// description: 统一返回格式
func (t *TenantStruct) addPortController(w http.ResponseWriter, r *http.Request) {
tenantID := r.Context().Value(ctxutil.ContextKey("tenant_id")).(string)
serviceID := r.Context().Value(ctxutil.ContextKey("service_id")).(string)
@ -1373,7 +1383,7 @@ func (t *TenantStruct) addPortController(w http.ResponseWriter, r *http.Request)
httputil.ReturnSuccess(r, w, ports.Port)
}
//UpdatePortVar PortVar
// UpdatePortVar PortVar
// swagger:operation PUT /v2/tenants/{tenant_name}/services/{service_alias}/ports/{port} v2 updatePort
//
// 更新应用端口信息
@ -1390,10 +1400,11 @@ func (t *TenantStruct) addPortController(w http.ResponseWriter, r *http.Request)
// - application/xml
//
// responses:
// default:
// schema:
// "$ref": "#/responses/commandResponse"
// description: 统一返回格式
//
// default:
// schema:
// "$ref": "#/responses/commandResponse"
// description: 统一返回格式
func (t *TenantStruct) updatePortController(w http.ResponseWriter, r *http.Request) {
tenantID := r.Context().Value(ctxutil.ContextKey("tenant_id")).(string)
serviceID := r.Context().Value(ctxutil.ContextKey("service_id")).(string)
@ -1415,7 +1426,7 @@ func (t *TenantStruct) updatePortController(w http.ResponseWriter, r *http.Reque
httputil.ReturnSuccess(r, w, nil)
}
//DeletePortVar PortVar
// DeletePortVar PortVar
// swagger:operation DELETE /v2/tenants/{tenant_name}/services/{service_alias}/ports/{port} v2 deletePort
//
// 删除端口变量
@ -1432,10 +1443,11 @@ func (t *TenantStruct) updatePortController(w http.ResponseWriter, r *http.Reque
// - application/xml
//
// responses:
// default:
// schema:
// "$ref": "#/responses/commandResponse"
// description: 统一返回格式
//
// default:
// schema:
// "$ref": "#/responses/commandResponse"
// description: 统一返回格式
func (t *TenantStruct) deletePortController(w http.ResponseWriter, r *http.Request) {
tenantID := r.Context().Value(ctxutil.ContextKey("tenant_id")).(string)
serviceID := r.Context().Value(ctxutil.ContextKey("service_id")).(string)
@ -1463,7 +1475,7 @@ func (t *TenantStruct) deletePortController(w http.ResponseWriter, r *http.Reque
httputil.ReturnSuccess(r, w, nil)
}
//PortOuterController 开关端口对外服务
// PortOuterController 开关端口对外服务
// swagger:operation PUT /v2/tenants/{tenant_name}/services/{service_alias}/ports/{port}/outer v2 PortOuterController
//
// 开关端口对外服务,应用无需重启自动生效
@ -1480,10 +1492,11 @@ func (t *TenantStruct) deletePortController(w http.ResponseWriter, r *http.Reque
// - application/xml
//
// responses:
// default:
// schema:
// "$ref": "#/responses/commandResponse"
// description: 统一返回格式
//
// default:
// schema:
// "$ref": "#/responses/commandResponse"
// description: 统一返回格式
func (t *TenantStruct) PortOuterController(w http.ResponseWriter, r *http.Request) {
var data api_model.ServicePortInnerOrOuter
if !httputil.ValidatorRequestStructAndErrorResponse(r, w, &(data.Body), nil) {
@ -1555,7 +1568,7 @@ func (t *TenantStruct) PortOuterController(w http.ResponseWriter, r *http.Reques
httputil.ReturnSuccess(r, w, rc)
}
//PortInnerController 开关端口对内服务
// PortInnerController 开关端口对内服务
// swagger:operation PUT /v2/tenants/{tenant_name}/services/{service_alias}/ports/{port}/inner v2 PortInnerController
//
// 开关对内服务,应用无需重启,自动生效
@ -1572,10 +1585,11 @@ func (t *TenantStruct) PortOuterController(w http.ResponseWriter, r *http.Reques
// - application/xml
//
// responses:
// default:
// schema:
// "$ref": "#/responses/commandResponse"
// description: 统一返回格式
//
// default:
// schema:
// "$ref": "#/responses/commandResponse"
// description: 统一返回格式
func (t *TenantStruct) PortInnerController(w http.ResponseWriter, r *http.Request) {
var data api_model.ServicePortInnerOrOuter
if !httputil.ValidatorRequestStructAndErrorResponse(r, w, &(data.Body), nil) {
@ -1614,7 +1628,7 @@ func (t *TenantStruct) PortInnerController(w http.ResponseWriter, r *http.Reques
httputil.ReturnSuccess(r, w, nil)
}
//Pods pods
// Pods pods
// swagger:operation GET /v2/tenants/{tenant_name}/services/{service_alias}/pods v2 getPodsInfo
//
// 获取pods信息
@ -1631,10 +1645,11 @@ func (t *TenantStruct) PortInnerController(w http.ResponseWriter, r *http.Reques
// - application/xml
//
// responses:
// default:
// schema:
// "$ref": "#/responses/commandResponse"
// description: 统一返回格式
//
// default:
// schema:
// "$ref": "#/responses/commandResponse"
// description: 统一返回格式
func (t *TenantStruct) Pods(w http.ResponseWriter, r *http.Request) {
serviceID := r.Context().Value(ctxutil.ContextKey("service_id")).(string)
pods, err := handler.GetServiceManager().GetPods(serviceID)
@ -1651,7 +1666,7 @@ func (t *TenantStruct) Pods(w http.ResponseWriter, r *http.Request) {
httputil.ReturnSuccess(r, w, pods)
}
//Probe probe
// Probe probe
func (t *TenantStruct) Probe(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case "PUT":
@ -1663,7 +1678,7 @@ func (t *TenantStruct) Probe(w http.ResponseWriter, r *http.Request) {
}
}
//AddProbe add probe
// AddProbe add probe
// swagger:operation POST /v2/tenants/{tenant_name}/services/{service_alias}/probe v2 addProbe
//
// 增加应用探针
@ -1680,10 +1695,11 @@ func (t *TenantStruct) Probe(w http.ResponseWriter, r *http.Request) {
// - application/xml
//
// responses:
// default:
// schema:
// "$ref": "#/responses/commandResponse"
// description: 统一返回格式
//
// default:
// schema:
// "$ref": "#/responses/commandResponse"
// description: 统一返回格式
func (t *TenantStruct) AddProbe(w http.ResponseWriter, r *http.Request) {
serviceID := r.Context().Value(ctxutil.ContextKey("service_id")).(string)
var tsp api_model.ServiceProbe
@ -1714,7 +1730,7 @@ func (t *TenantStruct) AddProbe(w http.ResponseWriter, r *http.Request) {
httputil.ReturnSuccess(r, w, nil)
}
//UpdateProbe update probe
// UpdateProbe update probe
// swagger:operation PUT /v2/tenants/{tenant_name}/services/{service_alias}/probe v2 updateProbe
//
// 更新应用探针信息, *注意此处为全量更新
@ -1731,10 +1747,11 @@ func (t *TenantStruct) AddProbe(w http.ResponseWriter, r *http.Request) {
// - application/xml
//
// responses:
// default:
// schema:
// "$ref": "#/responses/commandResponse"
// description: 统一返回格式
//
// default:
// schema:
// "$ref": "#/responses/commandResponse"
// description: 统一返回格式
func (t *TenantStruct) UpdateProbe(w http.ResponseWriter, r *http.Request) {
serviceID := r.Context().Value(ctxutil.ContextKey("service_id")).(string)
var tsp api_model.ServiceProbe
@ -1768,7 +1785,7 @@ func (t *TenantStruct) UpdateProbe(w http.ResponseWriter, r *http.Request) {
httputil.ReturnSuccess(r, w, nil)
}
//DeleteProbe delete probe
// DeleteProbe delete probe
// swagger:operation DELETE /v2/tenants/{tenant_name}/services/{service_alias}/probe v2 deleteProbe
//
// 删除应用探针
@ -1785,10 +1802,11 @@ func (t *TenantStruct) UpdateProbe(w http.ResponseWriter, r *http.Request) {
// - application/xml
//
// responses:
// default:
// schema:
// "$ref": "#/responses/commandResponse"
// description: 统一返回格式
//
// default:
// schema:
// "$ref": "#/responses/commandResponse"
// description: 统一返回格式
func (t *TenantStruct) DeleteProbe(w http.ResponseWriter, r *http.Request) {
serviceID := r.Context().Value(ctxutil.ContextKey("service_id")).(string)
var tsp api_model.ServiceProbe
@ -1810,7 +1828,7 @@ func (t *TenantStruct) DeleteProbe(w http.ResponseWriter, r *http.Request) {
httputil.ReturnSuccess(r, w, nil)
}
//Port Port
// Port Port
func (t *TenantStruct) Port(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case "PUT":
@ -1822,19 +1840,19 @@ func (t *TenantStruct) Port(w http.ResponseWriter, r *http.Request) {
}
}
//AddPort add port
// AddPort add port
func (t *TenantStruct) AddPort(w http.ResponseWriter, r *http.Request) {
}
//DeletePort delete port
// DeletePort delete port
func (t *TenantStruct) DeletePort(w http.ResponseWriter, r *http.Request) {
}
//UpdatePort Update port
// UpdatePort Update port
func (t *TenantStruct) UpdatePort(w http.ResponseWriter, r *http.Request) {
}
//SingleTenantResources SingleTenantResources
// SingleTenantResources SingleTenantResources
// swagger:operation GET /v2/tenants/{tenant_name}/resources v2 singletenantResources
//
// 指定租户资源使用情况
@ -1846,17 +1864,18 @@ func (t *TenantStruct) UpdatePort(w http.ResponseWriter, r *http.Request) {
// - application/json
// - application/xml
// parameters:
// - name: tenant_name
// in: path
// description: tenant name
// required: true
// type: string
// - name: tenant_name
// in: path
// description: tenant name
// required: true
// type: string
//
// responses:
// default:
// schema:
// "$ref": "#/responses/commandResponse"
// description: 统一返回格式
//
// default:
// schema:
// "$ref": "#/responses/commandResponse"
// description: 统一返回格式
func (t *TenantStruct) SingleTenantResources(w http.ResponseWriter, r *http.Request) {
tenantID := r.Context().Value(ctxutil.ContextKey("tenant_id")).(string)
//11ms
@ -1875,7 +1894,7 @@ func (t *TenantStruct) SingleTenantResources(w http.ResponseWriter, r *http.Requ
return
}
//GetSupportProtocols GetSupportProtocols
// GetSupportProtocols GetSupportProtocols
// swagger:operation GET /v2/tenants/{tenant_name}/protocols v2 getSupportProtocols
//
// 获取当前数据中心支持的protocols
@ -1887,17 +1906,18 @@ func (t *TenantStruct) SingleTenantResources(w http.ResponseWriter, r *http.Requ
// - application/json
// - application/xml
// parameters:
// - name: tenant_name
// in: path
// description: tenant name
// required: true
// type: string
// - name: tenant_name
// in: path
// description: tenant name
// required: true
// type: string
//
// responses:
// default:
// schema:
// "$ref": "#/responses/commandResponse"
// description: 统一返回格式
//
// default:
// schema:
// "$ref": "#/responses/commandResponse"
// description: 统一返回格式
func (t *TenantStruct) GetSupportProtocols(w http.ResponseWriter, r *http.Request) {
rps, err := handler.GetTenantManager().GetProtocols()
if err != nil {
@ -1908,7 +1928,7 @@ func (t *TenantStruct) GetSupportProtocols(w http.ResponseWriter, r *http.Reques
return
}
//TransPlugins transPlugins
// TransPlugins transPlugins
// swagger:operation POST /v2/tenants/{tenant_name}/transplugins v2 transPlugins
//
// 安装云帮默认plugins
@ -1920,17 +1940,18 @@ func (t *TenantStruct) GetSupportProtocols(w http.ResponseWriter, r *http.Reques
// - application/json
// - application/xml
// parameters:
// - name: tenant_name
// in: path
// description: tenant name
// required: true
// type: string
// - name: tenant_name
// in: path
// description: tenant name
// required: true
// type: string
//
// responses:
// default:
// schema:
// "$ref": "#/responses/commandResponse"
// description: 统一返回格式
//
// default:
// schema:
// "$ref": "#/responses/commandResponse"
// description: 统一返回格式
func (t *TenantStruct) TransPlugins(w http.ResponseWriter, r *http.Request) {
var tps api_model.TransPlugins
ok := httputil.ValidatorRequestStructAndErrorResponse(r, w, &tps.Body, nil)

View File

@ -2024,6 +2024,17 @@ func (s *ServiceAction) CreateTenant(t *dbmodel.Tenants) error {
return err
}
}
if t.Namespace == "default" {
ns, err := s.kubeClient.CoreV1().Namespaces().Get(context.Background(), t.Namespace, metav1.GetOptions{})
if err != nil && !k8sErrors.IsNotFound(err) {
return err
}
if err == nil {
ns.Labels = labels
_, err = s.kubeClient.CoreV1().Namespaces().Update(context.Background(), ns, metav1.UpdateOptions{})
return err
}
}
if _, err := s.kubeClient.CoreV1().Namespaces().Create(context.Background(), &corev1.Namespace{
ObjectMeta: metav1.ObjectMeta{
Name: t.Namespace,

View File

@ -524,19 +524,23 @@ func (e *ErrorBuild) Error() string {
func (s *slugBuild) HandleNodeJsDir(re *Request) error {
if re.Lang == code.NodeJSStatic {
if ok, _ := util.FileExists(path.Join(re.SourceDir, "nodestatic.json")); !ok {
filePtr, err := os.Create(path.Join(re.SourceDir, "nodestatic.json"))
if err != nil {
logrus.Error("create nodestatic json error:", err)
return err
}
defer filePtr.Close()
_, err = io.WriteString(filePtr, "{\"path\":\"dist\"}")
if err != nil {
logrus.Error("write nodestatic json error:", err)
if ok, _ := util.FileExists(path.Join(re.SourceDir, "nodestatic.json")); ok {
if err := os.RemoveAll(path.Join(re.SourceDir, "nodestatic.json")); err != nil {
logrus.Error("remove nodestatic json error:", err)
return err
}
}
filePtr, err := os.Create(path.Join(re.SourceDir, "nodestatic.json"))
if err != nil {
logrus.Error("create nodestatic json error:", err)
return err
}
defer filePtr.Close()
_, err = io.WriteString(filePtr, fmt.Sprintf("{\"path\":\"%v\"}", re.BuildEnvs["DIST_DIR"]))
if err != nil {
logrus.Error("write nodestatic json error:", err)
return err
}
}
if re.BuildEnvs["PACKAGE_TOOL"] == "yarn" {
if ok, _ := util.FileExists(path.Join(re.SourceDir, "yarn.lock")); !ok {

View File

@ -49,6 +49,7 @@ type ImageBuildItem struct {
HubPassword string
Action string
Configs map[string]gjson.Result `json:"configs"`
FailCause string
}
//NewImageBuildItem 创建实体
@ -77,19 +78,25 @@ func (i *ImageBuildItem) Run(timeout time.Duration) error {
_, err := i.ImageClient.ImagePull(i.Image, user, pass, i.Logger, 30)
if err != nil {
logrus.Errorf("pull image %s error: %s", i.Image, err.Error())
i.Logger.Error(fmt.Sprintf("获取指定镜像: %s失败", i.Image), map[string]string{"step": "builder-exector", "status": "failure"})
failCause := fmt.Sprintf("获取指定镜像: %s失败", i.Image)
i.Logger.Error(failCause, map[string]string{"step": "builder-exector", "status": "failure"})
i.FailCause = failCause
return err
}
localImageURL := build.CreateImageName(i.ServiceID, i.DeployVersion)
if err := i.ImageClient.ImageTag(i.Image, localImageURL, i.Logger, 1); err != nil {
logrus.Errorf("change image tag error: %s", err.Error())
i.Logger.Error(fmt.Sprintf("修改镜像tag: %s -> %s 失败", i.Image, localImageURL), map[string]string{"step": "builder-exector", "status": "failure"})
failCause := fmt.Sprintf("修改镜像tag: %s -> %s 失败", i.Image, localImageURL)
i.Logger.Error(failCause, map[string]string{"step": "builder-exector", "status": "failure"})
i.FailCause = failCause
return err
}
err = i.ImageClient.ImagePush(localImageURL, builder.REGISTRYUSER, builder.REGISTRYPASS, i.Logger, 30)
if err != nil {
logrus.Errorf("push image into registry error: %s", err.Error())
i.Logger.Error("推送镜像至镜像仓库失败", map[string]string{"step": "builder-exector", "status": "failure"})
failCause := "推送镜像至镜像仓库失败"
i.Logger.Error(failCause, map[string]string{"step": "builder-exector", "status": "failure"})
i.FailCause = failCause
return err
}
@ -104,7 +111,9 @@ func (i *ImageBuildItem) Run(timeout time.Duration) error {
}
if err := i.StorageVersionInfo(localImageURL); err != nil {
logrus.Errorf("storage version info error, ignor it: %s", err.Error())
i.Logger.Error("更新应用版本信息失败", map[string]string{"step": "builder-exector", "status": "failure"})
failCause := "更新应用版本信息失败"
i.Logger.Error(failCause, map[string]string{"step": "builder-exector", "status": "failure"})
i.FailCause = failCause
return err
}
return nil

View File

@ -76,6 +76,7 @@ type SourceCodeBuildItem struct {
commit Commit
Configs map[string]gjson.Result `json:"configs"`
Ctx context.Context
FailCause string
}
//Commit code Commit
@ -134,13 +135,17 @@ func (i *SourceCodeBuildItem) Run(timeout time.Duration) error {
// 4.upload image /upload slug
rbi, err := sources.CreateRepostoryBuildInfo(i.CodeSouceInfo.RepositoryURL, i.CodeSouceInfo.ServerType, i.CodeSouceInfo.Branch, i.TenantID, i.ServiceID)
if err != nil {
i.Logger.Error("Git项目仓库地址格式错误", map[string]string{"step": "parse"})
failCause := util.Translation("git project warehouse address format error")
i.Logger.Error(failCause, map[string]string{"step": "parse"})
i.FailCause = failCause
return err
}
i.RepoInfo = rbi
if err := i.prepare(); err != nil {
logrus.Errorf("prepare build code error: %s", err.Error())
i.Logger.Error("准备源码构建失败", map[string]string{"step": "builder-exector", "status": "failure"})
failCause := util.Translation("prepare build code error")
i.Logger.Error(failCause, map[string]string{"step": "builder-exector", "status": "failure"})
i.FailCause = failCause
return err
}
i.CodeSouceInfo.RepositoryURL = rbi.RepostoryURL
@ -151,12 +156,16 @@ func (i *SourceCodeBuildItem) Run(timeout time.Duration) error {
rs, err := svnclient.UpdateOrCheckout(rbi.BuildPath)
if err != nil {
logrus.Errorf("checkout svn code error: %s", err.Error())
i.Logger.Error(fmt.Sprintf("Checkout svn code failed, please make sure the code can be downloaded properly"), map[string]string{"step": "builder-exector", "status": "failure"})
failCause := util.Translation("Checkout svn code failed, please make sure the code can be downloaded properly")
i.Logger.Error(failCause, map[string]string{"step": "builder-exector", "status": "failure"})
i.FailCause = failCause
return err
}
if rs.Logs == nil || len(rs.Logs.CommitEntrys) < 1 {
logrus.Errorf("get code commit info error: %s", err.Error())
i.Logger.Error(fmt.Sprintf("读取代码版本信息失败"), map[string]string{"step": "builder-exector", "status": "failure"})
failCause := util.Translation("get code commit info error")
i.Logger.Error(failCause, map[string]string{"step": "builder-exector", "status": "failure"})
i.FailCause = failCause
return err
}
i.commit = Commit{
@ -231,17 +240,25 @@ func (i *SourceCodeBuildItem) Run(timeout time.Duration) error {
default:
//default git
rs, err := sources.GitCloneOrPull(i.CodeSouceInfo, rbi.GetCodeHome(), i.Logger, 5)
rs, errMsg, err := sources.GitCloneOrPull(i.CodeSouceInfo, rbi.GetCodeHome(), i.Logger, 5)
if err != nil {
logrus.Errorf("pull git code error: %s", err.Error())
i.Logger.Error("拉取代码失败,请确保代码可以被正常下载", map[string]string{"step": "builder-exector", "status": "failure"})
failCause := util.Translation("pull git code error")
i.Logger.Error(failCause, map[string]string{"step": "builder-exector", "status": "failure"})
if errMsg != "" {
i.FailCause = errMsg
} else {
i.FailCause = failCause
}
return err
}
//get last commit
commit, err := sources.GetLastCommit(rs)
if err != nil || commit == nil {
logrus.Errorf("get code commit info error: %s", err.Error())
i.Logger.Error("读取代码版本信息失败", map[string]string{"step": "builder-exector", "status": "failure"})
failCause := util.Translation("get code commit info error")
i.Logger.Error(failCause, map[string]string{"step": "builder-exector", "status": "failure"})
i.FailCause = failCause
return err
}
i.commit = Commit{
@ -268,8 +285,10 @@ func (i *SourceCodeBuildItem) Run(timeout time.Duration) error {
if _, ok := i.BuildEnvs["REPARSE"]; ok {
_, lang, err := parser.ReadRbdConfigAndLang(rbi)
if err != nil {
failCause := util.Translation("reparse code lange error")
logrus.Errorf("reparse code lange error %s", err.Error())
i.Logger.Error(fmt.Sprintf("重新解析代码语言错误"), map[string]string{"step": "builder-exector", "status": "failure"})
i.Logger.Error(failCause, map[string]string{"step": "builder-exector", "status": "failure"})
i.FailCause = failCause
return err
}
i.Lang = string(lang)
@ -283,6 +302,7 @@ func (i *SourceCodeBuildItem) Run(timeout time.Duration) error {
} else {
i.Logger.Error("Build app version from source code failure,"+err.Error(), map[string]string{"step": "builder-exector", "status": "failure"})
}
i.FailCause = util.Translation("Check for log location code errors")
return err
}
if err := i.UpdateBuildVersionInfo(res); err != nil {

View File

@ -307,7 +307,7 @@ func (e *exectorManager) buildFromImage(task *pb.TaskMessage) {
i.Logger.Error("The application task to build from the mirror failed to executewill try", map[string]string{"step": "build-exector", "status": "failure"})
} else {
MetricErrorTaskNum++
i.Logger.Error(util.Translation("Check for log location imgae source errors"), map[string]string{"step": "callback", "status": "failure"})
i.Logger.Error(i.FailCause, map[string]string{"step": "callback", "status": "failure"})
if err := i.UpdateVersionInfo("failure"); err != nil {
logrus.Debugf("update version Info error: %s", err.Error())
}
@ -361,7 +361,7 @@ func (e *exectorManager) buildFromSourceCode(task *pb.TaskMessage) {
err := i.Run(time.Minute * 30)
if err != nil {
logrus.Errorf("build from source code error: %s", err.Error())
i.Logger.Error(util.Translation("Check for log location code errors"), map[string]string{"step": "callback", "status": "failure"})
i.Logger.Error(i.FailCause, map[string]string{"step": "callback", "status": "failure"})
vi := &dbmodel.VersionInfo{
FinalStatus: "failure",
EventID: i.EventID,

View File

@ -89,7 +89,7 @@ func (e *exectorManager) runD(t *model.BuildPluginTaskBody, logger event.Logger)
if err := util.CheckAndCreateDir(sourceDir); err != nil {
return err
}
if _, err := sources.GitClone(sources.CodeSourceInfo{RepositoryURL: t.GitURL, Branch: t.Repo, User: t.GitUsername, Password: t.GitPassword}, sourceDir, logger, 4); err != nil {
if _, _, err := sources.GitClone(sources.CodeSourceInfo{RepositoryURL: t.GitURL, Branch: t.Repo, User: t.GitUsername, Password: t.GitPassword}, sourceDir, logger, 4); err != nil {
logger.Error("拉取代码失败", map[string]string{"step": "builder-exector", "status": "failure"})
logrus.Errorf("[plugin]git clone code error %v", err)
return err

View File

@ -128,7 +128,7 @@ func (d *SourceCodeParse) Parse() ParseErrorList {
}
}
csi.RepositoryURL = buildInfo.RepostoryURL
rs, err := sources.GitClone(csi, buildInfo.GetCodeHome(), d.logger, 5)
rs, _, err := sources.GitClone(csi, buildInfo.GetCodeHome(), d.logger, 5)
if err != nil {
if err == transport.ErrAuthenticationRequired || err == transport.ErrAuthorizationFailed {
if buildInfo.GetProtocol() == "ssh" {

View File

@ -114,7 +114,7 @@ func getShowURL(rurl string) string {
}
//GitClone git clone code
func GitClone(csi CodeSourceInfo, sourceDir string, logger event.Logger, timeout int) (*git.Repository, error) {
func GitClone(csi CodeSourceInfo, sourceDir string, logger event.Logger, timeout int) (*git.Repository, string, error) {
GetPrivateFileParam := csi.TenantID
if !strings.HasSuffix(csi.RepositoryURL, ".git") {
csi.RepositoryURL = csi.RepositoryURL + ".git"
@ -127,7 +127,7 @@ Loop:
}
ep, err := transport.NewEndpoint(csi.RepositoryURL)
if err != nil {
return nil, err
return nil, "", err
}
if timeout < 1 {
timeout = 1
@ -152,10 +152,11 @@ Loop:
publichFile := GetPrivateFile(GetPrivateFileParam)
sshAuth, auerr := ssh.NewPublicKeysFromFile("git", publichFile, "")
if auerr != nil {
errMsg := fmt.Sprintf("创建SSH PublicKeys错误")
if logger != nil {
logger.Error(fmt.Sprintf("Create PublicKeys failure"), map[string]string{"step": "clone-code", "status": "failure"})
logger.Error(errMsg, map[string]string{"step": "pull-code", "status": "failure"})
}
return nil, auerr
return nil, errMsg, auerr
}
sshAuth.HostKeyCallbackHelper.HostKeyCallback = netssh.InsecureIgnoreHostKey()
opts.Auth = sshAuth
@ -192,39 +193,45 @@ Loop:
}
if err != nil {
if reerr := os.RemoveAll(sourceDir); reerr != nil {
errMsg := fmt.Sprintf("拉取代码发生错误删除代码目录失败。")
if logger != nil {
logger.Error(fmt.Sprintf("拉取代码发生错误删除代码目录失败。"), map[string]string{"step": "clone-code", "status": "failure"})
logger.Error(errMsg, map[string]string{"step": "clone-code", "status": "failure"})
}
}
if err == transport.ErrAuthenticationRequired {
errMsg := fmt.Sprintf("拉取代码发生错误,代码源需要授权访问。")
if logger != nil {
logger.Error(fmt.Sprintf("拉取代码发生错误,代码源需要授权访问。"), map[string]string{"step": "clone-code", "status": "failure"})
logger.Error(errMsg, map[string]string{"step": "clone-code", "status": "failure"})
}
return rs, err
return rs, errMsg, err
}
if err == transport.ErrAuthorizationFailed {
errMsg := fmt.Sprintf("拉取代码发生错误,代码源鉴权失败。")
if logger != nil {
logger.Error(fmt.Sprintf("拉取代码发生错误,代码源鉴权失败。"), map[string]string{"step": "clone-code", "status": "failure"})
logger.Error(errMsg, map[string]string{"step": "clone-code", "status": "failure"})
}
return rs, err
return rs, errMsg, err
}
if err == transport.ErrRepositoryNotFound {
errMsg := fmt.Sprintf("拉取代码发生错误,仓库不存在。")
if logger != nil {
logger.Error(fmt.Sprintf("拉取代码发生错误,仓库不存在。"), map[string]string{"step": "clone-code", "status": "failure"})
}
return rs, err
return rs, errMsg, err
}
if err == transport.ErrEmptyRemoteRepository {
errMsg := fmt.Sprintf("拉取代码发生错误,远程仓库为空。")
if logger != nil {
logger.Error(fmt.Sprintf("拉取代码发生错误,远程仓库为空。"), map[string]string{"step": "clone-code", "status": "failure"})
logger.Error(errMsg, map[string]string{"step": "clone-code", "status": "failure"})
}
return rs, err
return rs, errMsg, err
}
if err == plumbing.ErrReferenceNotFound {
if err == plumbing.ErrReferenceNotFound || strings.Contains(err.Error(), "couldn't find remote ref") {
errMsg := fmt.Sprintf("代码分支(%s)不存在。", csi.Branch)
if logger != nil {
logger.Error(fmt.Sprintf("代码分支(%s)不存在。", csi.Branch), map[string]string{"step": "clone-code", "status": "failure"})
logger.Error(errMsg, map[string]string{"step": "clone-code", "status": "failure"})
}
return rs, fmt.Errorf("branch %s is not exist", csi.Branch)
return rs, errMsg, fmt.Errorf("branch %s is not exist", csi.Branch)
}
if strings.Contains(err.Error(), "ssh: unable to authenticate") {
@ -233,19 +240,21 @@ Loop:
flag = false
goto Loop
}
errMsg := fmt.Sprintf("远程代码库需要配置SSH Key。")
if logger != nil {
logger.Error(fmt.Sprintf("远程代码库需要配置SSH Key。"), map[string]string{"step": "clone-code", "status": "failure"})
logger.Error(errMsg, map[string]string{"step": "clone-code", "status": "failure"})
}
return rs, err
return rs, errMsg, err
}
if strings.Contains(err.Error(), "context deadline exceeded") {
errMsg := fmt.Sprintf("获取代码超时")
if logger != nil {
logger.Error(fmt.Sprintf("获取代码超时"), map[string]string{"step": "clone-code", "status": "failure"})
logger.Error(errMsg, map[string]string{"step": "clone-code", "status": "failure"})
}
return rs, err
return rs, errMsg, err
}
}
return rs, err
return rs, "", err
}
func retryAuth(ep *transport.Endpoint, csi CodeSourceInfo) (transport.AuthMethod, error) {
switch ep.Protocol {
@ -263,7 +272,7 @@ func retryAuth(ep *transport.Endpoint, csi CodeSourceInfo) (transport.AuthMethod
}
//GitPull git pull code
func GitPull(csi CodeSourceInfo, sourceDir string, logger event.Logger, timeout int) (*git.Repository, error) {
func GitPull(csi CodeSourceInfo, sourceDir string, logger event.Logger, timeout int) (*git.Repository, string, error) {
GetPrivateFileParam := csi.TenantID
flag := true
Loop:
@ -287,16 +296,17 @@ Loop:
}
ep, err := transport.NewEndpoint(csi.RepositoryURL)
if err != nil {
return nil, err
return nil, "", err
}
if ep.Protocol == "ssh" {
publichFile := GetPrivateFile(GetPrivateFileParam)
sshAuth, auerr := ssh.NewPublicKeysFromFile("git", publichFile, "")
if auerr != nil {
errMsg := fmt.Sprintf("创建SSH PublicKeys错误")
if logger != nil {
logger.Error(fmt.Sprintf("创建PublicKeys错误"), map[string]string{"step": "pull-code", "status": "failure"})
logger.Error(errMsg, map[string]string{"step": "pull-code", "status": "failure"})
}
return nil, auerr
return nil, errMsg, auerr
}
sshAuth.HostKeyCallbackHelper.HostKeyCallback = netssh.InsecureIgnoreHostKey()
opts.Auth = sshAuth
@ -322,44 +332,48 @@ Loop:
}
rs, err := git.PlainOpen(sourceDir)
if err != nil {
return nil, err
return nil, "", err
}
tree, err := rs.Worktree()
if err != nil {
return nil, err
return nil, "", err
}
err = tree.PullContext(ctx, opts)
if err != nil {
if err == transport.ErrAuthenticationRequired {
errMsg := fmt.Sprintf("更新代码发生错误,代码源需要授权访问。")
if logger != nil {
logger.Error(fmt.Sprintf("更新代码发生错误,代码源需要授权访问。"), map[string]string{"step": "pull-code", "status": "failure"})
logger.Error(errMsg, map[string]string{"step": "pull-code", "status": "failure"})
}
return rs, err
return rs, errMsg, err
}
if err == transport.ErrAuthorizationFailed {
errMsg := fmt.Sprintf("更新代码发生错误,代码源鉴权失败。")
if logger != nil {
logger.Error(fmt.Sprintf("更新代码发生错误,代码源鉴权失败。"), map[string]string{"step": "pull-code", "status": "failure"})
logger.Error(errMsg, map[string]string{"step": "pull-code", "status": "failure"})
}
return rs, err
return rs, errMsg, err
}
if err == transport.ErrRepositoryNotFound {
errMsg := fmt.Sprintf("更新代码发生错误,仓库不存在。")
if logger != nil {
logger.Error(fmt.Sprintf("更新代码发生错误,仓库不存在。"), map[string]string{"step": "pull-code", "status": "failure"})
logger.Error(errMsg, map[string]string{"step": "pull-code", "status": "failure"})
}
return rs, err
return rs, errMsg, err
}
if err == transport.ErrEmptyRemoteRepository {
errMsg := fmt.Sprintf("更新代码发生错误,远程仓库为空。")
if logger != nil {
logger.Error(fmt.Sprintf("更新代码发生错误,远程仓库为空。"), map[string]string{"step": "pull-code", "status": "failure"})
logger.Error(errMsg, map[string]string{"step": "pull-code", "status": "failure"})
}
return rs, err
return rs, errMsg, err
}
if err == plumbing.ErrReferenceNotFound {
errMsg := fmt.Sprintf("代码分支(%s)不存在。", csi.Branch)
if logger != nil {
logger.Error(fmt.Sprintf("代码分支(%s)不存在。", csi.Branch), map[string]string{"step": "pull-code", "status": "failure"})
logger.Error(errMsg, map[string]string{"step": "pull-code", "status": "failure"})
}
return rs, fmt.Errorf("branch %s is not exist", csi.Branch)
return rs, errMsg, fmt.Errorf("branch %s is not exist", csi.Branch)
}
if strings.Contains(err.Error(), "ssh: unable to authenticate") {
if flag {
@ -367,30 +381,32 @@ Loop:
flag = false
goto Loop
}
errMsg := fmt.Sprintf("远程代码库需要配置SSH Key。")
if logger != nil {
logger.Error(fmt.Sprintf("远程代码库需要配置SSH Key。"), map[string]string{"step": "pull-code", "status": "failure"})
logger.Error(errMsg, map[string]string{"step": "pull-code", "status": "failure"})
}
return rs, err
return rs, errMsg, err
}
if strings.Contains(err.Error(), "context deadline exceeded") {
errMsg := fmt.Sprintf("更新代码超时")
if logger != nil {
logger.Error(fmt.Sprintf("更新代码超时"), map[string]string{"step": "pull-code", "status": "failure"})
logger.Error(errMsg, map[string]string{"step": "pull-code", "status": "failure"})
}
return rs, err
return rs, errMsg, err
}
if err == git.NoErrAlreadyUpToDate {
return rs, nil
return rs, "", nil
}
}
return rs, err
return rs, "", err
}
//GitCloneOrPull if code exist in local,use git pull.
func GitCloneOrPull(csi CodeSourceInfo, sourceDir string, logger event.Logger, timeout int) (*git.Repository, error) {
func GitCloneOrPull(csi CodeSourceInfo, sourceDir string, logger event.Logger, timeout int) (*git.Repository, string, error) {
if ok, err := util.FileExists(path.Join(sourceDir, ".git")); err == nil && ok && !strings.HasPrefix(csi.Branch, "tag:") {
re, err := GitPull(csi, sourceDir, logger, timeout)
re, msg, err := GitPull(csi, sourceDir, logger, timeout)
if err == nil && re != nil {
return re, nil
return re, msg, nil
}
logrus.Error("git pull source code error,", err.Error())
}

View File

@ -436,6 +436,10 @@ type EventDao interface {
GetLastASyncEvent(target, targetID string) (*model.ServiceEvent, error)
UnfinishedEvents(target, targetID string, optTypes ...string) ([]*model.ServiceEvent, error)
LatestFailurePodEvent(podName string) (*model.ServiceEvent, error)
GetAppointEvent(serviceID, status, Opt string) (*model.ServiceEvent, error)
AbnormalEvent(serviceID, Opt string) (*model.ServiceEvent, error)
DelAbnormalEvent(serviceID, Opt string) error
DelAllAbnormalEvent(serviceID string, Opts []string) error
UpdateReason(eventID string, reason string) error
SetEventStatus(ctx context.Context, status model.EventStatus) error
DeleteEvents(eventIDs []string) error

View File

@ -78,21 +78,21 @@ var EventStatusFailure EventStatus = "failure"
//ServiceEvent event struct
type ServiceEvent struct {
Model
EventID string `gorm:"column:event_id;size:40;index:event_id"`
TenantID string `gorm:"column:tenant_id;size:40;index:tenant_id"`
ServiceID string `gorm:"column:service_id;size:40;index:service_id"`
Target string `gorm:"column:target;size:40"`
TargetID string `gorm:"column:target_id;size:255;index:target_id"`
RequestBody string `gorm:"column:request_body;size:1024"`
UserName string `gorm:"column:user_name;size:40"`
StartTime string `gorm:"column:start_time;size:40"`
EndTime string `gorm:"column:end_time;size:40"`
OptType string `gorm:"column:opt_type;size:40"`
SynType int `gorm:"column:syn_type;size:1"`
Status string `gorm:"column:status;size:40"`
FinalStatus string `gorm:"column:final_status;size:40"`
Message string `gorm:"column:message"`
Reason string `gorm:"column:reason"`
EventID string `gorm:"column:event_id;size:40;index:event_id"`
TenantID string `gorm:"column:tenant_id;size:40;index:tenant_id"`
ServiceID string `gorm:"column:service_id;size:40;index:service_id"`
Target string `gorm:"column:target;size:40"`
TargetID string `gorm:"column:target_id;size:255;index:target_id"`
RequestBody string `gorm:"column:request_body;size:1024"`
UserName string `gorm:"column:user_name;size:40"`
StartTime string `gorm:"column:start_time;size:40"`
EndTime string `gorm:"column:end_time;size:40"`
OptType string `gorm:"column:opt_type;size:40"`
SynType int `gorm:"column:syn_type;size:1"`
Status string `gorm:"column:status;size:40"`
FinalStatus string `gorm:"column:final_status;size:40"`
Message string `gorm:"column:message"`
Reason string `gorm:"column:reason"`
}
//TableName 表名

View File

@ -265,6 +265,45 @@ func (c *EventDaoImpl) LatestFailurePodEvent(podName string) (*model.ServiceEven
return &event, nil
}
//GetAppointEvent get event log message
func (c *EventDaoImpl) GetAppointEvent(serviceID, status, Opt string) (*model.ServiceEvent, error) {
var result model.ServiceEvent
if err := c.DB.Where("service_id=? and status=? and opt_type=?", serviceID, status, Opt).Last(&result).Error; err != nil {
return nil, err
}
return &result, nil
}
// AbnormalEvent Abnormal event in components.
func (c *EventDaoImpl) AbnormalEvent(serviceID, Opt string) (*model.ServiceEvent, error) {
var event model.ServiceEvent
if err := c.DB.Where("target=? and service_id=? and opt_type=? and status=?", model.TargetTypePod, serviceID, Opt, model.EventStatusFailure.String()).
Last(&event).Error; err != nil {
return nil, err
}
return &event, nil
}
// DelAbnormalEvent delete Abnormal event in components.
func (c *EventDaoImpl) DelAbnormalEvent(serviceID, Opt string) error {
var event model.ServiceEvent
if err := c.DB.Where("target=? and service_id=? and opt_type=? and status=?", model.TargetTypePod, serviceID, Opt, model.EventStatusFailure.String()).
Delete(&event).Error; err != nil {
return err
}
return nil
}
// DelAllAbnormalEvent delete all Abnormal event in components when stop.
func (c *EventDaoImpl) DelAllAbnormalEvent(serviceID string, Opts []string) error {
var event model.ServiceEvent
if err := c.DB.Where("target=? and service_id=? and opt_type in (?) and status=?", model.TargetTypePod, serviceID, Opts, model.EventStatusFailure.String()).
Delete(&event).Error; err != nil {
return err
}
return nil
}
// SetEventStatus -
func (c *EventDaoImpl) SetEventStatus(ctx context.Context, status model.EventStatus) error {
event, _ := ctx.Value(ctxutil.ContextKey("event")).(*model.ServiceEvent)

View File

@ -1,4 +1,4 @@
FROM nginx:1.19
FROM nginx:stable-alpine3.17
ARG RELEASE_DESC
VOLUME ["/data/nginx/cache"]
ENV RELEASE_DESC=${RELEASE_DESC}

View File

@ -3,7 +3,6 @@ FROM goodrainapps/alpine:${BASE_IMAGE_VERSION}
ARG RELEASE_DESC
COPY rainbond-worker /run/rainbond-worker
COPY entrypoint.sh /run/entrypoint.sh
RUN chmod 655 /run/rainbond-worker
ENV EX_DOMAIN=ali-sh.goodrain.net:10080
ENV RELEASE_DESC=${RELEASE_DESC}

View File

@ -89,6 +89,15 @@ build::binary() {
if [ "$GOOS" = "windows" ]; then
mv "$OUTPATH" "${OUTPATH}.exe"
fi
if [ "$GOARCH" = "amd64" ]; then
sudo apt-get install -y upx
sudo upx --best --lzma "${OUTPATH}"
elif [ "$GOARCH" = "arm64" ]; then
wget https://rainbond-pkg.oss-cn-shanghai.aliyuncs.com/upx/upx-4.0.2-arm64_linux/upx
chmod +x upx
mv upx /usr/local/bin/upx
upx --best --lzma "${OUTPATH}"
fi
}
build::image() {

View File

@ -21,3 +21,12 @@ var memoryLabels = map[int]string{
32768: "32xlarge",
65536: "64xlarge",
}
// IsCustomMemory -
func IsCustomMemory(memory int) bool {
if _, ok := memoryLabels[memory]; ok {
return false
}
return true
}

View File

@ -46,6 +46,13 @@ var translationMetadata = map[string]string{
"Check for log location imgae source errors": "建议查看日志定位镜像源错误",
"create share image task error": "分享任务失败,请检查服务信息或查看日志",
"get rbd-repo ip failure": "获取依赖仓库IP地址失败请检查rbd-repo组件信息",
"reparse code lange error": "重新解析代码语言错误",
"get code commit info error": "读取代码版本信息失败",
"pull git code error": "拉取代码失败",
"git project warehouse address format error": "Git项目仓库地址格式错误",
"prepare build code error": "准备源码构建失败",
"Checkout svn code failed, please make sure the code can be downloaded properly": "检查svn代码失败请确保代码可以被正常下载",
}
//Translation Translation English to Chinese

View File

@ -21,6 +21,8 @@ package controller
import (
"context"
"fmt"
"github.com/goodrain/rainbond/db"
"github.com/jinzhu/gorm"
"sync"
"time"
@ -59,6 +61,10 @@ func (s *stopController) Begin() {
}
} else {
service.Logger.Info(fmt.Sprintf("stop service %s success", service.ServiceAlias), event.GetLastLoggerOption())
err = db.GetManager().ServiceEventDao().DelAllAbnormalEvent(service.ServiceID, []string{"INITIATING", "CrashLoopBackOff", "Unschedulable"})
if err != nil && err != gorm.ErrRecordNotFound {
logrus.Error("delete abnormal event error: ", err)
}
}
}(service)
}

View File

@ -220,16 +220,16 @@ func getMainContainer(as *v1.AppService, version *dbmodel.VersionInfo, dv *volum
return nil, err
}
c := &corev1.Container{
Name: as.K8sComponentName,
Image: imagename,
Args: args,
Ports: ports,
Env: envs,
EnvFrom: envFromSecrets,
VolumeMounts: vm,
LivenessProbe: createProbe(as, dbmanager, "liveness"),
ReadinessProbe: createProbe(as, dbmanager, "readiness"),
Resources: resources,
Name: as.K8sComponentName,
Image: imagename,
Args: args,
Ports: ports,
Env: envs,
EnvFrom: envFromSecrets,
VolumeMounts: vm,
LivenessProbe: createProbe(as, dbmanager, "liveness"),
ReadinessProbe: createProbe(as, dbmanager, "readiness"),
Resources: resources,
SecurityContext: security,
}
label, err := dbmanager.TenantServiceLabelDao().GetPrivilegedLabel(as.ServiceID)
@ -402,7 +402,11 @@ func createEnv(as *v1.AppService, dbmanager db.Manager, envVarSecrets []*corev1.
envs = append(envs, corev1.EnvVar{Name: "NAMESPACE", Value: as.GetNamespace()})
envs = append(envs, corev1.EnvVar{Name: "TENANT_ID", Value: as.TenantID})
envs = append(envs, corev1.EnvVar{Name: "SERVICE_ID", Value: as.ServiceID})
envs = append(envs, corev1.EnvVar{Name: "MEMORY_SIZE", Value: envutil.GetMemoryType(as.ContainerMemory)})
if envutil.IsCustomMemory(as.ContainerMemory) {
envs = append(envs, corev1.EnvVar{Name: "CUSTOM_MEMORY_SIZE", Value: strconv.Itoa(as.ContainerMemory)})
} else {
envs = append(envs, corev1.EnvVar{Name: "MEMORY_SIZE", Value: envutil.GetMemoryType(as.ContainerMemory)})
}
envs = append(envs, corev1.EnvVar{Name: "SERVICE_NAME", Value: as.GetK8sWorkloadName()})
envs = append(envs, corev1.EnvVar{Name: "SERVICE_ALIAS", Value: as.ServiceAlias})
envs = append(envs, corev1.EnvVar{Name: "SERVICE_POD_NUM", Value: strconv.Itoa(as.Replicas)})
@ -1225,7 +1229,6 @@ func createSecurityContext(as *v1.AppService, dbmanager db.Manager) (*corev1.Sec
return &securityContext, nil
}
func handleResource(resources corev1.ResourceRequirements, customResources *corev1.ResourceRequirements) (res corev1.ResourceRequirements) {
var haveMemory bool
if customResources != nil {

View File

@ -37,3 +37,4 @@ func IsPodNodeLost(pod *corev1.Pod) bool {
}
return false
}

View File

@ -1,7 +1,10 @@
package podevent
import (
"context"
"fmt"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/fields"
"sort"
"strings"
"time"
@ -30,6 +33,9 @@ func (p EventType) String() string {
// EventTypeOOMKilled -
var EventTypeOOMKilled EventType = "OOMKilled"
// EventTypeCrashLoopBackOff -
var EventTypeCrashLoopBackOff EventType = "CrashLoopBackOff"
// EventTypeAbnormalExited container exits abnormally
var EventTypeAbnormalExited EventType = "AbnormalExited"
@ -95,6 +101,9 @@ func (p *PodEvent) Handle() {
if time.Now().Sub(pod.CreationTimestamp.Time) > 10*time.Minute {
recordUpdateEvent(p.clientset, pod, defDetermineOptType)
}
if time.Now().Sub(pod.CreationTimestamp.Time) > 10*time.Second {
AbnormalEvent(p.clientset, pod)
}
case <-p.stopCh:
return
}
@ -105,6 +114,8 @@ func (p *PodEvent) Handle() {
func (p *PodEvent) GetChan() chan<- *corev1.Pod {
return p.podEventCh
}
//recordUpdateEvent -
func recordUpdateEvent(clientset kubernetes.Interface, pod *corev1.Pod, f determineOptType) {
evt, err := db.GetManager().ServiceEventDao().LatestFailurePodEvent(pod.GetName())
if err != nil && err != gorm.ErrRecordNotFound {
@ -124,7 +135,7 @@ func recordUpdateEvent(clientset kubernetes.Interface, pod *corev1.Pod, f determ
}
if evt == nil { // create event
eventID, err = createSystemEvent(tenantID, serviceID, pod.GetName(), optType.eventType.String(), model.EventStatusFailure.String())
eventID, err = createSystemEvent(tenantID, serviceID, pod.GetName(), optType.eventType.String(), model.EventStatusFailure.String(), optType.message)
if err != nil {
logrus.Warningf("pod: %s; type: %s; error creating event: %v", pod.GetName(), optType.eventType.String(), err)
return
@ -165,7 +176,7 @@ func recordUpdateEvent(clientset kubernetes.Interface, pod *corev1.Pod, f determ
logrus.Warningf("event id: %s; failed to update service event: %v", evt.EventID, err)
} else {
loggerOpt = event.GetCallbackLoggerOption()
_, err := createSystemEvent(tenantID, serviceID, pod.GetName(), EventTypeAbnormalRecovery.String(), model.EventStatusSuccess.String())
_, err := createSystemEvent(tenantID, serviceID, pod.GetName(), EventTypeAbnormalRecovery.String(), model.EventStatusSuccess.String(), "")
if err != nil {
logrus.Warningf("pod: %s; type: %s; error creating event: %v", pod.GetName(), EventTypeAbnormalRecovery.String(), err)
return
@ -176,9 +187,184 @@ func recordUpdateEvent(clientset kubernetes.Interface, pod *corev1.Pod, f determ
}
}
// AbnormalEvent -
func AbnormalEvent(clientset kubernetes.Interface, pod *corev1.Pod) {
tenantID, serviceID, _, _ := k8sutil.ExtractLabels(pod.GetLabels())
if pod != nil && pod.Status.Phase == corev1.PodPending {
for _, condition := range pod.Status.Conditions {
if condition.Type == corev1.PodScheduled && condition.Status == "False" {
var msg string
if strings.Contains(condition.Message, "affinity/selector") {
msg = "不满足节点亲和性"
}
if strings.Contains(condition.Message, "cpu") {
msg = "节点CPU不足"
}
if strings.Contains(condition.Message, "memory") {
msg = "节点内存不足"
}
if strings.Contains(condition.Message, "PersistentVolumeClaims") {
msg = "当前没有绑定 PVC"
}
if strings.Contains(condition.Message, "tolerate") {
msg = "节点存在污点"
}
unSchedulableEvent, err := db.GetManager().ServiceEventDao().AbnormalEvent(serviceID, "Unschedulable")
if err != nil && err != gorm.ErrRecordNotFound {
logrus.Warningf("error fetching latest unfinished pod event: %v", err)
return
}
if unSchedulableEvent != nil {
return
}
_, err = createSystemEvent(tenantID, serviceID, pod.Name, condition.Reason, model.EventStatusFailure.String(), msg)
if err != nil {
logrus.Warningf("pod: %s; type: %s; error creating event: %v", pod.GetName(), EventTypeAbnormalRecovery.String(), err)
return
}
}
if condition.Type == corev1.PodInitialized && condition.Status == "False" {
serviceRelations, err := db.GetManager().TenantServiceRelationDao().GetTenantServiceRelations(serviceID)
if err != nil && err != gorm.ErrRecordNotFound {
logrus.Warningf("error fetching service relations: %v", err)
return
}
var serviceIDs []string
if serviceRelations != nil {
for _, serviceRelation := range serviceRelations {
serviceIDs = append(serviceIDs, serviceRelation.DependServiceID)
}
} else {
return
}
services, err := db.GetManager().TenantServiceDao().GetServiceByIDs(serviceIDs)
if err != nil {
logrus.Warningf("get service relations ids: %v", err)
return
}
var serviceNames []string
for _, service := range services {
tenant, err := db.GetManager().TenantDao().GetTenantByUUID(service.TenantID)
if err != nil {
logrus.Warningf("get service event tenant info error: %v", err)
}
servicePods, err := clientset.CoreV1().Pods(tenant.Namespace).List(context.Background(), metav1.ListOptions{
LabelSelector: fields.SelectorFromSet(map[string]string{
"service_id": service.ServiceID,
}).String(),
})
if err != nil {
logrus.Warningf("get service relations pods error: %v", err)
return
}
for _, servicePod := range servicePods.Items {
if servicePod.Status.Phase == corev1.PodPending {
serviceNames = append(serviceNames, service.ServiceAlias)
}
}
}
if serviceNames == nil {
return
}
msg := strings.Join(serviceNames, ",")
// Update component Waiting for startup events
initEvents, err := db.GetManager().ServiceEventDao().GetAppointEvent(serviceID, "failure", "INITIATING")
if err != nil && err != gorm.ErrRecordNotFound {
logrus.Warningf("get start time out event error: %v", err)
}
if initEvents != nil {
initEvents.Message = msg
err = db.GetManager().ServiceEventDao().UpdateModel(initEvents)
if err != nil {
logrus.Warningf("update start time out event error: %v", err)
}
return
}
_, err = createSystemEvent(tenantID, serviceID, pod.Name, "INITIATING", model.EventStatusFailure.String(), msg)
if err != nil {
logrus.Warningf("pod: %s; type: %s; error creating event: %v", pod.GetName(), EventTypeAbnormalRecovery.String(), err)
return
}
}
}
}
if pod != nil && pod.Status.Phase == corev1.PodRunning {
servicePods, err := clientset.CoreV1().Pods(pod.GetNamespace()).List(context.Background(), metav1.ListOptions{
FieldSelector: "metadata.namespace!=rbd-system",
LabelSelector: fields.SelectorFromSet(map[string]string{
"service_id": serviceID,
}).String(),
})
if err != nil {
return
}
allPodRunning := true
allCtrRunning := true
for _, servicePod := range servicePods.Items {
if servicePod.Status.Phase != corev1.PodRunning {
allPodRunning = false
}
for _, containerStatus := range servicePod.Status.ContainerStatuses {
if containerStatus.State.Running == nil {
allCtrRunning = false
}
}
}
if allPodRunning {
err = db.GetManager().ServiceEventDao().DelAbnormalEvent(serviceID, "Unschedulable")
if err != nil {
logrus.Warningf("Delete component scheduling pod event: %v", err)
}
// Update last startup component timeout events
startEvents, err := db.GetManager().ServiceEventDao().GetAppointEvent(serviceID, "timeout", "start-service")
if err != nil && err != gorm.ErrRecordNotFound {
logrus.Warningf("get start time out event error: %v", err)
}
if startEvents != nil {
startEvents.Message = "Start service success"
startEvents.Status = "success"
err = db.GetManager().ServiceEventDao().UpdateModel(startEvents)
if err != nil {
logrus.Warningf("update start time out event error: %v", err)
}
}
// delete Waiting for start event
err = db.GetManager().ServiceEventDao().DelAbnormalEvent(serviceID, "INITIATING")
if err != nil && err != gorm.ErrRecordNotFound {
logrus.Warningf("delete INITIATING event error: %v", err)
return
}
}
if allCtrRunning {
err := db.GetManager().ServiceEventDao().DelAbnormalEvent(serviceID, "CrashLoopBackOff")
if err != nil {
logrus.Warningf("Delete component scheduling pod event: %v", err)
}
}
for _, containerStatus := range pod.Status.ContainerStatuses {
if containerStatus.State.Waiting != nil && containerStatus.State.Waiting.Reason == EventTypeCrashLoopBackOff.String() {
unSchedulableEvent, err := db.GetManager().ServiceEventDao().AbnormalEvent(serviceID, "CrashLoopBackOff")
if err != nil && err != gorm.ErrRecordNotFound {
logrus.Warningf("error fetching latest unfinished pod event: %v", err)
return
}
if unSchedulableEvent != nil {
return
}
_, err = createSystemEvent(tenantID, serviceID, pod.Name, containerStatus.State.Waiting.Reason, model.EventStatusFailure.String(), "服务运行异常,请检查容器日志")
if err != nil {
logrus.Warningf("pod: %s; type: %s; error creating event: %v", pod.GetName(), EventTypeAbnormalRecovery.String(), err)
return
}
}
}
}
}
// determine the type of exception
type determineOptType func(clientset kubernetes.Interface, pod *corev1.Pod, f k8sutil.ListEventsByPod) *optType
// defDetermineOptType -
func defDetermineOptType(clientset kubernetes.Interface, pod *corev1.Pod, f k8sutil.ListEventsByPod) *optType {
oneContainerOptType := func(state corev1.ContainerState) (EventType, string) {
if state.Terminated != nil {
@ -234,7 +420,8 @@ func defDetermineOptType(clientset kubernetes.Interface, pod *corev1.Pod, f k8su
return optTypeMap[keys[0]]
}
func createSystemEvent(tenantID, serviceID, targetID, optType, status string) (eventID string, err error) {
// createSystemEvent -
func createSystemEvent(tenantID, serviceID, targetID, optType, status, msg string) (eventID string, err error) {
eventID = util.NewUUID()
et := &model.ServiceEvent{
EventID: eventID,
@ -246,6 +433,7 @@ func createSystemEvent(tenantID, serviceID, targetID, optType, status string) (e
OptType: optType,
Status: status,
FinalStatus: model.EventFinalStatusEmpty.String(),
Message: msg,
}
if err = db.GetManager().ServiceEventDao().AddModel(et); err != nil {
return

View File

@ -166,10 +166,16 @@ func getPodNameByPVCName(pvcName string) string {
func getVolumeIDByPVCName(pvcName string) int {
logrus.Debug("parse volume id from pvc name", pvcName)
pvcNames := strings.SplitN(pvcName, "-", 2)
// pvcNames 通常情况下为 "manual15-zk-zk-gr3cd1a1-0" 或 "manual6", 但是在使用 Helm 部署时,由于存储使用集群内部的 StorageClass
// 并不是 rainbondsssc 或 rainbondsslc所以此时的 pvcNames 可能是 "data-sonar-gra7c815-0", 此时就会触发切片越界,但实际上对于
// 这类存储,应该交给 K8s 集群中的 StorageClass 处理
if len(pvcNames) == 2 {
idStr := pvcNames[0][6:]
id, _ := strconv.Atoi(idStr)
return id
if len(pvcNames[0]) > 6 {
idStr := pvcNames[0][6:]
id, _ := strconv.Atoi(idStr)
return id
}
return 0
}
if strings.HasPrefix(pvcName, "manual") {
idStr := strings.TrimPrefix(pvcName, "manual")
@ -212,7 +218,7 @@ func updatePathForPersistentVolumeSource(persistentVolumeSource *v1.PersistentVo
Path: newPath(persistentVolumeSource.HostPath.Path),
Type: persistentVolumeSource.HostPath.Type,
}
case persistentVolumeSource.CSI != nil :
case persistentVolumeSource.CSI != nil:
source.CSI = persistentVolumeSource.CSI
default:
return nil, fmt.Errorf("unsupported persistence volume source")

View File

@ -338,7 +338,6 @@ func (r *RuntimeServer) GetAppPods(ctx context.Context, re *pb.ServiceRequest) (
oldpods = append(oldpods, sapod)
}
}
return &pb.ServiceAppPodList{
OldPods: oldpods,
NewPods: newpods,