Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

정책을 위한 k8s resource name 추가 #326

Merged
merged 1 commit into from
Apr 3, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 12 additions & 3 deletions api/swagger/docs.go
Original file line number Diff line number Diff line change
Expand Up @@ -10209,12 +10209,16 @@ const docTemplate = `{
},
"parameters": {
"type": "string",
"example": "{\"labels\":{\"key\":\"owner\",\"allowedRegex\":\"test*\"}"
"example": "{\"key\":\"value\"}"
},
"policyName": {
"type": "string",
"example": "label 정책"
},
"policyResourceName": {
"type": "string",
"example": "labelpolicy"
},
"targetClusterIds": {
"type": "array",
"items": {
Expand Down Expand Up @@ -12226,16 +12230,21 @@ const docTemplate = `{
"$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.Match"
},
"matchYaml": {
"type": "string"
"type": "string",
"example": "namespaces:\r\n- testns1"
},
"parameters": {
"type": "string",
"example": "{\"labels\":{\"key\":\"owner\",\"allowedRegex\":\"test*\"}"
"example": "{\"key\":\"value\"}"
},
"policyName": {
"type": "string",
"example": "label 정책"
},
"policyResourceName": {
"type": "string",
"example": "labelpolicy"
},
"targetClusterIds": {
"type": "array",
"items": {
Expand Down
15 changes: 12 additions & 3 deletions api/swagger/swagger.json
Original file line number Diff line number Diff line change
Expand Up @@ -10203,12 +10203,16 @@
},
"parameters": {
"type": "string",
"example": "{\"labels\":{\"key\":\"owner\",\"allowedRegex\":\"test*\"}"
"example": "{\"key\":\"value\"}"
},
"policyName": {
"type": "string",
"example": "label 정책"
},
"policyResourceName": {
"type": "string",
"example": "labelpolicy"
},
"targetClusterIds": {
"type": "array",
"items": {
Expand Down Expand Up @@ -12220,16 +12224,21 @@
"$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.Match"
},
"matchYaml": {
"type": "string"
"type": "string",
"example": "namespaces:\r\n- testns1"
},
"parameters": {
"type": "string",
"example": "{\"labels\":{\"key\":\"owner\",\"allowedRegex\":\"test*\"}"
"example": "{\"key\":\"value\"}"
},
"policyName": {
"type": "string",
"example": "label 정책"
},
"policyResourceName": {
"type": "string",
"example": "labelpolicy"
},
"targetClusterIds": {
"type": "array",
"items": {
Expand Down
11 changes: 9 additions & 2 deletions api/swagger/swagger.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -895,11 +895,14 @@ definitions:
example: "namespaces:\r\n- testns1"
type: string
parameters:
example: '{"labels":{"key":"owner","allowedRegex":"test*"}'
example: '{"key":"value"}'
type: string
policyName:
example: label 정책
type: string
policyResourceName:
example: labelpolicy
type: string
targetClusterIds:
example:
- 83bf8081-f0c5-4b31-826d-23f6f366ec90
Expand Down Expand Up @@ -2231,13 +2234,17 @@ definitions:
match:
$ref: '#/definitions/github_com_openinfradev_tks-api_pkg_domain.Match'
matchYaml:
example: "namespaces:\r\n- testns1"
type: string
parameters:
example: '{"labels":{"key":"owner","allowedRegex":"test*"}'
example: '{"key":"value"}'
type: string
policyName:
example: label 정책
type: string
policyResourceName:
example: labelpolicy
type: string
targetClusterIds:
example:
- 83bf8081-f0c5-4b31-826d-23f6f366ec90
Expand Down
10 changes: 10 additions & 0 deletions internal/delivery/http/policy.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import (
"github.com/openinfradev/tks-api/pkg/httpErrors"
"github.com/openinfradev/tks-api/pkg/log"
"gopkg.in/yaml.v3"
"k8s.io/apimachinery/pkg/util/validation"
)

type PolicyHandler struct {
Expand Down Expand Up @@ -89,6 +90,15 @@ func (h *PolicyHandler) CreatePolicy(w http.ResponseWriter, r *http.Request) {
}
}

if len(input.PolicyResourceName) > 0 {
errMsgs := validation.IsDNS1123Subdomain(input.PolicyResourceName)

if len(errMsgs) > 0 {
ErrorJSON(w, r, httpErrors.NewBadRequestError(fmt.Errorf("invalid k8s resource name for policy: %v", errMsgs), "P_INVALID_RESURCE_NAME", ""))
return
}
}

var dto model.Policy
if err = serializer.Map(r.Context(), input, &dto); err != nil {
log.Info(r.Context(), err)
Expand Down
7 changes: 4 additions & 3 deletions internal/model/policy.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,10 @@ type Policy struct {
ID uuid.UUID `gorm:"primarykey;type:varchar(36);not null"`
OrganizationId string

PolicyName string
Mandatory bool
Description string
PolicyName string
PolicyResourceName string
Mandatory bool
Description string

TargetClusterIds []string `gorm:"-:all"`
TargetClusters []Cluster `gorm:"many2many:policy_target_clusters"`
Expand Down
2 changes: 1 addition & 1 deletion internal/policy-template/policy-operator.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ func PolicyToTksPolicyCR(policy *model.Policy) *TKSPolicy {
},

ObjectMeta: metav1.ObjectMeta{
Name: policy.PolicyName,
Name: policy.PolicyResourceName,
Labels: labels,
},

Expand Down
5 changes: 5 additions & 0 deletions internal/repository/policy.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ type IPolicyRepository interface {
FetchByClusterId(ctx context.Context, clusterId string, pg *pagination.Pagination) (out *[]model.Policy, err error)
FetchByClusterIdAndTemplaeId(ctx context.Context, clusterId string, templateId uuid.UUID) (out *[]model.Policy, err error)
ExistByName(ctx context.Context, organizationId string, policyName string) (exist bool, err error)
ExistByResourceName(ctx context.Context, organizationId string, policyName string) (exist bool, err error)
ExistByID(ctx context.Context, organizationId string, policyId uuid.UUID) (exist bool, err error)
GetByName(ctx context.Context, organizationId string, policyName string) (out *model.Policy, err error)
GetByID(ctx context.Context, organizationId string, policyId uuid.UUID) (out *model.Policy, err error)
Expand Down Expand Up @@ -150,6 +151,10 @@ func (r *PolicyRepository) ExistByName(ctx context.Context, organizationId strin
return r.ExistBy(ctx, organizationId, "policy_name", policyName)
}

func (r *PolicyRepository) ExistByResourceName(ctx context.Context, organizationId string, policyName string) (exist bool, err error) {
return r.ExistBy(ctx, organizationId, "policy_resource_name", policyName)
}

func (r *PolicyRepository) ExistByID(ctx context.Context, organizationId string, policyId uuid.UUID) (exist bool, err error) {
return r.ExistBy(ctx, organizationId, "id", policyId)
}
Expand Down
37 changes: 33 additions & 4 deletions internal/usecase/policy.go
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,12 @@ func NewPolicyUsecase(r repository.Repository) IPolicyUsecase {
}
}

func randomResouceName(kind string) string {
uuid := uuid.New().String()
idStr := strings.Split(uuid, "-")
return strings.ToLower(kind) + "-" + idStr[len(idStr)-1]
}

func (u *PolicyUsecase) Create(ctx context.Context, organizationId string, dto model.Policy) (policyId uuid.UUID, err error) {
dto.OrganizationId = organizationId

Expand All @@ -82,6 +88,19 @@ func (u *PolicyUsecase) Create(ctx context.Context, organizationId string, dto m
return uuid.Nil, httpErrors.NewBadRequestError(httpErrors.DuplicateResource, "PT_POlICY_TEMPLATE_NOT_FOUND", "policy template not found")
}

if len(dto.PolicyResourceName) == 0 {
dto.PolicyResourceName = randomResouceName(policyTemplate.Kind)
}

exists, err = u.repo.ExistByResourceName(ctx, dto.OrganizationId, dto.PolicyResourceName)
if err != nil {
return uuid.Nil, err
}

if exists {
return uuid.Nil, httpErrors.NewBadRequestError(httpErrors.DuplicateResource, "P_CREATE_ALREADY_EXISTED_RESOURCE_NAME", "policy resource name already exists")
}

dto.TargetClusters = make([]model.Cluster, len(dto.TargetClusterIds))
for i, clusterId := range dto.TargetClusterIds {

Expand Down Expand Up @@ -126,7 +145,12 @@ func (u *PolicyUsecase) Create(ctx context.Context, organizationId string, dto m
err = policytemplate.ApplyTksPolicyTemplateCR(ctx, organization.PrimaryClusterId, policyTemplateCR)

if err != nil {
log.Errorf(ctx, "error is :%s(%T)", err.Error(), err)
errYaml := ""
if policyCR != nil {
errYaml, _ = policyTemplateCR.YAML()
}

log.Errorf(ctx, "error is :%s(%T), policyTemplateCR='%+v'", err.Error(), err, errYaml)

return uuid.Nil, httpErrors.NewInternalServerError(err, "P_FAILED_TO_APPLY_KUBERNETES", "")
}
Expand All @@ -135,7 +159,12 @@ func (u *PolicyUsecase) Create(ctx context.Context, organizationId string, dto m
err = policytemplate.ApplyTksPolicyCR(ctx, organization.PrimaryClusterId, policyCR)

if err != nil {
log.Errorf(ctx, "error is :%s(%T)", err.Error(), err)
errYaml := ""
if policyCR != nil {
errYaml, _ = policyCR.YAML()
}

log.Errorf(ctx, "error is :%s(%T), policyCR='%+v'", err.Error(), err, errYaml)

return uuid.Nil, httpErrors.NewInternalServerError(err, "P_FAILED_TO_APPLY_KUBERNETES", "")
}
Expand Down Expand Up @@ -303,14 +332,14 @@ func (u *PolicyUsecase) Delete(ctx context.Context, organizationId string, polic
return httpErrors.NewBadRequestError(fmt.Errorf("invalid organizationId"), "C_INVALID_ORGANIZATION_ID", "")
}

exists, err := policytemplate.ExistsTksPolicyCR(ctx, organization.PrimaryClusterId, policy.PolicyName)
exists, err := policytemplate.ExistsTksPolicyCR(ctx, organization.PrimaryClusterId, policy.PolicyResourceName)
if err != nil {
log.Errorf(ctx, "failed to check TksPolicyCR: %v", err)
return httpErrors.NewInternalServerError(err, "P_FAILED_TO_APPLY_KUBERNETES", "")
}

if exists {
err = policytemplate.DeleteTksPolicyCR(ctx, organization.PrimaryClusterId, policy.PolicyName)
err = policytemplate.DeleteTksPolicyCR(ctx, organization.PrimaryClusterId, policy.PolicyResourceName)

if err != nil {
log.Errorf(ctx, "failed to delete TksPolicyCR: %v", err)
Expand Down
34 changes: 18 additions & 16 deletions pkg/domain/policy.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,29 +36,31 @@ type PolicyResponse struct {
TargetClusterIds []string `json:"targetClusterIds" example:"83bf8081-f0c5-4b31-826d-23f6f366ec90,83bf8081-f0c5-4b31-826d-23f6f366ec90"`
Mandatory bool `json:"mandatory"`

PolicyName string `json:"policyName" example:"label 정책"`
Description string `json:"description"`
TemplateId string `json:"templateId" example:"d98ef5f1-4a68-4047-a446-2207787ce3ff"`
TemplateName string `json:"templateName" example:"필수 Label 검사"`
EnforcementAction string `json:"enforcementAction" enum:"warn,deny,dryrun" example:"deny"`
Parameters string `json:"parameters" example:"{\"labels\":{\"key\":\"owner\",\"allowedRegex\":\"test*\"}"`
FilledParameters []*ParameterDef `json:"filledParameters"`
Match *Match `json:"match,omitempty"`
MatchYaml *string `json:"matchYaml,omitempty" example:"namespaces:\r\n- testns1"`
PolicyName string `json:"policyName" example:"label 정책"`
PolicyResourceName string `json:"policyResourceName,omitempty" example:"labelpolicy"`
Description string `json:"description"`
TemplateId string `json:"templateId" example:"d98ef5f1-4a68-4047-a446-2207787ce3ff"`
TemplateName string `json:"templateName" example:"필수 Label 검사"`
EnforcementAction string `json:"enforcementAction" enum:"warn,deny,dryrun" example:"deny"`
Parameters string `json:"parameters" example:"{\"key\":\"value\"}"`
FilledParameters []*ParameterDef `json:"filledParameters"`
Match *Match `json:"match,omitempty"`
MatchYaml *string `json:"matchYaml,omitempty" example:"namespaces:\r\n- testns1"`
//Tags []string `json:"tags,omitempty" example:"k8s,label"`
}

type CreatePolicyRequest struct {
TargetClusterIds []string `json:"targetClusterIds" example:"83bf8081-f0c5-4b31-826d-23f6f366ec90,83bf8081-f0c5-4b31-826d-23f6f366ec90"`
Mandatory bool `json:"mandatory"`

PolicyName string `json:"policyName" example:"label 정책"`
Description string `json:"description"`
TemplateId string `json:"templateId" example:"d98ef5f1-4a68-4047-a446-2207787ce3ff"`
EnforcementAction string `json:"enforcementAction" enum:"warn,deny,dryrun" example:"deny"`
Parameters string `json:"parameters" example:"{\"labels\":{\"key\":\"owner\",\"allowedRegex\":\"test*\"}"`
Match *Match `json:"match,omitempty"`
MatchYaml *string `json:"matchYaml,omitempty" example:"namespaces:\r\n- testns1"`
PolicyName string `json:"policyName" example:"label 정책"`
PolicyResourceName string `json:"policyResourceName,omitempty" example:"labelpolicy"`
Description string `json:"description"`
TemplateId string `json:"templateId" example:"d98ef5f1-4a68-4047-a446-2207787ce3ff"`
EnforcementAction string `json:"enforcementAction" enum:"warn,deny,dryrun" example:"deny"`
Parameters string `json:"parameters" example:"{\"key\":\"value\"}"`
Match *Match `json:"match,omitempty"`
MatchYaml *string `json:"matchYaml,omitempty" example:"namespaces:\r\n- testns1"`
//Tags []string `json:"tags,omitempty" example:"k8s,label"`
}

Expand Down
17 changes: 9 additions & 8 deletions pkg/httpErrors/errorCode.go
Original file line number Diff line number Diff line change
Expand Up @@ -129,14 +129,15 @@ var errorMap = map[ErrorCode]string{
"PT_NOT_PERMITTED_ON_TKS_POLICY_TEMPLATE": "tks 템플릿에 대해 해당 동작을 수행할 수 없습니다.",

// Policy
"P_CREATE_ALREADY_EXISTED_NAME": "정첵에 이미 존재하는 이름입니다.",
"P_NOT_FOUND_POLICY": "정책이 존재하지 않습니다.",
"P_INVALID_POLICY_NAME": "유효하지 않은 정책 이름입니다. 정책 이름을 확인하세요.",
"P_INVALID_MATCH": "유효하지 않은 match 설정입니다. match 설정을 확인하세요.",
"P_FAILED_FETCH_POLICY": "정책 ID에 해당하는 정책을 가져오는데 실패했습니다.",
"P_FAILED_FETCH_CLUSTER": "정책의 클러스터 정보를 가져오는데 실패했습니다.",
"P_CALL_TO_APPLY_KUBERNETES": "쿠버네티스 클러스터 호출에 실패했습니다.",
"P_FAILED_TO_APPLY_KUBERNETES": "쿠버네티스 클러스터 변경사항 적용에 실패했습니다.",
"P_CREATE_ALREADY_EXISTED_NAME": "정첵에 이미 존재하는 이름입니다.",
"P_NOT_FOUND_POLICY": "정책이 존재하지 않습니다.",
"P_INVALID_POLICY_NAME": "유효하지 않은 정책 이름입니다. 정책 이름을 확인하세요.",
"P_CREATE_ALREADY_EXISTED_RESOURCE_NAME": "유효하지 않은 정책 자원 이름(k8s 자원 이름)입니다. 정책 자원 이름을 확인하세요.",
"P_INVALID_MATCH": "유효하지 않은 match 설정입니다. match 설정을 확인하세요.",
"P_FAILED_FETCH_POLICY": "정책 ID에 해당하는 정책을 가져오는데 실패했습니다.",
"P_FAILED_FETCH_CLUSTER": "정책의 클러스터 정보를 가져오는데 실패했습니다.",
"P_CALL_TO_APPLY_KUBERNETES": "쿠버네티스 클러스터 호출에 실패했습니다.",
"P_FAILED_TO_APPLY_KUBERNETES": "쿠버네티스 클러스터 변경사항 적용에 실패했습니다.",
}

func (m ErrorCode) GetText() string {
Expand Down
Loading