From 19566601ecb7e503acb578295096a98f82e088a3 Mon Sep 17 00:00:00 2001 From: Seungkyu Ahn Date: Thu, 14 Mar 2024 13:31:35 +0900 Subject: [PATCH] Revert "Merge pull request #277 from seungkyua/20240314_revert" This reverts commit 3c1aa54a7124eb2a06e12647bdd8d6289682157b, reversing changes made to 92dc48e12cba948799c857fd600b1ecf8f61d90e. --- api/swagger/docs.go | 1362 ++++++++--------- api/swagger/swagger.json | 1362 ++++++++--------- api/swagger/swagger.yaml | 837 +++++----- internal/database/database.go | 63 +- internal/delivery/api/endpoint.go | 4 +- .../delivery/api/generated_endpoints.go.go | 16 + internal/delivery/http/alert.go | 3 +- internal/delivery/http/app-group.go | 5 +- internal/delivery/http/app-serve-app.go | 51 +- internal/delivery/http/audit.go | 17 +- internal/delivery/http/auth.go | 5 +- internal/delivery/http/cloud-account.go | 13 +- internal/delivery/http/cluster.go | 34 +- internal/delivery/http/handler.go | 2 + internal/delivery/http/organization.go | 14 +- internal/delivery/http/permission.go | 57 +- internal/delivery/http/policy-template.go | 3 +- internal/delivery/http/role.go | 10 +- internal/delivery/http/stack-template.go | 127 +- internal/delivery/http/stack.go | 15 +- internal/delivery/http/user.go | 21 +- internal/filter/settings.go | 2 + internal/keycloak/keycloak.go | 34 +- internal/middleware/audit/audit-map.go | 88 +- internal/middleware/audit/audit.go | 4 +- internal/model/alert.go | 60 + internal/model/app-group.go | 47 + internal/model/app-serve-app.go | 67 + internal/model/audit.go | 26 + internal/model/cloud-account.go | 38 + internal/model/cluster.go | 84 + internal/model/dashboard.go | 4 + internal/model/end-point.go | 11 + internal/model/organization.go | 21 + internal/model/permission.go | 615 ++++++++ internal/model/policy-template.go | 48 + internal/model/role.go | 27 + internal/model/stack-template.go | 40 + internal/model/stack.go | 45 + internal/model/user.go | 34 + internal/pagination/pagination.go | 14 +- internal/repository/alert.go | 143 +- internal/repository/app-group.go | 127 +- internal/repository/app-serve-app.go | 63 +- internal/repository/audit.go | 63 +- internal/repository/cloud-account.go | 103 +- internal/repository/cluster.go | 183 +-- internal/repository/endpoint.go | 27 +- internal/repository/organization.go | 73 +- internal/repository/permission.go | 26 +- internal/repository/policy-template.go | 135 +- internal/repository/role.go | 51 +- internal/repository/stack-template.go | 117 +- internal/repository/user.go | 104 +- internal/route/route.go | 10 +- internal/serializer/serializer.go | 18 +- internal/usecase/alert.go | 42 +- internal/usecase/app-group.go | 23 +- internal/usecase/app-serve-app.go | 33 +- internal/usecase/audit.go | 22 +- internal/usecase/auth.go | 17 +- internal/usecase/cloud-account.go | 51 +- internal/usecase/cluster.go | 58 +- internal/usecase/dashboard.go | 5 +- internal/usecase/organization.go | 23 +- internal/usecase/permission.go | 54 +- internal/usecase/policy-template.go | 45 +- internal/usecase/role.go | 22 +- internal/usecase/stack-template.go | 44 +- internal/usecase/stack.go | 37 +- internal/usecase/user.go | 50 +- pkg/domain/admin/user.go | 45 +- pkg/domain/alert.go | 44 - pkg/domain/app-group.go | 27 - pkg/domain/app-serve-app.go | 119 +- pkg/domain/audit.go | 18 - pkg/domain/auth.go | 14 +- pkg/domain/cloud-account.go | 30 +- pkg/domain/cluster.go | 30 +- pkg/domain/dashboard.go | 16 +- pkg/domain/endpoint.go | 13 +- pkg/domain/mapper.go | 140 -- pkg/domain/mapper_test.go | 117 -- pkg/domain/organization.go | 14 +- pkg/domain/permission.go | 629 +------- pkg/domain/policy-template.go | 2 + pkg/domain/project.go | 23 +- pkg/domain/role.go | 31 +- pkg/domain/stack-template.go | 27 - pkg/domain/stack.go | 53 +- pkg/domain/user.go | 181 +-- 91 files changed, 4143 insertions(+), 4529 deletions(-) create mode 100644 internal/model/alert.go create mode 100644 internal/model/app-group.go create mode 100644 internal/model/app-serve-app.go create mode 100644 internal/model/audit.go create mode 100644 internal/model/cloud-account.go create mode 100644 internal/model/cluster.go create mode 100644 internal/model/dashboard.go create mode 100644 internal/model/end-point.go create mode 100644 internal/model/organization.go create mode 100644 internal/model/permission.go create mode 100644 internal/model/policy-template.go create mode 100644 internal/model/role.go create mode 100644 internal/model/stack-template.go create mode 100644 internal/model/stack.go create mode 100644 internal/model/user.go delete mode 100644 pkg/domain/mapper.go delete mode 100644 pkg/domain/mapper_test.go diff --git a/api/swagger/docs.go b/api/swagger/docs.go index 4464bf58..4a544877 100644 --- a/api/swagger/docs.go +++ b/api/swagger/docs.go @@ -22,6 +22,186 @@ const docTemplate = `{ "host": "{{.Host}}", "basePath": "{{.BasePath}}", "paths": { + "/admin/audits": { + "get": { + "security": [ + { + "JWT": [] + } + ], + "description": "Get Audits", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Audits" + ], + "summary": "Get Audits", + "parameters": [ + { + "type": "string", + "description": "pageSize", + "name": "limit", + "in": "query" + }, + { + "type": "string", + "description": "pageNumber", + "name": "page", + "in": "query" + }, + { + "type": "string", + "description": "sortColumn", + "name": "soertColumn", + "in": "query" + }, + { + "type": "string", + "description": "sortOrder", + "name": "sortOrder", + "in": "query" + }, + { + "type": "array", + "items": { + "type": "string" + }, + "collectionFormat": "csv", + "description": "filters", + "name": "filter", + "in": "query" + }, + { + "type": "array", + "items": { + "type": "string" + }, + "collectionFormat": "csv", + "description": "filters", + "name": "or", + "in": "query" + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.GetAuditsResponse" + } + } + } + }, + "post": { + "security": [ + { + "JWT": [] + } + ], + "description": "Create Audit", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Audits" + ], + "summary": "Create Audit", + "parameters": [ + { + "description": "create audit request", + "name": "body", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.CreateAuditRequest" + } + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.CreateAuditResponse" + } + } + } + } + }, + "/admin/audits/{auditId}": { + "get": { + "security": [ + { + "JWT": [] + } + ], + "description": "Get Audit", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Audits" + ], + "summary": "Get Audit", + "parameters": [ + { + "type": "string", + "description": "auditId", + "name": "auditId", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.GetAuditResponse" + } + } + } + }, + "delete": { + "security": [ + { + "JWT": [] + } + ], + "description": "Delete Audit", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Audits" + ], + "summary": "Delete Audit 'NOT IMPLEMENTED'", + "parameters": [ + { + "type": "string", + "description": "auditId", + "name": "auditId", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "OK" + } + } + } + }, "/admin/organizations/{organizationId}/projects": { "get": { "security": [ @@ -816,7 +996,7 @@ const docTemplate = `{ "tags": [ "StackTemplates" ], - "summary": "Create StackTemplate 'NOT IMPLEMENTED'", + "summary": "Create StackTemplate", "parameters": [ { "description": "create stack template request", @@ -918,7 +1098,7 @@ const docTemplate = `{ "tags": [ "StackTemplates" ], - "summary": "Update StackTemplate 'NOT IMPLEMENTED'", + "summary": "Update StackTemplate", "parameters": [ { "description": "Update stack template request", @@ -952,7 +1132,7 @@ const docTemplate = `{ "tags": [ "StackTemplates" ], - "summary": "Delete StackTemplate 'NOT IMPLEMENTED'", + "summary": "Delete StackTemplate", "parameters": [ { "type": "string", @@ -1688,7 +1868,7 @@ const docTemplate = `{ "200": { "description": "OK", "schema": { - "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.Cluster" + "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.GetClusterResponse" } } } @@ -1721,10 +1901,7 @@ const docTemplate = `{ ], "responses": { "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.Cluster" - } + "description": "OK" } } } @@ -2105,7 +2282,7 @@ const docTemplate = `{ "200": { "description": "OK", "schema": { - "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.Organization" + "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.DeleteOrganizationResponse" } } } @@ -2340,14 +2517,14 @@ const docTemplate = `{ } } }, - "/organizations/{organizationId}/audits": { + "/organizations/{organizationId}/cloud-accounts": { "get": { "security": [ { "JWT": [] } ], - "description": "Get Audits", + "description": "Get CloudAccounts", "consumes": [ "application/json" ], @@ -2355,10 +2532,17 @@ const docTemplate = `{ "application/json" ], "tags": [ - "Audits" + "CloudAccounts" ], - "summary": "Get Audits", + "summary": "Get CloudAccounts", "parameters": [ + { + "type": "string", + "description": "organizationId", + "name": "organizationId", + "in": "path", + "required": true + }, { "type": "string", "description": "pageSize", @@ -2390,17 +2574,7 @@ const docTemplate = `{ }, "collectionFormat": "csv", "description": "filters", - "name": "filter", - "in": "query" - }, - { - "type": "array", - "items": { - "type": "string" - }, - "collectionFormat": "csv", - "description": "filters", - "name": "or", + "name": "filters", "in": "query" } ], @@ -2408,7 +2582,7 @@ const docTemplate = `{ "200": { "description": "OK", "schema": { - "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.GetAuditsResponse" + "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.GetCloudAccountsResponse" } } } @@ -2419,7 +2593,7 @@ const docTemplate = `{ "JWT": [] } ], - "description": "Create Audit", + "description": "Create CloudAccount", "consumes": [ "application/json" ], @@ -2427,17 +2601,24 @@ const docTemplate = `{ "application/json" ], "tags": [ - "Audits" + "CloudAccounts" ], - "summary": "Create Audit", + "summary": "Create CloudAccount", "parameters": [ { - "description": "create audit request", + "type": "string", + "description": "organizationId", + "name": "organizationId", + "in": "path", + "required": true + }, + { + "description": "create cloud setting request", "name": "body", "in": "body", "required": true, "schema": { - "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.CreateAuditRequest" + "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.CreateCloudAccountRequest" } } ], @@ -2445,20 +2626,20 @@ const docTemplate = `{ "200": { "description": "OK", "schema": { - "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.CreateAuditResponse" + "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.CreateCloudAccountResponse" } } } } }, - "/organizations/{organizationId}/audits/{auditId}": { + "/organizations/{organizationId}/cloud-accounts/aws-account-id/{awsAccountId}/existence": { "get": { "security": [ { "JWT": [] } ], - "description": "Get Audit", + "description": "Check awsAccountId for cloudAccount", "consumes": [ "application/json" ], @@ -2466,14 +2647,21 @@ const docTemplate = `{ "application/json" ], "tags": [ - "Audits" + "CloudAccounts" ], - "summary": "Get Audit", + "summary": "Check awsAccountId for cloudAccount", "parameters": [ { "type": "string", - "description": "auditId", - "name": "auditId", + "description": "organizationId", + "name": "organizationId", + "in": "path", + "required": true + }, + { + "type": "string", + "description": "awsAccountId", + "name": "awsAccountId", "in": "path", "required": true } @@ -2482,205 +2670,14 @@ const docTemplate = `{ "200": { "description": "OK", "schema": { - "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.GetAuditResponse" + "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.CheckCloudAccountAwsAccountIdResponse" } } } - }, - "delete": { - "security": [ - { - "JWT": [] - } - ], - "description": "Delete Audit", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "Audits" - ], - "summary": "Delete Audit 'NOT IMPLEMENTED'", - "parameters": [ - { - "type": "string", - "description": "auditId", - "name": "auditId", - "in": "path", - "required": true - } - ], - "responses": { - "200": { - "description": "OK" - } - } - } - }, - "/organizations/{organizationId}/cloud-accounts": { - "get": { - "security": [ - { - "JWT": [] - } - ], - "description": "Get CloudAccounts", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "CloudAccounts" - ], - "summary": "Get CloudAccounts", - "parameters": [ - { - "type": "string", - "description": "organizationId", - "name": "organizationId", - "in": "path", - "required": true - }, - { - "type": "string", - "description": "pageSize", - "name": "limit", - "in": "query" - }, - { - "type": "string", - "description": "pageNumber", - "name": "page", - "in": "query" - }, - { - "type": "string", - "description": "sortColumn", - "name": "soertColumn", - "in": "query" - }, - { - "type": "string", - "description": "sortOrder", - "name": "sortOrder", - "in": "query" - }, - { - "type": "array", - "items": { - "type": "string" - }, - "collectionFormat": "csv", - "description": "filters", - "name": "filters", - "in": "query" - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.GetCloudAccountsResponse" - } - } - } - }, - "post": { - "security": [ - { - "JWT": [] - } - ], - "description": "Create CloudAccount", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "CloudAccounts" - ], - "summary": "Create CloudAccount", - "parameters": [ - { - "type": "string", - "description": "organizationId", - "name": "organizationId", - "in": "path", - "required": true - }, - { - "description": "create cloud setting request", - "name": "body", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.CreateCloudAccountRequest" - } - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.CreateCloudAccountResponse" - } - } - } - } - }, - "/organizations/{organizationId}/cloud-accounts/aws-account-id/{awsAccountId}/existence": { - "get": { - "security": [ - { - "JWT": [] - } - ], - "description": "Check awsAccountId for cloudAccount", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "CloudAccounts" - ], - "summary": "Check awsAccountId for cloudAccount", - "parameters": [ - { - "type": "string", - "description": "organizationId", - "name": "organizationId", - "in": "path", - "required": true - }, - { - "type": "string", - "description": "awsAccountId", - "name": "awsAccountId", - "in": "path", - "required": true - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.CheckCloudAccountAwsAccountIdResponse" - } - } - } - } - }, - "/organizations/{organizationId}/cloud-accounts/name/{name}/existence": { - "get": { + } + }, + "/organizations/{organizationId}/cloud-accounts/name/{name}/existence": { + "get": { "security": [ { "JWT": [] @@ -3771,7 +3768,7 @@ const docTemplate = `{ "schema": { "type": "array", "items": { - "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.AppServeApp" + "$ref": "#/definitions/github_com_openinfradev_tks-api_internal_model.AppServeApp" } } } @@ -4438,7 +4435,7 @@ const docTemplate = `{ "schema": { "type": "array", "items": { - "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.AppServeApp" + "$ref": "#/definitions/github_com_openinfradev_tks-api_internal_model.AppServeApp" } } } @@ -5627,7 +5624,7 @@ const docTemplate = `{ "200": { "description": "OK", "schema": { - "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.PermissionSet" + "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.PermissionSetResponse" } } } @@ -5674,14 +5671,14 @@ const docTemplate = `{ } } }, - "/organizations/{organizationId}/stacks": { + "/organizations/{organizationId}/stack-templates": { "get": { "security": [ { "JWT": [] } ], - "description": "Get Stacks", + "description": "Get Organization StackTemplates", "consumes": [ "application/json" ], @@ -5689,17 +5686,10 @@ const docTemplate = `{ "application/json" ], "tags": [ - "Stacks" + "StackTemplates" ], - "summary": "Get Stacks", + "summary": "Get Organization StackTemplates", "parameters": [ - { - "type": "string", - "description": "organizationId", - "name": "organizationId", - "in": "path", - "required": true - }, { "type": "string", "description": "pageSize", @@ -5725,9 +5715,13 @@ const docTemplate = `{ "in": "query" }, { - "type": "string", - "description": "combinedFilter", - "name": "combinedFilter", + "type": "array", + "items": { + "type": "string" + }, + "collectionFormat": "csv", + "description": "filters", + "name": "filters", "in": "query" } ], @@ -5735,18 +5729,20 @@ const docTemplate = `{ "200": { "description": "OK", "schema": { - "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.GetStacksResponse" + "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.GetStackTemplatesResponse" } } } - }, - "post": { + } + }, + "/organizations/{organizationId}/stack-templates/{stackTemplateId}": { + "get": { "security": [ { "JWT": [] } ], - "description": "Create Stack", + "description": "Get Organization StackTemplate", "consumes": [ "application/json" ], @@ -5754,45 +5750,27 @@ const docTemplate = `{ "application/json" ], "tags": [ - "Stacks" - ], - "summary": "Create Stack", - "parameters": [ - { - "type": "string", - "description": "organizationId", - "name": "organizationId", - "in": "path", - "required": true - }, - { - "description": "create cloud setting request", - "name": "body", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.CreateStackRequest" - } - } + "StackTemplates" ], + "summary": "Get Organization StackTemplate", "responses": { "200": { "description": "OK", "schema": { - "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.CreateStackResponse" + "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.GetStackTemplateResponse" } } } } }, - "/organizations/{organizationId}/stacks/name/{name}/existence": { + "/organizations/{organizationId}/stacks": { "get": { "security": [ { "JWT": [] } ], - "description": "Check name for stack", + "description": "Get Stacks", "consumes": [ "application/json" ], @@ -5802,7 +5780,7 @@ const docTemplate = `{ "tags": [ "Stacks" ], - "summary": "Check name for stack", + "summary": "Get Stacks", "parameters": [ { "type": "string", @@ -5813,11 +5791,122 @@ const docTemplate = `{ }, { "type": "string", - "description": "stackId", - "name": "stackId", - "in": "path", - "required": true - }, + "description": "pageSize", + "name": "limit", + "in": "query" + }, + { + "type": "string", + "description": "pageNumber", + "name": "page", + "in": "query" + }, + { + "type": "string", + "description": "sortColumn", + "name": "soertColumn", + "in": "query" + }, + { + "type": "string", + "description": "sortOrder", + "name": "sortOrder", + "in": "query" + }, + { + "type": "string", + "description": "combinedFilter", + "name": "combinedFilter", + "in": "query" + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.GetStacksResponse" + } + } + } + }, + "post": { + "security": [ + { + "JWT": [] + } + ], + "description": "Create Stack", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Stacks" + ], + "summary": "Create Stack", + "parameters": [ + { + "type": "string", + "description": "organizationId", + "name": "organizationId", + "in": "path", + "required": true + }, + { + "description": "create cloud setting request", + "name": "body", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.CreateStackRequest" + } + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.CreateStackResponse" + } + } + } + } + }, + "/organizations/{organizationId}/stacks/name/{name}/existence": { + "get": { + "security": [ + { + "JWT": [] + } + ], + "description": "Check name for stack", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Stacks" + ], + "summary": "Check name for stack", + "parameters": [ + { + "type": "string", + "description": "organizationId", + "name": "organizationId", + "in": "path", + "required": true + }, + { + "type": "string", + "description": "stackId", + "name": "stackId", + "in": "path", + "required": true + }, { "type": "string", "description": "name", @@ -6461,10 +6550,7 @@ const docTemplate = `{ ], "responses": { "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.User" - } + "description": "OK" } } } @@ -6532,7 +6618,7 @@ const docTemplate = `{ "200": { "description": "OK", "schema": { - "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.PermissionSet" + "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.PermissionSetResponse" } } } @@ -6620,6 +6706,177 @@ const docTemplate = `{ } }, "definitions": { + "github_com_openinfradev_tks-api_internal_model.AppServeApp": { + "type": "object", + "properties": { + "appServeAppTasks": { + "type": "array", + "items": { + "$ref": "#/definitions/github_com_openinfradev_tks-api_internal_model.AppServeAppTask" + } + }, + "appType": { + "description": "appType (spring/springboot)", + "type": "string" + }, + "createdAt": { + "type": "string" + }, + "deletedAt": { + "type": "string" + }, + "endpointUrl": { + "description": "endpoint URL of deployed app", + "type": "string" + }, + "grafanaUrl": { + "description": "grafana dashboard URL for deployed app", + "type": "string" + }, + "id": { + "type": "string" + }, + "name": { + "description": "application name", + "type": "string" + }, + "namespace": { + "description": "application namespace", + "type": "string" + }, + "organizationId": { + "description": "contractId is a contract ID which this app belongs to", + "type": "string" + }, + "previewEndpointUrl": { + "description": "preview svc endpoint URL in B/G deployment", + "type": "string" + }, + "projectId": { + "description": "project ID which this app belongs to", + "type": "string" + }, + "status": { + "description": "status is status of deployed app", + "type": "string" + }, + "targetClusterId": { + "description": "target cluster to which the app is deployed", + "type": "string" + }, + "targetClusterName": { + "description": "target cluster name", + "type": "string" + }, + "type": { + "description": "type (build/deploy/all)", + "type": "string" + }, + "updatedAt": { + "type": "string" + } + } + }, + "github_com_openinfradev_tks-api_internal_model.AppServeAppTask": { + "type": "object", + "properties": { + "appConfig": { + "description": "java app config", + "type": "string" + }, + "appSecret": { + "description": "java app secret", + "type": "string" + }, + "appServeAppId": { + "description": "ID for appServeApp that this task belongs to", + "type": "string" + }, + "artifactUrl": { + "description": "URL of java app artifact (Eg, Jar)", + "type": "string" + }, + "availableRollback": { + "type": "boolean" + }, + "createdAt": { + "description": "createdAt is a creation timestamp for the application", + "type": "string" + }, + "deletedAt": { + "type": "string" + }, + "executablePath": { + "description": "Executable path of app image", + "type": "string" + }, + "extraEnv": { + "description": "env variable list for java app", + "type": "string" + }, + "helmRevision": { + "description": "revision of deployed helm release", + "type": "integer" + }, + "id": { + "type": "string" + }, + "imageUrl": { + "description": "URL of built image for app", + "type": "string" + }, + "output": { + "description": "output for task result", + "type": "string" + }, + "port": { + "description": "java app port", + "type": "string" + }, + "profile": { + "description": "java app profile", + "type": "string" + }, + "pvAccessMode": { + "type": "string" + }, + "pvEnabled": { + "type": "boolean" + }, + "pvMountPath": { + "type": "string" + }, + "pvSize": { + "type": "string" + }, + "pvStorageClass": { + "type": "string" + }, + "resourceSpec": { + "description": "resource spec of app pod", + "type": "string" + }, + "rollbackVersion": { + "description": "rollback target version", + "type": "string" + }, + "status": { + "description": "status is app status", + "type": "string" + }, + "strategy": { + "description": "deployment strategy (eg, rolling-update)", + "type": "string" + }, + "updatedAt": { + "type": "string" + }, + "version": { + "description": "application version", + "type": "string" + } + } + }, "github_com_openinfradev_tks-api_pkg_domain.ActionResponse": { "type": "object", "properties": { @@ -6828,13 +7085,13 @@ const docTemplate = `{ "AppGroupType_SERVICE_MESH" ] }, - "github_com_openinfradev_tks-api_pkg_domain.AppServeApp": { + "github_com_openinfradev_tks-api_pkg_domain.AppServeAppResponse": { "type": "object", "properties": { "appServeAppTasks": { "type": "array", "items": { - "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.AppServeAppTask" + "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.AppServeAppTaskResponse" } }, "appType": { @@ -6899,7 +7156,7 @@ const docTemplate = `{ } } }, - "github_com_openinfradev_tks-api_pkg_domain.AppServeAppTask": { + "github_com_openinfradev_tks-api_pkg_domain.AppServeAppTaskResponse": { "type": "object", "properties": { "appConfig": { @@ -7086,9 +7343,6 @@ const docTemplate = `{ }, "user": { "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.SimpleUserResponse" - }, - "userId": { - "type": "string" } } }, @@ -7158,71 +7412,6 @@ const docTemplate = `{ } } }, - "github_com_openinfradev_tks-api_pkg_domain.CloudAccount": { - "type": "object", - "properties": { - "accessKeyId": { - "type": "string" - }, - "awsAccountId": { - "type": "string" - }, - "cloudService": { - "type": "string" - }, - "clusters": { - "type": "integer" - }, - "createdAt": { - "type": "string" - }, - "createdIAM": { - "type": "boolean" - }, - "creator": { - "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.User" - }, - "creatorId": { - "type": "string" - }, - "description": { - "type": "string" - }, - "id": { - "type": "string" - }, - "name": { - "type": "string" - }, - "organizationId": { - "type": "string" - }, - "resource": { - "type": "string" - }, - "secretAccessKey": { - "type": "string" - }, - "sessionToken": { - "type": "string" - }, - "status": { - "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.CloudAccountStatus" - }, - "statusDesc": { - "type": "string" - }, - "updatedAt": { - "type": "string" - }, - "updator": { - "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.User" - }, - "updatorId": { - "type": "string" - } - } - }, "github_com_openinfradev_tks-api_pkg_domain.CloudAccountResponse": { "type": "object", "properties": { @@ -7241,165 +7430,32 @@ const docTemplate = `{ "createdIAM": { "type": "boolean" }, - "creator": { - "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.SimpleUserResponse" - }, - "description": { - "type": "string" - }, - "id": { - "type": "string" - }, - "name": { - "type": "string" - }, - "organizationId": { - "type": "string" - }, - "resource": { - "type": "string" - }, - "status": { - "type": "string" - }, - "updatedAt": { - "type": "string" - }, - "updator": { - "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.SimpleUserResponse" - } - } - }, - "github_com_openinfradev_tks-api_pkg_domain.CloudAccountStatus": { - "type": "integer", - "enum": [ - 0, - 1, - 2, - 3, - 4, - 5, - 6 - ], - "x-enum-varnames": [ - "CloudAccountStatus_PENDING", - "CloudAccountStatus_CREATING", - "CloudAccountStatus_CREATED", - "CloudAccountStatus_DELETING", - "CloudAccountStatus_DELETED", - "CloudAccountStatus_CREATE_ERROR", - "CloudAccountStatus_DELETE_ERROR" - ] - }, - "github_com_openinfradev_tks-api_pkg_domain.Cluster": { - "type": "object", - "properties": { - "byoClusterEndpointHost": { - "type": "string" - }, - "byoClusterEndpointPort": { - "type": "integer" - }, - "cloudAccount": { - "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.CloudAccount" - }, - "cloudAccountId": { - "type": "string" - }, - "cloudService": { - "type": "string" - }, - "clusterType": { - "type": "integer" - }, - "conf": { - "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.ClusterConf" - }, - "createdAt": { - "type": "string" - }, - "creator": { - "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.User" - }, - "creatorId": { - "type": "string" + "creator": { + "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.SimpleUserResponse" }, "description": { "type": "string" }, - "favorited": { - "type": "boolean" - }, "id": { "type": "string" }, - "isStack": { - "type": "boolean" - }, - "kubeconfig": { - "type": "array", - "items": { - "type": "integer" - } - }, "name": { "type": "string" }, "organizationId": { "type": "string" }, - "stackTemplate": { - "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.StackTemplate" - }, - "stackTemplateId": { + "resource": { "type": "string" }, "status": { - "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.ClusterStatus" - }, - "statusDesc": { "type": "string" }, "updatedAt": { "type": "string" }, "updator": { - "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.User" - }, - "updatorId": { - "type": "string" - } - } - }, - "github_com_openinfradev_tks-api_pkg_domain.ClusterConf": { - "type": "object", - "properties": { - "tksCpNode": { - "type": "integer" - }, - "tksCpNodeMax": { - "type": "integer" - }, - "tksCpNodeType": { - "type": "string" - }, - "tksInfraNode": { - "type": "integer" - }, - "tksInfraNodeMax": { - "type": "integer" - }, - "tksInfraNodeType": { - "type": "string" - }, - "tksUserNode": { - "type": "integer" - }, - "tksUserNodeMax": { - "type": "integer" - }, - "tksUserNodeType": { - "type": "string" + "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.SimpleUserResponse" } } }, @@ -7508,6 +7564,9 @@ const docTemplate = `{ "description": { "type": "string" }, + "favorited": { + "type": "boolean" + }, "id": { "type": "string" }, @@ -7584,33 +7643,6 @@ const docTemplate = `{ } } }, - "github_com_openinfradev_tks-api_pkg_domain.ClusterStatus": { - "type": "integer", - "enum": [ - 0, - 1, - 2, - 3, - 4, - 5, - 6, - 7, - 8, - 9 - ], - "x-enum-varnames": [ - "ClusterStatus_PENDING", - "ClusterStatus_INSTALLING", - "ClusterStatus_RUNNING", - "ClusterStatus_DELETING", - "ClusterStatus_DELETED", - "ClusterStatus_INSTALL_ERROR", - "ClusterStatus_DELETE_ERROR", - "ClusterStatus_BOOTSTRAPPING", - "ClusterStatus_BOOTSTRAPPED", - "ClusterStatus_BOOTSTRAP_ERROR" - ] - }, "github_com_openinfradev_tks-api_pkg_domain.CommonProjectResponse": { "type": "object", "properties": { @@ -8306,10 +8338,10 @@ const docTemplate = `{ "type": "string" }, "organization": { - "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.Organization" + "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.OrganizationResponse" }, "role": { - "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.Role" + "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.RoleResponse" } } } @@ -8425,7 +8457,15 @@ const docTemplate = `{ } } }, - "github_com_openinfradev_tks-api_pkg_domain.Endpoint": { + "github_com_openinfradev_tks-api_pkg_domain.DeleteOrganizationResponse": { + "type": "object", + "properties": { + "id": { + "type": "string" + } + } + }, + "github_com_openinfradev_tks-api_pkg_domain.EndpointResponse": { "type": "object", "properties": { "createdAt": { @@ -8436,6 +8476,9 @@ const docTemplate = `{ }, "name": { "type": "string" + }, + "updatedAt": { + "type": "string" } } }, @@ -8568,7 +8611,7 @@ const docTemplate = `{ "type": "object", "properties": { "appServeApp": { - "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.AppServeApp" + "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.AppServeAppResponse" }, "stages": { "type": "array", @@ -8582,10 +8625,10 @@ const docTemplate = `{ "type": "object", "properties": { "appServeApp": { - "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.AppServeApp" + "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.AppServeAppResponse" }, "appServeAppTask": { - "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.AppServeAppTask" + "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.AppServeAppTaskResponse" }, "stages": { "type": "array", @@ -8680,6 +8723,14 @@ const docTemplate = `{ } } }, + "github_com_openinfradev_tks-api_pkg_domain.GetClusterResponse": { + "type": "object", + "properties": { + "cluster": { + "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.ClusterResponse" + } + } + }, "github_com_openinfradev_tks-api_pkg_domain.GetClustersResponse": { "type": "object", "properties": { @@ -8754,10 +8805,10 @@ const docTemplate = `{ "type": "string" }, "organization": { - "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.Organization" + "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.OrganizationResponse" }, "role": { - "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.Role" + "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.RoleResponse" } } } @@ -9087,10 +9138,10 @@ const docTemplate = `{ "type": "string" }, "organization": { - "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.Organization" + "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.OrganizationResponse" }, "role": { - "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.Role" + "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.RoleResponse" }, "updatedAt": { "type": "string" @@ -9253,10 +9304,10 @@ const docTemplate = `{ "type": "string" }, "organization": { - "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.Organization" + "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.OrganizationResponse" }, "role": { - "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.Role" + "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.RoleResponse" }, "updatedAt": { "type": "string" @@ -9298,13 +9349,13 @@ const docTemplate = `{ "type": "string" }, "organization": { - "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.Organization" + "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.OrganizationResponse" }, "passwordExpired": { "type": "boolean" }, "role": { - "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.Role" + "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.RoleResponse" }, "token": { "type": "string" @@ -9327,18 +9378,12 @@ const docTemplate = `{ } } }, - "github_com_openinfradev_tks-api_pkg_domain.Organization": { + "github_com_openinfradev_tks-api_pkg_domain.OrganizationResponse": { "type": "object", "properties": { "createdAt": { "type": "string" }, - "creator": { - "type": "string" - }, - "deletedAt": { - "$ref": "#/definitions/gorm.DeletedAt" - }, "description": { "type": "string" }, @@ -9440,7 +9485,7 @@ const docTemplate = `{ } } }, - "github_com_openinfradev_tks-api_pkg_domain.Permission": { + "github_com_openinfradev_tks-api_pkg_domain.PermissionResponse": { "type": "object", "properties": { "ID": { @@ -9449,24 +9494,15 @@ const docTemplate = `{ "children": { "type": "array", "items": { - "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.Permission" + "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.PermissionResponse" } }, - "createdAt": { - "type": "string" - }, - "deletedAt": { - "$ref": "#/definitions/gorm.DeletedAt" - }, "endpoints": { "type": "array", "items": { - "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.Endpoint" + "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.EndpointResponse" } }, - "id": { - "type": "integer" - }, "is_allowed": { "type": "boolean" }, @@ -9474,42 +9510,39 @@ const docTemplate = `{ "type": "string" }, "parent": { - "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.Permission" + "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.PermissionResponse" }, "parent_id": { "type": "string" }, "role": { - "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.Role" + "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.RoleResponse" }, "role_id": { "type": "string" - }, - "updatedAt": { - "type": "string" } } }, - "github_com_openinfradev_tks-api_pkg_domain.PermissionSet": { + "github_com_openinfradev_tks-api_pkg_domain.PermissionSetResponse": { "type": "object", "properties": { "configuration": { - "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.Permission" + "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.PermissionResponse" }, "dashboard": { - "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.Permission" + "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.PermissionResponse" }, "notification": { - "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.Permission" + "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.PermissionResponse" }, "project_management": { - "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.Permission" + "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.PermissionResponse" }, "security_policy": { - "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.Permission" + "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.PermissionResponse" }, "stack": { - "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.Permission" + "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.PermissionResponse" } } }, @@ -9861,6 +9894,9 @@ const docTemplate = `{ }, "projectRoleName": { "type": "string" + }, + "updatedAt": { + "type": "string" } } }, @@ -9982,7 +10018,7 @@ const docTemplate = `{ } } }, - "github_com_openinfradev_tks-api_pkg_domain.Role": { + "github_com_openinfradev_tks-api_pkg_domain.RoleResponse": { "type": "object", "properties": { "createdAt": { @@ -9991,9 +10027,6 @@ const docTemplate = `{ "creator": { "type": "string" }, - "deletedAt": { - "$ref": "#/definitions/gorm.DeletedAt" - }, "description": { "type": "string" }, @@ -10004,7 +10037,7 @@ const docTemplate = `{ "type": "string" }, "organization": { - "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.Organization" + "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.OrganizationResponse" }, "organizationId": { "type": "string" @@ -10082,20 +10115,6 @@ const docTemplate = `{ } } }, - "github_com_openinfradev_tks-api_pkg_domain.SimpleRoleResponse": { - "type": "object", - "properties": { - "description": { - "type": "string" - }, - "id": { - "type": "string" - }, - "name": { - "type": "string" - } - } - }, "github_com_openinfradev_tks-api_pkg_domain.SimpleStackTemplateResponse": { "type": "object", "properties": { @@ -10139,9 +10158,6 @@ const docTemplate = `{ }, "name": { "type": "string" - }, - "role": { - "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.SimpleRoleResponse" } } }, @@ -10261,86 +10277,6 @@ const docTemplate = `{ } } }, - "github_com_openinfradev_tks-api_pkg_domain.StackTemplate": { - "type": "object", - "properties": { - "cloudService": { - "type": "string" - }, - "createdAt": { - "type": "string" - }, - "creator": { - "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.User" - }, - "creatorId": { - "type": "string" - }, - "description": { - "type": "string" - }, - "id": { - "type": "string" - }, - "kubeType": { - "type": "string" - }, - "kubeVersion": { - "type": "string" - }, - "name": { - "type": "string" - }, - "organizationId": { - "type": "string" - }, - "organizationIds": { - "type": "array", - "items": { - "type": "string" - } - }, - "organizations": { - "type": "array", - "items": { - "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.Organization" - } - }, - "platform": { - "type": "string" - }, - "serviceIds": { - "type": "array", - "items": { - "type": "string" - } - }, - "services": { - "type": "array", - "items": { - "type": "integer" - } - }, - "template": { - "type": "string" - }, - "templateType": { - "type": "string" - }, - "updatedAt": { - "type": "string" - }, - "updator": { - "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.User" - }, - "updatorId": { - "type": "string" - }, - "version": { - "type": "string" - } - } - }, "github_com_openinfradev_tks-api_pkg_domain.StackTemplateResponse": { "type": "object", "properties": { @@ -10606,10 +10542,10 @@ const docTemplate = `{ "type": "string" }, "organization": { - "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.Organization" + "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.OrganizationResponse" }, "role": { - "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.Role" + "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.RoleResponse" } } } @@ -10677,7 +10613,7 @@ const docTemplate = `{ "permissions": { "type": "array", "items": { - "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.Permission" + "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.PermissionResponse" } } } @@ -10901,10 +10837,10 @@ const docTemplate = `{ "type": "string" }, "organization": { - "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.Organization" + "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.OrganizationResponse" }, "role": { - "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.Role" + "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.RoleResponse" }, "updatedAt": { "type": "string" @@ -10913,62 +10849,6 @@ const docTemplate = `{ } } }, - "github_com_openinfradev_tks-api_pkg_domain.User": { - "type": "object", - "properties": { - "accountId": { - "type": "string" - }, - "createdAt": { - "type": "string" - }, - "creator": { - "type": "string" - }, - "department": { - "type": "string" - }, - "description": { - "type": "string" - }, - "email": { - "type": "string" - }, - "id": { - "type": "string" - }, - "name": { - "type": "string" - }, - "organization": { - "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.Organization" - }, - "organizationId": { - "type": "string" - }, - "password": { - "type": "string" - }, - "passwordExpired": { - "type": "boolean" - }, - "passwordUpdatedAt": { - "type": "string" - }, - "role": { - "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.Role" - }, - "roleId": { - "type": "string" - }, - "token": { - "type": "string" - }, - "updatedAt": { - "type": "string" - } - } - }, "github_com_openinfradev_tks-api_pkg_domain.VerifyIdentityForLostIdRequest": { "type": "object", "required": [ @@ -11058,10 +10938,10 @@ const docTemplate = `{ "type": "string" }, "organization": { - "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.Organization" + "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.OrganizationResponse" }, "role": { - "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.Role" + "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.RoleResponse" }, "updatedAt": { "type": "string" @@ -11129,10 +11009,10 @@ const docTemplate = `{ "type": "string" }, "organization": { - "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.Organization" + "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.OrganizationResponse" }, "role": { - "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.Role" + "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.RoleResponse" }, "updatedAt": { "type": "string" @@ -11157,18 +11037,6 @@ const docTemplate = `{ "type": "string" } } - }, - "gorm.DeletedAt": { - "type": "object", - "properties": { - "time": { - "type": "string" - }, - "valid": { - "description": "Valid is true if Time is not NULL", - "type": "boolean" - } - } } }, "securityDefinitions": { diff --git a/api/swagger/swagger.json b/api/swagger/swagger.json index 86d8b058..8872bcf7 100644 --- a/api/swagger/swagger.json +++ b/api/swagger/swagger.json @@ -16,6 +16,186 @@ "host": "tks-api-dev.taco-cat.xyz", "basePath": "/api/1.0/", "paths": { + "/admin/audits": { + "get": { + "security": [ + { + "JWT": [] + } + ], + "description": "Get Audits", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Audits" + ], + "summary": "Get Audits", + "parameters": [ + { + "type": "string", + "description": "pageSize", + "name": "limit", + "in": "query" + }, + { + "type": "string", + "description": "pageNumber", + "name": "page", + "in": "query" + }, + { + "type": "string", + "description": "sortColumn", + "name": "soertColumn", + "in": "query" + }, + { + "type": "string", + "description": "sortOrder", + "name": "sortOrder", + "in": "query" + }, + { + "type": "array", + "items": { + "type": "string" + }, + "collectionFormat": "csv", + "description": "filters", + "name": "filter", + "in": "query" + }, + { + "type": "array", + "items": { + "type": "string" + }, + "collectionFormat": "csv", + "description": "filters", + "name": "or", + "in": "query" + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.GetAuditsResponse" + } + } + } + }, + "post": { + "security": [ + { + "JWT": [] + } + ], + "description": "Create Audit", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Audits" + ], + "summary": "Create Audit", + "parameters": [ + { + "description": "create audit request", + "name": "body", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.CreateAuditRequest" + } + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.CreateAuditResponse" + } + } + } + } + }, + "/admin/audits/{auditId}": { + "get": { + "security": [ + { + "JWT": [] + } + ], + "description": "Get Audit", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Audits" + ], + "summary": "Get Audit", + "parameters": [ + { + "type": "string", + "description": "auditId", + "name": "auditId", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.GetAuditResponse" + } + } + } + }, + "delete": { + "security": [ + { + "JWT": [] + } + ], + "description": "Delete Audit", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Audits" + ], + "summary": "Delete Audit 'NOT IMPLEMENTED'", + "parameters": [ + { + "type": "string", + "description": "auditId", + "name": "auditId", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "OK" + } + } + } + }, "/admin/organizations/{organizationId}/projects": { "get": { "security": [ @@ -810,7 +990,7 @@ "tags": [ "StackTemplates" ], - "summary": "Create StackTemplate 'NOT IMPLEMENTED'", + "summary": "Create StackTemplate", "parameters": [ { "description": "create stack template request", @@ -912,7 +1092,7 @@ "tags": [ "StackTemplates" ], - "summary": "Update StackTemplate 'NOT IMPLEMENTED'", + "summary": "Update StackTemplate", "parameters": [ { "description": "Update stack template request", @@ -946,7 +1126,7 @@ "tags": [ "StackTemplates" ], - "summary": "Delete StackTemplate 'NOT IMPLEMENTED'", + "summary": "Delete StackTemplate", "parameters": [ { "type": "string", @@ -1682,7 +1862,7 @@ "200": { "description": "OK", "schema": { - "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.Cluster" + "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.GetClusterResponse" } } } @@ -1715,10 +1895,7 @@ ], "responses": { "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.Cluster" - } + "description": "OK" } } } @@ -2099,7 +2276,7 @@ "200": { "description": "OK", "schema": { - "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.Organization" + "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.DeleteOrganizationResponse" } } } @@ -2334,14 +2511,14 @@ } } }, - "/organizations/{organizationId}/audits": { + "/organizations/{organizationId}/cloud-accounts": { "get": { "security": [ { "JWT": [] } ], - "description": "Get Audits", + "description": "Get CloudAccounts", "consumes": [ "application/json" ], @@ -2349,10 +2526,17 @@ "application/json" ], "tags": [ - "Audits" + "CloudAccounts" ], - "summary": "Get Audits", + "summary": "Get CloudAccounts", "parameters": [ + { + "type": "string", + "description": "organizationId", + "name": "organizationId", + "in": "path", + "required": true + }, { "type": "string", "description": "pageSize", @@ -2384,17 +2568,7 @@ }, "collectionFormat": "csv", "description": "filters", - "name": "filter", - "in": "query" - }, - { - "type": "array", - "items": { - "type": "string" - }, - "collectionFormat": "csv", - "description": "filters", - "name": "or", + "name": "filters", "in": "query" } ], @@ -2402,7 +2576,7 @@ "200": { "description": "OK", "schema": { - "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.GetAuditsResponse" + "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.GetCloudAccountsResponse" } } } @@ -2413,7 +2587,7 @@ "JWT": [] } ], - "description": "Create Audit", + "description": "Create CloudAccount", "consumes": [ "application/json" ], @@ -2421,17 +2595,24 @@ "application/json" ], "tags": [ - "Audits" + "CloudAccounts" ], - "summary": "Create Audit", + "summary": "Create CloudAccount", "parameters": [ { - "description": "create audit request", + "type": "string", + "description": "organizationId", + "name": "organizationId", + "in": "path", + "required": true + }, + { + "description": "create cloud setting request", "name": "body", "in": "body", "required": true, "schema": { - "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.CreateAuditRequest" + "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.CreateCloudAccountRequest" } } ], @@ -2439,20 +2620,20 @@ "200": { "description": "OK", "schema": { - "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.CreateAuditResponse" + "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.CreateCloudAccountResponse" } } } } }, - "/organizations/{organizationId}/audits/{auditId}": { + "/organizations/{organizationId}/cloud-accounts/aws-account-id/{awsAccountId}/existence": { "get": { "security": [ { "JWT": [] } ], - "description": "Get Audit", + "description": "Check awsAccountId for cloudAccount", "consumes": [ "application/json" ], @@ -2460,14 +2641,21 @@ "application/json" ], "tags": [ - "Audits" + "CloudAccounts" ], - "summary": "Get Audit", + "summary": "Check awsAccountId for cloudAccount", "parameters": [ { "type": "string", - "description": "auditId", - "name": "auditId", + "description": "organizationId", + "name": "organizationId", + "in": "path", + "required": true + }, + { + "type": "string", + "description": "awsAccountId", + "name": "awsAccountId", "in": "path", "required": true } @@ -2476,205 +2664,14 @@ "200": { "description": "OK", "schema": { - "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.GetAuditResponse" + "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.CheckCloudAccountAwsAccountIdResponse" } } } - }, - "delete": { - "security": [ - { - "JWT": [] - } - ], - "description": "Delete Audit", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "Audits" - ], - "summary": "Delete Audit 'NOT IMPLEMENTED'", - "parameters": [ - { - "type": "string", - "description": "auditId", - "name": "auditId", - "in": "path", - "required": true - } - ], - "responses": { - "200": { - "description": "OK" - } - } - } - }, - "/organizations/{organizationId}/cloud-accounts": { - "get": { - "security": [ - { - "JWT": [] - } - ], - "description": "Get CloudAccounts", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "CloudAccounts" - ], - "summary": "Get CloudAccounts", - "parameters": [ - { - "type": "string", - "description": "organizationId", - "name": "organizationId", - "in": "path", - "required": true - }, - { - "type": "string", - "description": "pageSize", - "name": "limit", - "in": "query" - }, - { - "type": "string", - "description": "pageNumber", - "name": "page", - "in": "query" - }, - { - "type": "string", - "description": "sortColumn", - "name": "soertColumn", - "in": "query" - }, - { - "type": "string", - "description": "sortOrder", - "name": "sortOrder", - "in": "query" - }, - { - "type": "array", - "items": { - "type": "string" - }, - "collectionFormat": "csv", - "description": "filters", - "name": "filters", - "in": "query" - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.GetCloudAccountsResponse" - } - } - } - }, - "post": { - "security": [ - { - "JWT": [] - } - ], - "description": "Create CloudAccount", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "CloudAccounts" - ], - "summary": "Create CloudAccount", - "parameters": [ - { - "type": "string", - "description": "organizationId", - "name": "organizationId", - "in": "path", - "required": true - }, - { - "description": "create cloud setting request", - "name": "body", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.CreateCloudAccountRequest" - } - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.CreateCloudAccountResponse" - } - } - } - } - }, - "/organizations/{organizationId}/cloud-accounts/aws-account-id/{awsAccountId}/existence": { - "get": { - "security": [ - { - "JWT": [] - } - ], - "description": "Check awsAccountId for cloudAccount", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "CloudAccounts" - ], - "summary": "Check awsAccountId for cloudAccount", - "parameters": [ - { - "type": "string", - "description": "organizationId", - "name": "organizationId", - "in": "path", - "required": true - }, - { - "type": "string", - "description": "awsAccountId", - "name": "awsAccountId", - "in": "path", - "required": true - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.CheckCloudAccountAwsAccountIdResponse" - } - } - } - } - }, - "/organizations/{organizationId}/cloud-accounts/name/{name}/existence": { - "get": { + } + }, + "/organizations/{organizationId}/cloud-accounts/name/{name}/existence": { + "get": { "security": [ { "JWT": [] @@ -3765,7 +3762,7 @@ "schema": { "type": "array", "items": { - "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.AppServeApp" + "$ref": "#/definitions/github_com_openinfradev_tks-api_internal_model.AppServeApp" } } } @@ -4432,7 +4429,7 @@ "schema": { "type": "array", "items": { - "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.AppServeApp" + "$ref": "#/definitions/github_com_openinfradev_tks-api_internal_model.AppServeApp" } } } @@ -5621,7 +5618,7 @@ "200": { "description": "OK", "schema": { - "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.PermissionSet" + "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.PermissionSetResponse" } } } @@ -5668,14 +5665,14 @@ } } }, - "/organizations/{organizationId}/stacks": { + "/organizations/{organizationId}/stack-templates": { "get": { "security": [ { "JWT": [] } ], - "description": "Get Stacks", + "description": "Get Organization StackTemplates", "consumes": [ "application/json" ], @@ -5683,17 +5680,10 @@ "application/json" ], "tags": [ - "Stacks" + "StackTemplates" ], - "summary": "Get Stacks", + "summary": "Get Organization StackTemplates", "parameters": [ - { - "type": "string", - "description": "organizationId", - "name": "organizationId", - "in": "path", - "required": true - }, { "type": "string", "description": "pageSize", @@ -5719,9 +5709,13 @@ "in": "query" }, { - "type": "string", - "description": "combinedFilter", - "name": "combinedFilter", + "type": "array", + "items": { + "type": "string" + }, + "collectionFormat": "csv", + "description": "filters", + "name": "filters", "in": "query" } ], @@ -5729,18 +5723,20 @@ "200": { "description": "OK", "schema": { - "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.GetStacksResponse" + "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.GetStackTemplatesResponse" } } } - }, - "post": { + } + }, + "/organizations/{organizationId}/stack-templates/{stackTemplateId}": { + "get": { "security": [ { "JWT": [] } ], - "description": "Create Stack", + "description": "Get Organization StackTemplate", "consumes": [ "application/json" ], @@ -5748,45 +5744,27 @@ "application/json" ], "tags": [ - "Stacks" - ], - "summary": "Create Stack", - "parameters": [ - { - "type": "string", - "description": "organizationId", - "name": "organizationId", - "in": "path", - "required": true - }, - { - "description": "create cloud setting request", - "name": "body", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.CreateStackRequest" - } - } + "StackTemplates" ], + "summary": "Get Organization StackTemplate", "responses": { "200": { "description": "OK", "schema": { - "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.CreateStackResponse" + "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.GetStackTemplateResponse" } } } } }, - "/organizations/{organizationId}/stacks/name/{name}/existence": { + "/organizations/{organizationId}/stacks": { "get": { "security": [ { "JWT": [] } ], - "description": "Check name for stack", + "description": "Get Stacks", "consumes": [ "application/json" ], @@ -5796,7 +5774,7 @@ "tags": [ "Stacks" ], - "summary": "Check name for stack", + "summary": "Get Stacks", "parameters": [ { "type": "string", @@ -5807,11 +5785,122 @@ }, { "type": "string", - "description": "stackId", - "name": "stackId", - "in": "path", - "required": true - }, + "description": "pageSize", + "name": "limit", + "in": "query" + }, + { + "type": "string", + "description": "pageNumber", + "name": "page", + "in": "query" + }, + { + "type": "string", + "description": "sortColumn", + "name": "soertColumn", + "in": "query" + }, + { + "type": "string", + "description": "sortOrder", + "name": "sortOrder", + "in": "query" + }, + { + "type": "string", + "description": "combinedFilter", + "name": "combinedFilter", + "in": "query" + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.GetStacksResponse" + } + } + } + }, + "post": { + "security": [ + { + "JWT": [] + } + ], + "description": "Create Stack", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Stacks" + ], + "summary": "Create Stack", + "parameters": [ + { + "type": "string", + "description": "organizationId", + "name": "organizationId", + "in": "path", + "required": true + }, + { + "description": "create cloud setting request", + "name": "body", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.CreateStackRequest" + } + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.CreateStackResponse" + } + } + } + } + }, + "/organizations/{organizationId}/stacks/name/{name}/existence": { + "get": { + "security": [ + { + "JWT": [] + } + ], + "description": "Check name for stack", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Stacks" + ], + "summary": "Check name for stack", + "parameters": [ + { + "type": "string", + "description": "organizationId", + "name": "organizationId", + "in": "path", + "required": true + }, + { + "type": "string", + "description": "stackId", + "name": "stackId", + "in": "path", + "required": true + }, { "type": "string", "description": "name", @@ -6455,10 +6544,7 @@ ], "responses": { "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.User" - } + "description": "OK" } } } @@ -6526,7 +6612,7 @@ "200": { "description": "OK", "schema": { - "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.PermissionSet" + "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.PermissionSetResponse" } } } @@ -6614,6 +6700,177 @@ } }, "definitions": { + "github_com_openinfradev_tks-api_internal_model.AppServeApp": { + "type": "object", + "properties": { + "appServeAppTasks": { + "type": "array", + "items": { + "$ref": "#/definitions/github_com_openinfradev_tks-api_internal_model.AppServeAppTask" + } + }, + "appType": { + "description": "appType (spring/springboot)", + "type": "string" + }, + "createdAt": { + "type": "string" + }, + "deletedAt": { + "type": "string" + }, + "endpointUrl": { + "description": "endpoint URL of deployed app", + "type": "string" + }, + "grafanaUrl": { + "description": "grafana dashboard URL for deployed app", + "type": "string" + }, + "id": { + "type": "string" + }, + "name": { + "description": "application name", + "type": "string" + }, + "namespace": { + "description": "application namespace", + "type": "string" + }, + "organizationId": { + "description": "contractId is a contract ID which this app belongs to", + "type": "string" + }, + "previewEndpointUrl": { + "description": "preview svc endpoint URL in B/G deployment", + "type": "string" + }, + "projectId": { + "description": "project ID which this app belongs to", + "type": "string" + }, + "status": { + "description": "status is status of deployed app", + "type": "string" + }, + "targetClusterId": { + "description": "target cluster to which the app is deployed", + "type": "string" + }, + "targetClusterName": { + "description": "target cluster name", + "type": "string" + }, + "type": { + "description": "type (build/deploy/all)", + "type": "string" + }, + "updatedAt": { + "type": "string" + } + } + }, + "github_com_openinfradev_tks-api_internal_model.AppServeAppTask": { + "type": "object", + "properties": { + "appConfig": { + "description": "java app config", + "type": "string" + }, + "appSecret": { + "description": "java app secret", + "type": "string" + }, + "appServeAppId": { + "description": "ID for appServeApp that this task belongs to", + "type": "string" + }, + "artifactUrl": { + "description": "URL of java app artifact (Eg, Jar)", + "type": "string" + }, + "availableRollback": { + "type": "boolean" + }, + "createdAt": { + "description": "createdAt is a creation timestamp for the application", + "type": "string" + }, + "deletedAt": { + "type": "string" + }, + "executablePath": { + "description": "Executable path of app image", + "type": "string" + }, + "extraEnv": { + "description": "env variable list for java app", + "type": "string" + }, + "helmRevision": { + "description": "revision of deployed helm release", + "type": "integer" + }, + "id": { + "type": "string" + }, + "imageUrl": { + "description": "URL of built image for app", + "type": "string" + }, + "output": { + "description": "output for task result", + "type": "string" + }, + "port": { + "description": "java app port", + "type": "string" + }, + "profile": { + "description": "java app profile", + "type": "string" + }, + "pvAccessMode": { + "type": "string" + }, + "pvEnabled": { + "type": "boolean" + }, + "pvMountPath": { + "type": "string" + }, + "pvSize": { + "type": "string" + }, + "pvStorageClass": { + "type": "string" + }, + "resourceSpec": { + "description": "resource spec of app pod", + "type": "string" + }, + "rollbackVersion": { + "description": "rollback target version", + "type": "string" + }, + "status": { + "description": "status is app status", + "type": "string" + }, + "strategy": { + "description": "deployment strategy (eg, rolling-update)", + "type": "string" + }, + "updatedAt": { + "type": "string" + }, + "version": { + "description": "application version", + "type": "string" + } + } + }, "github_com_openinfradev_tks-api_pkg_domain.ActionResponse": { "type": "object", "properties": { @@ -6822,13 +7079,13 @@ "AppGroupType_SERVICE_MESH" ] }, - "github_com_openinfradev_tks-api_pkg_domain.AppServeApp": { + "github_com_openinfradev_tks-api_pkg_domain.AppServeAppResponse": { "type": "object", "properties": { "appServeAppTasks": { "type": "array", "items": { - "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.AppServeAppTask" + "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.AppServeAppTaskResponse" } }, "appType": { @@ -6893,7 +7150,7 @@ } } }, - "github_com_openinfradev_tks-api_pkg_domain.AppServeAppTask": { + "github_com_openinfradev_tks-api_pkg_domain.AppServeAppTaskResponse": { "type": "object", "properties": { "appConfig": { @@ -7080,9 +7337,6 @@ }, "user": { "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.SimpleUserResponse" - }, - "userId": { - "type": "string" } } }, @@ -7152,71 +7406,6 @@ } } }, - "github_com_openinfradev_tks-api_pkg_domain.CloudAccount": { - "type": "object", - "properties": { - "accessKeyId": { - "type": "string" - }, - "awsAccountId": { - "type": "string" - }, - "cloudService": { - "type": "string" - }, - "clusters": { - "type": "integer" - }, - "createdAt": { - "type": "string" - }, - "createdIAM": { - "type": "boolean" - }, - "creator": { - "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.User" - }, - "creatorId": { - "type": "string" - }, - "description": { - "type": "string" - }, - "id": { - "type": "string" - }, - "name": { - "type": "string" - }, - "organizationId": { - "type": "string" - }, - "resource": { - "type": "string" - }, - "secretAccessKey": { - "type": "string" - }, - "sessionToken": { - "type": "string" - }, - "status": { - "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.CloudAccountStatus" - }, - "statusDesc": { - "type": "string" - }, - "updatedAt": { - "type": "string" - }, - "updator": { - "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.User" - }, - "updatorId": { - "type": "string" - } - } - }, "github_com_openinfradev_tks-api_pkg_domain.CloudAccountResponse": { "type": "object", "properties": { @@ -7235,165 +7424,32 @@ "createdIAM": { "type": "boolean" }, - "creator": { - "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.SimpleUserResponse" - }, - "description": { - "type": "string" - }, - "id": { - "type": "string" - }, - "name": { - "type": "string" - }, - "organizationId": { - "type": "string" - }, - "resource": { - "type": "string" - }, - "status": { - "type": "string" - }, - "updatedAt": { - "type": "string" - }, - "updator": { - "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.SimpleUserResponse" - } - } - }, - "github_com_openinfradev_tks-api_pkg_domain.CloudAccountStatus": { - "type": "integer", - "enum": [ - 0, - 1, - 2, - 3, - 4, - 5, - 6 - ], - "x-enum-varnames": [ - "CloudAccountStatus_PENDING", - "CloudAccountStatus_CREATING", - "CloudAccountStatus_CREATED", - "CloudAccountStatus_DELETING", - "CloudAccountStatus_DELETED", - "CloudAccountStatus_CREATE_ERROR", - "CloudAccountStatus_DELETE_ERROR" - ] - }, - "github_com_openinfradev_tks-api_pkg_domain.Cluster": { - "type": "object", - "properties": { - "byoClusterEndpointHost": { - "type": "string" - }, - "byoClusterEndpointPort": { - "type": "integer" - }, - "cloudAccount": { - "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.CloudAccount" - }, - "cloudAccountId": { - "type": "string" - }, - "cloudService": { - "type": "string" - }, - "clusterType": { - "type": "integer" - }, - "conf": { - "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.ClusterConf" - }, - "createdAt": { - "type": "string" - }, - "creator": { - "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.User" - }, - "creatorId": { - "type": "string" + "creator": { + "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.SimpleUserResponse" }, "description": { "type": "string" }, - "favorited": { - "type": "boolean" - }, "id": { "type": "string" }, - "isStack": { - "type": "boolean" - }, - "kubeconfig": { - "type": "array", - "items": { - "type": "integer" - } - }, "name": { "type": "string" }, "organizationId": { "type": "string" }, - "stackTemplate": { - "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.StackTemplate" - }, - "stackTemplateId": { + "resource": { "type": "string" }, "status": { - "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.ClusterStatus" - }, - "statusDesc": { "type": "string" }, "updatedAt": { "type": "string" }, "updator": { - "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.User" - }, - "updatorId": { - "type": "string" - } - } - }, - "github_com_openinfradev_tks-api_pkg_domain.ClusterConf": { - "type": "object", - "properties": { - "tksCpNode": { - "type": "integer" - }, - "tksCpNodeMax": { - "type": "integer" - }, - "tksCpNodeType": { - "type": "string" - }, - "tksInfraNode": { - "type": "integer" - }, - "tksInfraNodeMax": { - "type": "integer" - }, - "tksInfraNodeType": { - "type": "string" - }, - "tksUserNode": { - "type": "integer" - }, - "tksUserNodeMax": { - "type": "integer" - }, - "tksUserNodeType": { - "type": "string" + "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.SimpleUserResponse" } } }, @@ -7502,6 +7558,9 @@ "description": { "type": "string" }, + "favorited": { + "type": "boolean" + }, "id": { "type": "string" }, @@ -7578,33 +7637,6 @@ } } }, - "github_com_openinfradev_tks-api_pkg_domain.ClusterStatus": { - "type": "integer", - "enum": [ - 0, - 1, - 2, - 3, - 4, - 5, - 6, - 7, - 8, - 9 - ], - "x-enum-varnames": [ - "ClusterStatus_PENDING", - "ClusterStatus_INSTALLING", - "ClusterStatus_RUNNING", - "ClusterStatus_DELETING", - "ClusterStatus_DELETED", - "ClusterStatus_INSTALL_ERROR", - "ClusterStatus_DELETE_ERROR", - "ClusterStatus_BOOTSTRAPPING", - "ClusterStatus_BOOTSTRAPPED", - "ClusterStatus_BOOTSTRAP_ERROR" - ] - }, "github_com_openinfradev_tks-api_pkg_domain.CommonProjectResponse": { "type": "object", "properties": { @@ -8300,10 +8332,10 @@ "type": "string" }, "organization": { - "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.Organization" + "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.OrganizationResponse" }, "role": { - "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.Role" + "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.RoleResponse" } } } @@ -8419,7 +8451,15 @@ } } }, - "github_com_openinfradev_tks-api_pkg_domain.Endpoint": { + "github_com_openinfradev_tks-api_pkg_domain.DeleteOrganizationResponse": { + "type": "object", + "properties": { + "id": { + "type": "string" + } + } + }, + "github_com_openinfradev_tks-api_pkg_domain.EndpointResponse": { "type": "object", "properties": { "createdAt": { @@ -8430,6 +8470,9 @@ }, "name": { "type": "string" + }, + "updatedAt": { + "type": "string" } } }, @@ -8562,7 +8605,7 @@ "type": "object", "properties": { "appServeApp": { - "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.AppServeApp" + "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.AppServeAppResponse" }, "stages": { "type": "array", @@ -8576,10 +8619,10 @@ "type": "object", "properties": { "appServeApp": { - "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.AppServeApp" + "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.AppServeAppResponse" }, "appServeAppTask": { - "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.AppServeAppTask" + "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.AppServeAppTaskResponse" }, "stages": { "type": "array", @@ -8674,6 +8717,14 @@ } } }, + "github_com_openinfradev_tks-api_pkg_domain.GetClusterResponse": { + "type": "object", + "properties": { + "cluster": { + "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.ClusterResponse" + } + } + }, "github_com_openinfradev_tks-api_pkg_domain.GetClustersResponse": { "type": "object", "properties": { @@ -8748,10 +8799,10 @@ "type": "string" }, "organization": { - "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.Organization" + "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.OrganizationResponse" }, "role": { - "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.Role" + "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.RoleResponse" } } } @@ -9081,10 +9132,10 @@ "type": "string" }, "organization": { - "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.Organization" + "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.OrganizationResponse" }, "role": { - "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.Role" + "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.RoleResponse" }, "updatedAt": { "type": "string" @@ -9247,10 +9298,10 @@ "type": "string" }, "organization": { - "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.Organization" + "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.OrganizationResponse" }, "role": { - "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.Role" + "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.RoleResponse" }, "updatedAt": { "type": "string" @@ -9292,13 +9343,13 @@ "type": "string" }, "organization": { - "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.Organization" + "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.OrganizationResponse" }, "passwordExpired": { "type": "boolean" }, "role": { - "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.Role" + "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.RoleResponse" }, "token": { "type": "string" @@ -9321,18 +9372,12 @@ } } }, - "github_com_openinfradev_tks-api_pkg_domain.Organization": { + "github_com_openinfradev_tks-api_pkg_domain.OrganizationResponse": { "type": "object", "properties": { "createdAt": { "type": "string" }, - "creator": { - "type": "string" - }, - "deletedAt": { - "$ref": "#/definitions/gorm.DeletedAt" - }, "description": { "type": "string" }, @@ -9434,7 +9479,7 @@ } } }, - "github_com_openinfradev_tks-api_pkg_domain.Permission": { + "github_com_openinfradev_tks-api_pkg_domain.PermissionResponse": { "type": "object", "properties": { "ID": { @@ -9443,24 +9488,15 @@ "children": { "type": "array", "items": { - "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.Permission" + "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.PermissionResponse" } }, - "createdAt": { - "type": "string" - }, - "deletedAt": { - "$ref": "#/definitions/gorm.DeletedAt" - }, "endpoints": { "type": "array", "items": { - "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.Endpoint" + "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.EndpointResponse" } }, - "id": { - "type": "integer" - }, "is_allowed": { "type": "boolean" }, @@ -9468,42 +9504,39 @@ "type": "string" }, "parent": { - "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.Permission" + "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.PermissionResponse" }, "parent_id": { "type": "string" }, "role": { - "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.Role" + "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.RoleResponse" }, "role_id": { "type": "string" - }, - "updatedAt": { - "type": "string" } } }, - "github_com_openinfradev_tks-api_pkg_domain.PermissionSet": { + "github_com_openinfradev_tks-api_pkg_domain.PermissionSetResponse": { "type": "object", "properties": { "configuration": { - "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.Permission" + "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.PermissionResponse" }, "dashboard": { - "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.Permission" + "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.PermissionResponse" }, "notification": { - "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.Permission" + "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.PermissionResponse" }, "project_management": { - "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.Permission" + "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.PermissionResponse" }, "security_policy": { - "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.Permission" + "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.PermissionResponse" }, "stack": { - "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.Permission" + "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.PermissionResponse" } } }, @@ -9855,6 +9888,9 @@ }, "projectRoleName": { "type": "string" + }, + "updatedAt": { + "type": "string" } } }, @@ -9976,7 +10012,7 @@ } } }, - "github_com_openinfradev_tks-api_pkg_domain.Role": { + "github_com_openinfradev_tks-api_pkg_domain.RoleResponse": { "type": "object", "properties": { "createdAt": { @@ -9985,9 +10021,6 @@ "creator": { "type": "string" }, - "deletedAt": { - "$ref": "#/definitions/gorm.DeletedAt" - }, "description": { "type": "string" }, @@ -9998,7 +10031,7 @@ "type": "string" }, "organization": { - "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.Organization" + "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.OrganizationResponse" }, "organizationId": { "type": "string" @@ -10076,20 +10109,6 @@ } } }, - "github_com_openinfradev_tks-api_pkg_domain.SimpleRoleResponse": { - "type": "object", - "properties": { - "description": { - "type": "string" - }, - "id": { - "type": "string" - }, - "name": { - "type": "string" - } - } - }, "github_com_openinfradev_tks-api_pkg_domain.SimpleStackTemplateResponse": { "type": "object", "properties": { @@ -10133,9 +10152,6 @@ }, "name": { "type": "string" - }, - "role": { - "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.SimpleRoleResponse" } } }, @@ -10255,86 +10271,6 @@ } } }, - "github_com_openinfradev_tks-api_pkg_domain.StackTemplate": { - "type": "object", - "properties": { - "cloudService": { - "type": "string" - }, - "createdAt": { - "type": "string" - }, - "creator": { - "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.User" - }, - "creatorId": { - "type": "string" - }, - "description": { - "type": "string" - }, - "id": { - "type": "string" - }, - "kubeType": { - "type": "string" - }, - "kubeVersion": { - "type": "string" - }, - "name": { - "type": "string" - }, - "organizationId": { - "type": "string" - }, - "organizationIds": { - "type": "array", - "items": { - "type": "string" - } - }, - "organizations": { - "type": "array", - "items": { - "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.Organization" - } - }, - "platform": { - "type": "string" - }, - "serviceIds": { - "type": "array", - "items": { - "type": "string" - } - }, - "services": { - "type": "array", - "items": { - "type": "integer" - } - }, - "template": { - "type": "string" - }, - "templateType": { - "type": "string" - }, - "updatedAt": { - "type": "string" - }, - "updator": { - "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.User" - }, - "updatorId": { - "type": "string" - }, - "version": { - "type": "string" - } - } - }, "github_com_openinfradev_tks-api_pkg_domain.StackTemplateResponse": { "type": "object", "properties": { @@ -10600,10 +10536,10 @@ "type": "string" }, "organization": { - "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.Organization" + "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.OrganizationResponse" }, "role": { - "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.Role" + "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.RoleResponse" } } } @@ -10671,7 +10607,7 @@ "permissions": { "type": "array", "items": { - "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.Permission" + "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.PermissionResponse" } } } @@ -10895,10 +10831,10 @@ "type": "string" }, "organization": { - "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.Organization" + "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.OrganizationResponse" }, "role": { - "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.Role" + "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.RoleResponse" }, "updatedAt": { "type": "string" @@ -10907,62 +10843,6 @@ } } }, - "github_com_openinfradev_tks-api_pkg_domain.User": { - "type": "object", - "properties": { - "accountId": { - "type": "string" - }, - "createdAt": { - "type": "string" - }, - "creator": { - "type": "string" - }, - "department": { - "type": "string" - }, - "description": { - "type": "string" - }, - "email": { - "type": "string" - }, - "id": { - "type": "string" - }, - "name": { - "type": "string" - }, - "organization": { - "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.Organization" - }, - "organizationId": { - "type": "string" - }, - "password": { - "type": "string" - }, - "passwordExpired": { - "type": "boolean" - }, - "passwordUpdatedAt": { - "type": "string" - }, - "role": { - "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.Role" - }, - "roleId": { - "type": "string" - }, - "token": { - "type": "string" - }, - "updatedAt": { - "type": "string" - } - } - }, "github_com_openinfradev_tks-api_pkg_domain.VerifyIdentityForLostIdRequest": { "type": "object", "required": [ @@ -11052,10 +10932,10 @@ "type": "string" }, "organization": { - "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.Organization" + "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.OrganizationResponse" }, "role": { - "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.Role" + "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.RoleResponse" }, "updatedAt": { "type": "string" @@ -11123,10 +11003,10 @@ "type": "string" }, "organization": { - "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.Organization" + "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.OrganizationResponse" }, "role": { - "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.Role" + "$ref": "#/definitions/github_com_openinfradev_tks-api_pkg_domain.RoleResponse" }, "updatedAt": { "type": "string" @@ -11151,18 +11031,6 @@ "type": "string" } } - }, - "gorm.DeletedAt": { - "type": "object", - "properties": { - "time": { - "type": "string" - }, - "valid": { - "description": "Valid is true if Time is not NULL", - "type": "boolean" - } - } } }, "securityDefinitions": { diff --git a/api/swagger/swagger.yaml b/api/swagger/swagger.yaml index 188af9fd..a94fa389 100644 --- a/api/swagger/swagger.yaml +++ b/api/swagger/swagger.yaml @@ -1,5 +1,128 @@ basePath: /api/1.0/ definitions: + github_com_openinfradev_tks-api_internal_model.AppServeApp: + properties: + appServeAppTasks: + items: + $ref: '#/definitions/github_com_openinfradev_tks-api_internal_model.AppServeAppTask' + type: array + appType: + description: appType (spring/springboot) + type: string + createdAt: + type: string + deletedAt: + type: string + endpointUrl: + description: endpoint URL of deployed app + type: string + grafanaUrl: + description: grafana dashboard URL for deployed app + type: string + id: + type: string + name: + description: application name + type: string + namespace: + description: application namespace + type: string + organizationId: + description: contractId is a contract ID which this app belongs to + type: string + previewEndpointUrl: + description: preview svc endpoint URL in B/G deployment + type: string + projectId: + description: project ID which this app belongs to + type: string + status: + description: status is status of deployed app + type: string + targetClusterId: + description: target cluster to which the app is deployed + type: string + targetClusterName: + description: target cluster name + type: string + type: + description: type (build/deploy/all) + type: string + updatedAt: + type: string + type: object + github_com_openinfradev_tks-api_internal_model.AppServeAppTask: + properties: + appConfig: + description: java app config + type: string + appSecret: + description: java app secret + type: string + appServeAppId: + description: ID for appServeApp that this task belongs to + type: string + artifactUrl: + description: URL of java app artifact (Eg, Jar) + type: string + availableRollback: + type: boolean + createdAt: + description: createdAt is a creation timestamp for the application + type: string + deletedAt: + type: string + executablePath: + description: Executable path of app image + type: string + extraEnv: + description: env variable list for java app + type: string + helmRevision: + description: revision of deployed helm release + type: integer + id: + type: string + imageUrl: + description: URL of built image for app + type: string + output: + description: output for task result + type: string + port: + description: java app port + type: string + profile: + description: java app profile + type: string + pvAccessMode: + type: string + pvEnabled: + type: boolean + pvMountPath: + type: string + pvSize: + type: string + pvStorageClass: + type: string + resourceSpec: + description: resource spec of app pod + type: string + rollbackVersion: + description: rollback target version + type: string + status: + description: status is app status + type: string + strategy: + description: deployment strategy (eg, rolling-update) + type: string + updatedAt: + type: string + version: + description: application version + type: string + type: object github_com_openinfradev_tks-api_pkg_domain.ActionResponse: properties: body: @@ -143,11 +266,11 @@ definitions: - AppGroupType_UNSPECIFIED - AppGroupType_LMA - AppGroupType_SERVICE_MESH - github_com_openinfradev_tks-api_pkg_domain.AppServeApp: + github_com_openinfradev_tks-api_pkg_domain.AppServeAppResponse: properties: appServeAppTasks: items: - $ref: '#/definitions/github_com_openinfradev_tks-api_pkg_domain.AppServeAppTask' + $ref: '#/definitions/github_com_openinfradev_tks-api_pkg_domain.AppServeAppTaskResponse' type: array appType: description: appType (spring/springboot) @@ -194,7 +317,7 @@ definitions: updatedAt: type: string type: object - github_com_openinfradev_tks-api_pkg_domain.AppServeAppTask: + github_com_openinfradev_tks-api_pkg_domain.AppServeAppTaskResponse: properties: appConfig: description: java app config @@ -331,8 +454,6 @@ definitions: type: string user: $ref: '#/definitions/github_com_openinfradev_tks-api_pkg_domain.SimpleUserResponse' - userId: - type: string type: object github_com_openinfradev_tks-api_pkg_domain.Axis: properties: @@ -376,49 +497,6 @@ definitions: existed: type: boolean type: object - github_com_openinfradev_tks-api_pkg_domain.CloudAccount: - properties: - accessKeyId: - type: string - awsAccountId: - type: string - cloudService: - type: string - clusters: - type: integer - createdAt: - type: string - createdIAM: - type: boolean - creator: - $ref: '#/definitions/github_com_openinfradev_tks-api_pkg_domain.User' - creatorId: - type: string - description: - type: string - id: - type: string - name: - type: string - organizationId: - type: string - resource: - type: string - secretAccessKey: - type: string - sessionToken: - type: string - status: - $ref: '#/definitions/github_com_openinfradev_tks-api_pkg_domain.CloudAccountStatus' - statusDesc: - type: string - updatedAt: - type: string - updator: - $ref: '#/definitions/github_com_openinfradev_tks-api_pkg_domain.User' - updatorId: - type: string - type: object github_com_openinfradev_tks-api_pkg_domain.CloudAccountResponse: properties: awsAccountId: @@ -450,98 +528,6 @@ definitions: updator: $ref: '#/definitions/github_com_openinfradev_tks-api_pkg_domain.SimpleUserResponse' type: object - github_com_openinfradev_tks-api_pkg_domain.CloudAccountStatus: - enum: - - 0 - - 1 - - 2 - - 3 - - 4 - - 5 - - 6 - type: integer - x-enum-varnames: - - CloudAccountStatus_PENDING - - CloudAccountStatus_CREATING - - CloudAccountStatus_CREATED - - CloudAccountStatus_DELETING - - CloudAccountStatus_DELETED - - CloudAccountStatus_CREATE_ERROR - - CloudAccountStatus_DELETE_ERROR - github_com_openinfradev_tks-api_pkg_domain.Cluster: - properties: - byoClusterEndpointHost: - type: string - byoClusterEndpointPort: - type: integer - cloudAccount: - $ref: '#/definitions/github_com_openinfradev_tks-api_pkg_domain.CloudAccount' - cloudAccountId: - type: string - cloudService: - type: string - clusterType: - type: integer - conf: - $ref: '#/definitions/github_com_openinfradev_tks-api_pkg_domain.ClusterConf' - createdAt: - type: string - creator: - $ref: '#/definitions/github_com_openinfradev_tks-api_pkg_domain.User' - creatorId: - type: string - description: - type: string - favorited: - type: boolean - id: - type: string - isStack: - type: boolean - kubeconfig: - items: - type: integer - type: array - name: - type: string - organizationId: - type: string - stackTemplate: - $ref: '#/definitions/github_com_openinfradev_tks-api_pkg_domain.StackTemplate' - stackTemplateId: - type: string - status: - $ref: '#/definitions/github_com_openinfradev_tks-api_pkg_domain.ClusterStatus' - statusDesc: - type: string - updatedAt: - type: string - updator: - $ref: '#/definitions/github_com_openinfradev_tks-api_pkg_domain.User' - updatorId: - type: string - type: object - github_com_openinfradev_tks-api_pkg_domain.ClusterConf: - properties: - tksCpNode: - type: integer - tksCpNodeMax: - type: integer - tksCpNodeType: - type: string - tksInfraNode: - type: integer - tksInfraNodeMax: - type: integer - tksInfraNodeType: - type: string - tksUserNode: - type: integer - tksUserNodeMax: - type: integer - tksUserNodeType: - type: string - type: object github_com_openinfradev_tks-api_pkg_domain.ClusterConfResponse: properties: tksCpNode: @@ -611,6 +597,8 @@ definitions: $ref: '#/definitions/github_com_openinfradev_tks-api_pkg_domain.SimpleUserResponse' description: type: string + favorited: + type: boolean id: type: string isStack: @@ -661,30 +649,6 @@ definitions: tksUserNodeType: type: string type: object - github_com_openinfradev_tks-api_pkg_domain.ClusterStatus: - enum: - - 0 - - 1 - - 2 - - 3 - - 4 - - 5 - - 6 - - 7 - - 8 - - 9 - type: integer - x-enum-varnames: - - ClusterStatus_PENDING - - ClusterStatus_INSTALLING - - ClusterStatus_RUNNING - - ClusterStatus_DELETING - - ClusterStatus_DELETED - - ClusterStatus_INSTALL_ERROR - - ClusterStatus_DELETE_ERROR - - ClusterStatus_BOOTSTRAPPING - - ClusterStatus_BOOTSTRAPPED - - ClusterStatus_BOOTSTRAP_ERROR github_com_openinfradev_tks-api_pkg_domain.CommonProjectResponse: properties: result: @@ -1164,9 +1128,9 @@ definitions: name: type: string organization: - $ref: '#/definitions/github_com_openinfradev_tks-api_pkg_domain.Organization' + $ref: '#/definitions/github_com_openinfradev_tks-api_pkg_domain.OrganizationResponse' role: - $ref: '#/definitions/github_com_openinfradev_tks-api_pkg_domain.Role' + $ref: '#/definitions/github_com_openinfradev_tks-api_pkg_domain.RoleResponse' type: object type: object github_com_openinfradev_tks-api_pkg_domain.DashboardChartResponse: @@ -1243,7 +1207,12 @@ definitions: - accessKeyId - secretAccessKey type: object - github_com_openinfradev_tks-api_pkg_domain.Endpoint: + github_com_openinfradev_tks-api_pkg_domain.DeleteOrganizationResponse: + properties: + id: + type: string + type: object + github_com_openinfradev_tks-api_pkg_domain.EndpointResponse: properties: createdAt: type: string @@ -1251,6 +1220,8 @@ definitions: type: string name: type: string + updatedAt: + type: string type: object github_com_openinfradev_tks-api_pkg_domain.ExistsPolicyTemplateKindResponse: type: object @@ -1338,7 +1309,7 @@ definitions: github_com_openinfradev_tks-api_pkg_domain.GetAppServeAppResponse: properties: appServeApp: - $ref: '#/definitions/github_com_openinfradev_tks-api_pkg_domain.AppServeApp' + $ref: '#/definitions/github_com_openinfradev_tks-api_pkg_domain.AppServeAppResponse' stages: items: $ref: '#/definitions/github_com_openinfradev_tks-api_pkg_domain.StageResponse' @@ -1347,9 +1318,9 @@ definitions: github_com_openinfradev_tks-api_pkg_domain.GetAppServeAppTaskResponse: properties: appServeApp: - $ref: '#/definitions/github_com_openinfradev_tks-api_pkg_domain.AppServeApp' + $ref: '#/definitions/github_com_openinfradev_tks-api_pkg_domain.AppServeAppResponse' appServeAppTask: - $ref: '#/definitions/github_com_openinfradev_tks-api_pkg_domain.AppServeAppTask' + $ref: '#/definitions/github_com_openinfradev_tks-api_pkg_domain.AppServeAppTaskResponse' stages: items: $ref: '#/definitions/github_com_openinfradev_tks-api_pkg_domain.StageResponse' @@ -1409,6 +1380,11 @@ definitions: $ref: '#/definitions/github_com_openinfradev_tks-api_pkg_domain.ClusterNode' type: array type: object + github_com_openinfradev_tks-api_pkg_domain.GetClusterResponse: + properties: + cluster: + $ref: '#/definitions/github_com_openinfradev_tks-api_pkg_domain.ClusterResponse' + type: object github_com_openinfradev_tks-api_pkg_domain.GetClustersResponse: properties: clusters: @@ -1457,9 +1433,9 @@ definitions: name: type: string organization: - $ref: '#/definitions/github_com_openinfradev_tks-api_pkg_domain.Organization' + $ref: '#/definitions/github_com_openinfradev_tks-api_pkg_domain.OrganizationResponse' role: - $ref: '#/definitions/github_com_openinfradev_tks-api_pkg_domain.Role' + $ref: '#/definitions/github_com_openinfradev_tks-api_pkg_domain.RoleResponse' type: object type: object github_com_openinfradev_tks-api_pkg_domain.GetOrganizationResponse: @@ -1670,9 +1646,9 @@ definitions: name: type: string organization: - $ref: '#/definitions/github_com_openinfradev_tks-api_pkg_domain.Organization' + $ref: '#/definitions/github_com_openinfradev_tks-api_pkg_domain.OrganizationResponse' role: - $ref: '#/definitions/github_com_openinfradev_tks-api_pkg_domain.Role' + $ref: '#/definitions/github_com_openinfradev_tks-api_pkg_domain.RoleResponse' updatedAt: type: string type: object @@ -1779,9 +1755,9 @@ definitions: name: type: string organization: - $ref: '#/definitions/github_com_openinfradev_tks-api_pkg_domain.Organization' + $ref: '#/definitions/github_com_openinfradev_tks-api_pkg_domain.OrganizationResponse' role: - $ref: '#/definitions/github_com_openinfradev_tks-api_pkg_domain.Role' + $ref: '#/definitions/github_com_openinfradev_tks-api_pkg_domain.RoleResponse' updatedAt: type: string type: object @@ -1809,11 +1785,11 @@ definitions: name: type: string organization: - $ref: '#/definitions/github_com_openinfradev_tks-api_pkg_domain.Organization' + $ref: '#/definitions/github_com_openinfradev_tks-api_pkg_domain.OrganizationResponse' passwordExpired: type: boolean role: - $ref: '#/definitions/github_com_openinfradev_tks-api_pkg_domain.Role' + $ref: '#/definitions/github_com_openinfradev_tks-api_pkg_domain.RoleResponse' token: type: string type: object @@ -1827,14 +1803,10 @@ definitions: type: array type: object type: object - github_com_openinfradev_tks-api_pkg_domain.Organization: + github_com_openinfradev_tks-api_pkg_domain.OrganizationResponse: properties: createdAt: type: string - creator: - type: string - deletedAt: - $ref: '#/definitions/gorm.DeletedAt' description: type: string id: @@ -1906,53 +1878,45 @@ definitions: type: type: string type: object - github_com_openinfradev_tks-api_pkg_domain.Permission: + github_com_openinfradev_tks-api_pkg_domain.PermissionResponse: properties: ID: type: string children: items: - $ref: '#/definitions/github_com_openinfradev_tks-api_pkg_domain.Permission' + $ref: '#/definitions/github_com_openinfradev_tks-api_pkg_domain.PermissionResponse' type: array - createdAt: - type: string - deletedAt: - $ref: '#/definitions/gorm.DeletedAt' endpoints: items: - $ref: '#/definitions/github_com_openinfradev_tks-api_pkg_domain.Endpoint' + $ref: '#/definitions/github_com_openinfradev_tks-api_pkg_domain.EndpointResponse' type: array - id: - type: integer is_allowed: type: boolean name: type: string parent: - $ref: '#/definitions/github_com_openinfradev_tks-api_pkg_domain.Permission' + $ref: '#/definitions/github_com_openinfradev_tks-api_pkg_domain.PermissionResponse' parent_id: type: string role: - $ref: '#/definitions/github_com_openinfradev_tks-api_pkg_domain.Role' + $ref: '#/definitions/github_com_openinfradev_tks-api_pkg_domain.RoleResponse' role_id: type: string - updatedAt: - type: string type: object - github_com_openinfradev_tks-api_pkg_domain.PermissionSet: + github_com_openinfradev_tks-api_pkg_domain.PermissionSetResponse: properties: configuration: - $ref: '#/definitions/github_com_openinfradev_tks-api_pkg_domain.Permission' + $ref: '#/definitions/github_com_openinfradev_tks-api_pkg_domain.PermissionResponse' dashboard: - $ref: '#/definitions/github_com_openinfradev_tks-api_pkg_domain.Permission' + $ref: '#/definitions/github_com_openinfradev_tks-api_pkg_domain.PermissionResponse' notification: - $ref: '#/definitions/github_com_openinfradev_tks-api_pkg_domain.Permission' + $ref: '#/definitions/github_com_openinfradev_tks-api_pkg_domain.PermissionResponse' project_management: - $ref: '#/definitions/github_com_openinfradev_tks-api_pkg_domain.Permission' + $ref: '#/definitions/github_com_openinfradev_tks-api_pkg_domain.PermissionResponse' security_policy: - $ref: '#/definitions/github_com_openinfradev_tks-api_pkg_domain.Permission' + $ref: '#/definitions/github_com_openinfradev_tks-api_pkg_domain.PermissionResponse' stack: - $ref: '#/definitions/github_com_openinfradev_tks-api_pkg_domain.Permission' + $ref: '#/definitions/github_com_openinfradev_tks-api_pkg_domain.PermissionResponse' type: object github_com_openinfradev_tks-api_pkg_domain.PermittedOrganization: properties: @@ -2191,6 +2155,8 @@ definitions: type: string projectRoleName: type: string + updatedAt: + type: string type: object github_com_openinfradev_tks-api_pkg_domain.ProjectRoleResponse: properties: @@ -2270,14 +2236,12 @@ definitions: usage: type: integer type: object - github_com_openinfradev_tks-api_pkg_domain.Role: + github_com_openinfradev_tks-api_pkg_domain.RoleResponse: properties: createdAt: type: string creator: type: string - deletedAt: - $ref: '#/definitions/gorm.DeletedAt' description: type: string id: @@ -2285,7 +2249,7 @@ definitions: name: type: string organization: - $ref: '#/definitions/github_com_openinfradev_tks-api_pkg_domain.Organization' + $ref: '#/definitions/github_com_openinfradev_tks-api_pkg_domain.OrganizationResponse' organizationId: type: string type: @@ -2335,15 +2299,6 @@ definitions: name: type: string type: object - github_com_openinfradev_tks-api_pkg_domain.SimpleRoleResponse: - properties: - description: - type: string - id: - type: string - name: - type: string - type: object github_com_openinfradev_tks-api_pkg_domain.SimpleStackTemplateResponse: properties: cloudService: @@ -2373,8 +2328,6 @@ definitions: type: string name: type: string - role: - $ref: '#/definitions/github_com_openinfradev_tks-api_pkg_domain.SimpleRoleResponse' type: object github_com_openinfradev_tks-api_pkg_domain.StackConfResponse: properties: @@ -2454,59 +2407,6 @@ definitions: step: type: integer type: object - github_com_openinfradev_tks-api_pkg_domain.StackTemplate: - properties: - cloudService: - type: string - createdAt: - type: string - creator: - $ref: '#/definitions/github_com_openinfradev_tks-api_pkg_domain.User' - creatorId: - type: string - description: - type: string - id: - type: string - kubeType: - type: string - kubeVersion: - type: string - name: - type: string - organizationId: - type: string - organizationIds: - items: - type: string - type: array - organizations: - items: - $ref: '#/definitions/github_com_openinfradev_tks-api_pkg_domain.Organization' - type: array - platform: - type: string - serviceIds: - items: - type: string - type: array - services: - items: - type: integer - type: array - template: - type: string - templateType: - type: string - updatedAt: - type: string - updator: - $ref: '#/definitions/github_com_openinfradev_tks-api_pkg_domain.User' - updatorId: - type: string - version: - type: string - type: object github_com_openinfradev_tks-api_pkg_domain.StackTemplateResponse: properties: cloudService: @@ -2683,9 +2583,9 @@ definitions: name: type: string organization: - $ref: '#/definitions/github_com_openinfradev_tks-api_pkg_domain.Organization' + $ref: '#/definitions/github_com_openinfradev_tks-api_pkg_domain.OrganizationResponse' role: - $ref: '#/definitions/github_com_openinfradev_tks-api_pkg_domain.Role' + $ref: '#/definitions/github_com_openinfradev_tks-api_pkg_domain.RoleResponse' type: object type: object github_com_openinfradev_tks-api_pkg_domain.UpdateOrganizationRequest: @@ -2730,7 +2630,7 @@ definitions: properties: permissions: items: - $ref: '#/definitions/github_com_openinfradev_tks-api_pkg_domain.Permission' + $ref: '#/definitions/github_com_openinfradev_tks-api_pkg_domain.PermissionResponse' type: array type: object github_com_openinfradev_tks-api_pkg_domain.UpdatePolicyTemplateRequest: @@ -2880,50 +2780,13 @@ definitions: name: type: string organization: - $ref: '#/definitions/github_com_openinfradev_tks-api_pkg_domain.Organization' + $ref: '#/definitions/github_com_openinfradev_tks-api_pkg_domain.OrganizationResponse' role: - $ref: '#/definitions/github_com_openinfradev_tks-api_pkg_domain.Role' + $ref: '#/definitions/github_com_openinfradev_tks-api_pkg_domain.RoleResponse' updatedAt: type: string type: object type: object - github_com_openinfradev_tks-api_pkg_domain.User: - properties: - accountId: - type: string - createdAt: - type: string - creator: - type: string - department: - type: string - description: - type: string - email: - type: string - id: - type: string - name: - type: string - organization: - $ref: '#/definitions/github_com_openinfradev_tks-api_pkg_domain.Organization' - organizationId: - type: string - password: - type: string - passwordExpired: - type: boolean - passwordUpdatedAt: - type: string - role: - $ref: '#/definitions/github_com_openinfradev_tks-api_pkg_domain.Role' - roleId: - type: string - token: - type: string - updatedAt: - type: string - type: object github_com_openinfradev_tks-api_pkg_domain.VerifyIdentityForLostIdRequest: properties: email: @@ -2984,9 +2847,9 @@ definitions: name: type: string organization: - $ref: '#/definitions/github_com_openinfradev_tks-api_pkg_domain.Organization' + $ref: '#/definitions/github_com_openinfradev_tks-api_pkg_domain.OrganizationResponse' role: - $ref: '#/definitions/github_com_openinfradev_tks-api_pkg_domain.Role' + $ref: '#/definitions/github_com_openinfradev_tks-api_pkg_domain.RoleResponse' updatedAt: type: string type: object @@ -3032,9 +2895,9 @@ definitions: name: type: string organization: - $ref: '#/definitions/github_com_openinfradev_tks-api_pkg_domain.Organization' + $ref: '#/definitions/github_com_openinfradev_tks-api_pkg_domain.OrganizationResponse' role: - $ref: '#/definitions/github_com_openinfradev_tks-api_pkg_domain.Role' + $ref: '#/definitions/github_com_openinfradev_tks-api_pkg_domain.RoleResponse' updatedAt: type: string type: object @@ -3049,27 +2912,133 @@ definitions: type: integer text: type: string - type: object - gorm.DeletedAt: - properties: - time: + type: object +host: tks-api-dev.taco-cat.xyz +info: + contact: + email: taekyu.kang@sk.com + name: taekyu.kang@sk.com + description: This is backend api service for tks platform + license: + name: Apache 2.0 + url: http://www.apache.org/licenses/LICENSE-2.0.html + title: tks-api service + version: "1.0" +paths: + /admin/audits: + get: + consumes: + - application/json + description: Get Audits + parameters: + - description: pageSize + in: query + name: limit + type: string + - description: pageNumber + in: query + name: page + type: string + - description: sortColumn + in: query + name: soertColumn + type: string + - description: sortOrder + in: query + name: sortOrder + type: string + - collectionFormat: csv + description: filters + in: query + items: + type: string + name: filter + type: array + - collectionFormat: csv + description: filters + in: query + items: + type: string + name: or + type: array + produces: + - application/json + responses: + "200": + description: OK + schema: + $ref: '#/definitions/github_com_openinfradev_tks-api_pkg_domain.GetAuditsResponse' + security: + - JWT: [] + summary: Get Audits + tags: + - Audits + post: + consumes: + - application/json + description: Create Audit + parameters: + - description: create audit request + in: body + name: body + required: true + schema: + $ref: '#/definitions/github_com_openinfradev_tks-api_pkg_domain.CreateAuditRequest' + produces: + - application/json + responses: + "200": + description: OK + schema: + $ref: '#/definitions/github_com_openinfradev_tks-api_pkg_domain.CreateAuditResponse' + security: + - JWT: [] + summary: Create Audit + tags: + - Audits + /admin/audits/{auditId}: + delete: + consumes: + - application/json + description: Delete Audit + parameters: + - description: auditId + in: path + name: auditId + required: true + type: string + produces: + - application/json + responses: + "200": + description: OK + security: + - JWT: [] + summary: Delete Audit 'NOT IMPLEMENTED' + tags: + - Audits + get: + consumes: + - application/json + description: Get Audit + parameters: + - description: auditId + in: path + name: auditId + required: true type: string - valid: - description: Valid is true if Time is not NULL - type: boolean - type: object -host: tks-api-dev.taco-cat.xyz -info: - contact: - email: taekyu.kang@sk.com - name: taekyu.kang@sk.com - description: This is backend api service for tks platform - license: - name: Apache 2.0 - url: http://www.apache.org/licenses/LICENSE-2.0.html - title: tks-api service - version: "1.0" -paths: + produces: + - application/json + responses: + "200": + description: OK + schema: + $ref: '#/definitions/github_com_openinfradev_tks-api_pkg_domain.GetAuditResponse' + security: + - JWT: [] + summary: Get Audit + tags: + - Audits /admin/organizations/{organizationId}/projects: get: consumes: @@ -3586,7 +3555,7 @@ paths: $ref: '#/definitions/github_com_openinfradev_tks-api_pkg_domain.CreateStackTemplateResponse' security: - JWT: [] - summary: Create StackTemplate 'NOT IMPLEMENTED' + summary: Create StackTemplate tags: - StackTemplates /admin/stack-templates/{stackTemplateId}: @@ -3607,7 +3576,7 @@ paths: description: OK security: - JWT: [] - summary: Delete StackTemplate 'NOT IMPLEMENTED' + summary: Delete StackTemplate tags: - StackTemplates get: @@ -3650,7 +3619,7 @@ paths: description: OK security: - JWT: [] - summary: Update StackTemplate 'NOT IMPLEMENTED' + summary: Update StackTemplate tags: - StackTemplates /admin/stack-templates/{stackTemplateId}/organizations: @@ -4106,8 +4075,6 @@ paths: responses: "200": description: OK - schema: - $ref: '#/definitions/github_com_openinfradev_tks-api_pkg_domain.Cluster' security: - JWT: [] summary: Delete cluster @@ -4129,7 +4096,7 @@ paths: "200": description: OK schema: - $ref: '#/definitions/github_com_openinfradev_tks-api_pkg_domain.Cluster' + $ref: '#/definitions/github_com_openinfradev_tks-api_pkg_domain.GetClusterResponse' security: - JWT: [] summary: Get cluster @@ -4342,7 +4309,7 @@ paths: "200": description: OK schema: - $ref: '#/definitions/github_com_openinfradev_tks-api_pkg_domain.Organization' + $ref: '#/definitions/github_com_openinfradev_tks-api_pkg_domain.DeleteOrganizationResponse' security: - JWT: [] summary: Delete organization @@ -4544,120 +4511,6 @@ paths: summary: Create alert action tags: - Alerts - /organizations/{organizationId}/audits: - get: - consumes: - - application/json - description: Get Audits - parameters: - - description: pageSize - in: query - name: limit - type: string - - description: pageNumber - in: query - name: page - type: string - - description: sortColumn - in: query - name: soertColumn - type: string - - description: sortOrder - in: query - name: sortOrder - type: string - - collectionFormat: csv - description: filters - in: query - items: - type: string - name: filter - type: array - - collectionFormat: csv - description: filters - in: query - items: - type: string - name: or - type: array - produces: - - application/json - responses: - "200": - description: OK - schema: - $ref: '#/definitions/github_com_openinfradev_tks-api_pkg_domain.GetAuditsResponse' - security: - - JWT: [] - summary: Get Audits - tags: - - Audits - post: - consumes: - - application/json - description: Create Audit - parameters: - - description: create audit request - in: body - name: body - required: true - schema: - $ref: '#/definitions/github_com_openinfradev_tks-api_pkg_domain.CreateAuditRequest' - produces: - - application/json - responses: - "200": - description: OK - schema: - $ref: '#/definitions/github_com_openinfradev_tks-api_pkg_domain.CreateAuditResponse' - security: - - JWT: [] - summary: Create Audit - tags: - - Audits - /organizations/{organizationId}/audits/{auditId}: - delete: - consumes: - - application/json - description: Delete Audit - parameters: - - description: auditId - in: path - name: auditId - required: true - type: string - produces: - - application/json - responses: - "200": - description: OK - security: - - JWT: [] - summary: Delete Audit 'NOT IMPLEMENTED' - tags: - - Audits - get: - consumes: - - application/json - description: Get Audit - parameters: - - description: auditId - in: path - name: auditId - required: true - type: string - produces: - - application/json - responses: - "200": - description: OK - schema: - $ref: '#/definitions/github_com_openinfradev_tks-api_pkg_domain.GetAuditResponse' - security: - - JWT: [] - summary: Get Audit - tags: - - Audits /organizations/{organizationId}/cloud-accounts: get: consumes: @@ -5366,7 +5219,7 @@ paths: description: OK schema: items: - $ref: '#/definitions/github_com_openinfradev_tks-api_pkg_domain.AppServeApp' + $ref: '#/definitions/github_com_openinfradev_tks-api_internal_model.AppServeApp' type: array security: - JWT: [] @@ -5733,7 +5586,7 @@ paths: description: OK schema: items: - $ref: '#/definitions/github_com_openinfradev_tks-api_pkg_domain.AppServeApp' + $ref: '#/definitions/github_com_openinfradev_tks-api_internal_model.AppServeApp' type: array security: - JWT: [] @@ -6657,7 +6510,7 @@ paths: "200": description: OK schema: - $ref: '#/definitions/github_com_openinfradev_tks-api_pkg_domain.PermissionSet' + $ref: '#/definitions/github_com_openinfradev_tks-api_pkg_domain.PermissionSetResponse' security: - JWT: [] summary: Get Permissions By Role ID @@ -6689,6 +6542,64 @@ paths: summary: Update Permissions By Role ID tags: - Permission + /organizations/{organizationId}/stack-templates: + get: + consumes: + - application/json + description: Get Organization StackTemplates + parameters: + - description: pageSize + in: query + name: limit + type: string + - description: pageNumber + in: query + name: page + type: string + - description: sortColumn + in: query + name: soertColumn + type: string + - description: sortOrder + in: query + name: sortOrder + type: string + - collectionFormat: csv + description: filters + in: query + items: + type: string + name: filters + type: array + produces: + - application/json + responses: + "200": + description: OK + schema: + $ref: '#/definitions/github_com_openinfradev_tks-api_pkg_domain.GetStackTemplatesResponse' + security: + - JWT: [] + summary: Get Organization StackTemplates + tags: + - StackTemplates + /organizations/{organizationId}/stack-templates/{stackTemplateId}: + get: + consumes: + - application/json + description: Get Organization StackTemplate + produces: + - application/json + responses: + "200": + description: OK + schema: + $ref: '#/definitions/github_com_openinfradev_tks-api_pkg_domain.GetStackTemplateResponse' + security: + - JWT: [] + summary: Get Organization StackTemplate + tags: + - StackTemplates /organizations/{organizationId}/stacks: get: consumes: @@ -7079,8 +6990,6 @@ paths: responses: "200": description: OK - schema: - $ref: '#/definitions/github_com_openinfradev_tks-api_pkg_domain.User' security: - JWT: [] summary: Delete user @@ -7236,7 +7145,7 @@ paths: "200": description: OK schema: - $ref: '#/definitions/github_com_openinfradev_tks-api_pkg_domain.PermissionSet' + $ref: '#/definitions/github_com_openinfradev_tks-api_pkg_domain.PermissionSetResponse' security: - JWT: [] summary: Get Permission Templates diff --git a/internal/database/database.go b/internal/database/database.go index 1fd29171..4c34a427 100644 --- a/internal/database/database.go +++ b/internal/database/database.go @@ -14,7 +14,6 @@ import ( "github.com/openinfradev/tks-api/internal/model" "github.com/openinfradev/tks-api/internal/repository" - "github.com/openinfradev/tks-api/pkg/domain" ) func InitDB() (*gorm.DB, error) { @@ -60,68 +59,68 @@ func migrateSchema(db *gorm.DB) error { if err := db.AutoMigrate(&repository.CacheEmailCode{}); err != nil { return err } - if err := db.AutoMigrate(&domain.User{}); err != nil { + if err := db.AutoMigrate(&model.User{}); err != nil { return err } - if err := db.AutoMigrate(&domain.Role{}); err != nil { + if err := db.AutoMigrate(&model.Role{}); err != nil { return err } // Organization - if err := db.AutoMigrate(&domain.Organization{}); err != nil { + if err := db.AutoMigrate(&model.Organization{}); err != nil { return err } // CloudAccount - if err := db.AutoMigrate(&repository.CloudAccount{}); err != nil { + if err := db.AutoMigrate(&model.CloudAccount{}); err != nil { return err } // StackTemplate - if err := db.AutoMigrate(&repository.StackTemplate{}); err != nil { + if err := db.AutoMigrate(&model.StackTemplate{}); err != nil { return err } // Cluster - if err := db.AutoMigrate(&repository.Cluster{}); err != nil { + if err := db.AutoMigrate(&model.Cluster{}); err != nil { return err } - if err := db.AutoMigrate(&repository.ClusterFavorite{}); err != nil { + if err := db.AutoMigrate(&model.ClusterFavorite{}); err != nil { return err } // Services - if err := db.AutoMigrate(&repository.AppGroup{}); err != nil { + if err := db.AutoMigrate(&model.AppGroup{}); err != nil { return err } - if err := db.AutoMigrate(&repository.Application{}); err != nil { + if err := db.AutoMigrate(&model.Application{}); err != nil { return err } // AppServe - if err := db.AutoMigrate(&domain.AppServeApp{}); err != nil { + if err := db.AutoMigrate(&model.AppServeApp{}); err != nil { return err } - if err := db.AutoMigrate(&domain.AppServeAppTask{}); err != nil { + if err := db.AutoMigrate(&model.AppServeAppTask{}); err != nil { return err } // Alert - if err := db.AutoMigrate(&repository.Alert{}); err != nil { + if err := db.AutoMigrate(&model.Alert{}); err != nil { return err } - if err := db.AutoMigrate(&repository.AlertAction{}); err != nil { + if err := db.AutoMigrate(&model.AlertAction{}); err != nil { return err } // Role - if err := db.AutoMigrate(&domain.Role{}); err != nil { + if err := db.AutoMigrate(&model.Role{}); err != nil { return err } - if err := db.AutoMigrate(&domain.Permission{}); err != nil { + if err := db.AutoMigrate(&model.Permission{}); err != nil { return err } - if err := db.AutoMigrate(&domain.Endpoint{}); err != nil { + if err := db.AutoMigrate(&model.Endpoint{}); err != nil { return err } @@ -139,6 +138,20 @@ func migrateSchema(db *gorm.DB) error { return err } + // Audit + if err := db.AutoMigrate(&model.Audit{}); err != nil { + return err + } + + // PolicyTemplate + if err := db.AutoMigrate(&model.PolicyTemplateSupportedVersion{}); err != nil { + return err + } + + if err := db.AutoMigrate(&model.PolicyTemplate{}); err != nil { + return err + } + return nil } @@ -172,7 +185,7 @@ func EnsureDefaultRows(db *gorm.DB) error { } for _, ep := range api.ApiMap { if _, ok := storedEps[ep.Name]; !ok { - if err := repoFactory.Endpoint.Create(&domain.Endpoint{ + if err := repoFactory.Endpoint.Create(&model.Endpoint{ Name: ep.Name, Group: ep.Group, }); err != nil { @@ -181,19 +194,5 @@ func EnsureDefaultRows(db *gorm.DB) error { } } - // Audit - if err := db.AutoMigrate(&repository.Audit{}); err != nil { - return err - } - - // PolicyTemplate - if err := db.AutoMigrate(&repository.PolicyTemplateSupportedVersion{}); err != nil { - return err - } - - if err := db.AutoMigrate(&repository.PolicyTemplate{}); err != nil { - return err - } - return nil } diff --git a/internal/delivery/api/endpoint.go b/internal/delivery/api/endpoint.go index 9d7c0966..4c6a3bdd 100644 --- a/internal/delivery/api/endpoint.go +++ b/internal/delivery/api/endpoint.go @@ -102,6 +102,8 @@ const ( Admin_UpdateStackTemplate Admin_DeleteStackTemplate Admin_UpdateStackTemplateOrganizations + GetOrganizationStackTemplates + GetOrganizationStackTemplate // Dashboard GetChartsDashboard // 대시보드/대시보드/조회 @@ -119,7 +121,7 @@ const ( // Stack GetStacks // 스택관리/조회 - CreateStack // // 스택관리/생성 + CreateStack // 스택관리/생성 CheckStackName // 스택관리/조회 GetStack // 스택관리/조회 UpdateStack // 스택관리/수정 diff --git a/internal/delivery/api/generated_endpoints.go.go b/internal/delivery/api/generated_endpoints.go.go index aeea2305..32a81fb6 100644 --- a/internal/delivery/api/generated_endpoints.go.go +++ b/internal/delivery/api/generated_endpoints.go.go @@ -303,6 +303,14 @@ var ApiMap = map[Endpoint]EndpointInfo{ Name: "Admin_UpdateStackTemplateOrganizations", Group: "StackTemplate", }, + GetOrganizationStackTemplates: { + Name: "GetOrganizationStackTemplates", + Group: "StackTemplate", + }, + GetOrganizationStackTemplate: { + Name: "GetOrganizationStackTemplate", + Group: "StackTemplate", + }, GetChartsDashboard: { Name: "GetChartsDashboard", Group: "Dashboard", @@ -880,6 +888,10 @@ func (e Endpoint) String() string { return "Admin_DeleteStackTemplate" case Admin_UpdateStackTemplateOrganizations: return "Admin_UpdateStackTemplateOrganizations" + case GetOrganizationStackTemplates: + return "GetOrganizationStackTemplates" + case GetOrganizationStackTemplate: + return "GetOrganizationStackTemplate" case GetChartsDashboard: return "GetChartsDashboard" case GetChartDashboard: @@ -1248,6 +1260,10 @@ func GetEndpoint(name string) Endpoint { return Admin_DeleteStackTemplate case "Admin_UpdateStackTemplateOrganizations": return Admin_UpdateStackTemplateOrganizations + case "GetOrganizationStackTemplates": + return GetOrganizationStackTemplates + case "GetOrganizationStackTemplate": + return GetOrganizationStackTemplate case "GetChartsDashboard": return GetChartsDashboard case "GetChartDashboard": diff --git a/internal/delivery/http/alert.go b/internal/delivery/http/alert.go index 5b03746f..bf878aef 100644 --- a/internal/delivery/http/alert.go +++ b/internal/delivery/http/alert.go @@ -8,6 +8,7 @@ import ( "github.com/google/uuid" "github.com/gorilla/mux" "github.com/openinfradev/tks-api/internal/helper" + "github.com/openinfradev/tks-api/internal/model" "github.com/openinfradev/tks-api/internal/pagination" "github.com/openinfradev/tks-api/internal/serializer" "github.com/openinfradev/tks-api/internal/usecase" @@ -272,7 +273,7 @@ func (h *AlertHandler) CreateAlertAction(w http.ResponseWriter, r *http.Request) log.InfoWithContext(r.Context(), "alert : ", helper.ModelToJson(input)) - var dto domain.AlertAction + var dto model.AlertAction if err = serializer.Map(input, &dto); err != nil { log.InfoWithContext(r.Context(), err) } diff --git a/internal/delivery/http/app-group.go b/internal/delivery/http/app-group.go index 26dbb840..27543035 100644 --- a/internal/delivery/http/app-group.go +++ b/internal/delivery/http/app-group.go @@ -6,6 +6,7 @@ import ( "github.com/gorilla/mux" "github.com/openinfradev/tks-api/internal/helper" + "github.com/openinfradev/tks-api/internal/model" "github.com/openinfradev/tks-api/internal/pagination" "github.com/openinfradev/tks-api/internal/serializer" "github.com/openinfradev/tks-api/internal/usecase" @@ -43,7 +44,7 @@ func (h *AppGroupHandler) CreateAppGroup(w http.ResponseWriter, r *http.Request) return } - var dto domain.AppGroup + var dto model.AppGroup if err = serializer.Map(input, &dto); err != nil { log.InfoWithContext(r.Context(), err) } @@ -264,7 +265,7 @@ func (h *AppGroupHandler) CreateApplication(w http.ResponseWriter, r *http.Reque return } - var dto domain.Application + var dto model.Application if err := serializer.Map(input, &dto); err != nil { log.InfoWithContext(r.Context(), err) } diff --git a/internal/delivery/http/app-serve-app.go b/internal/delivery/http/app-serve-app.go index d738685f..aa6f92b1 100644 --- a/internal/delivery/http/app-serve-app.go +++ b/internal/delivery/http/app-serve-app.go @@ -12,6 +12,7 @@ import ( "github.com/gorilla/mux" "github.com/openinfradev/tks-api/internal" + "github.com/openinfradev/tks-api/internal/model" "github.com/openinfradev/tks-api/internal/pagination" "github.com/openinfradev/tks-api/internal/serializer" "github.com/openinfradev/tks-api/internal/usecase" @@ -115,7 +116,7 @@ func (h *AppServeAppHandler) CreateAppServeApp(w http.ResponseWriter, r *http.Re (appReq).SetDefaultValue() - var app domain.AppServeApp + var app model.AppServeApp if err = serializer.Map(appReq, &app); err != nil { ErrorJSON(w, r, httpErrors.NewBadRequestError(err, "", "")) return @@ -131,7 +132,7 @@ func (h *AppServeAppHandler) CreateAppServeApp(w http.ResponseWriter, r *http.Re app.Status = "PREPARING" app.CreatedAt = now - var task domain.AppServeAppTask + var task model.AppServeAppTask if err = serializer.Map(appReq, &task); err != nil { ErrorJSON(w, r, httpErrors.NewBadRequestError(err, "", "")) return @@ -230,7 +231,7 @@ func (h *AppServeAppHandler) CreateAppServeApp(w http.ResponseWriter, r *http.Re // @Param soertColumn query string false "sortColumn" // @Param sortOrder query string false "sortOrder" // @Param filters query []string false "filters" -// @Success 200 {object} []domain.AppServeApp +// @Success 200 {object} []model.AppServeApp // @Router /organizations/{organizationId}/projects/{projectId}/app-serve-apps [get] // @Security JWT func (h *AppServeAppHandler) GetAppServeApps(w http.ResponseWriter, r *http.Request) { @@ -264,7 +265,13 @@ func (h *AppServeAppHandler) GetAppServeApps(w http.ResponseWriter, r *http.Requ } var out domain.GetAppServeAppsResponse - out.AppServeApps = apps + out.AppServeApps = make([]domain.AppServeAppResponse, len(apps)) + for i, app := range apps { + if err := serializer.Map(app, &out.AppServeApps[i]); err != nil { + log.InfoWithContext(r.Context(), err) + continue + } + } if out.Pagination, err = pg.Response(); err != nil { log.InfoWithContext(r.Context(), err) @@ -317,7 +324,7 @@ func (h *AppServeAppHandler) GetAppServeApp(w http.ResponseWriter, r *http.Reque return } - newTasks := make([]domain.AppServeAppTask, 0) + newTasks := make([]model.AppServeAppTask, 0) for idx, t := range app.AppServeAppTasks { // Rollbacking to latest task should be blocked. @@ -330,7 +337,10 @@ func (h *AppServeAppHandler) GetAppServeApp(w http.ResponseWriter, r *http.Reque app.AppServeAppTasks = newTasks var out domain.GetAppServeAppResponse - out.AppServeApp = *app + if err := serializer.Map(app, &out.AppServeApp); err != nil { + log.InfoWithContext(r.Context(), err) + } + // NOTE: makeStages function's been changed to use task instead of app //out.Stages = makeStages(app) @@ -377,7 +387,9 @@ func (h *AppServeAppHandler) GetAppServeAppLatestTask(w http.ResponseWriter, r * } var out domain.GetAppServeAppTaskResponse - out.AppServeAppTask = *task + if err := serializer.Map(task, &out.AppServeAppTask); err != nil { + log.InfoWithContext(r.Context(), err) + } ResponseJSON(w, r, http.StatusOK, out) } @@ -435,7 +447,7 @@ func (h *AppServeAppHandler) GetNumOfAppsOnStack(w http.ResponseWriter, r *http. // @Param sortColumn query string false "sortColumn" // @Param sortOrder query string false "sortOrder" // @Param filters query []string false "filters" -// @Success 200 {object} []domain.AppServeApp +// @Success 200 {object} []model.AppServeApp // @Router /organizations/{organizationId}/projects/{projectId}/app-serve-apps/{appId}/tasks [get] // @Security JWT func (h *AppServeAppHandler) GetAppServeAppTasksByAppId(w http.ResponseWriter, r *http.Request) { @@ -463,7 +475,13 @@ func (h *AppServeAppHandler) GetAppServeAppTasksByAppId(w http.ResponseWriter, r } var out domain.GetAppServeAppTasksResponse - out.AppServeAppTasks = tasks + out.AppServeAppTasks = make([]domain.AppServeAppTaskResponse, len(tasks)) + for i, task := range tasks { + if err := serializer.Map(task, &out.AppServeAppTasks[i]); err != nil { + log.InfoWithContext(r.Context(), err) + continue + } + } if out.Pagination, err = pg.Response(); err != nil { log.InfoWithContext(r.Context(), err) @@ -533,14 +551,19 @@ func (h *AppServeAppHandler) GetAppServeAppTaskDetail(w http.ResponseWriter, r * } var out domain.GetAppServeAppTaskResponse - out.AppServeApp = *app - out.AppServeAppTask = *task + if err := serializer.Map(app, &out.AppServeApp); err != nil { + log.InfoWithContext(r.Context(), err) + } + if err := serializer.Map(task, &out.AppServeAppTask); err != nil { + log.InfoWithContext(r.Context(), err) + } + out.Stages = makeStages(task, app) ResponseJSON(w, r, http.StatusOK, out) } -func makeStages(task *domain.AppServeAppTask, app *domain.AppServeApp) []domain.StageResponse { +func makeStages(task *model.AppServeAppTask, app *model.AppServeApp) []domain.StageResponse { stages := make([]domain.StageResponse, 0) var stage domain.StageResponse @@ -582,7 +605,7 @@ func makeStages(task *domain.AppServeAppTask, app *domain.AppServeApp) []domain. return stages } -func makeStage(task *domain.AppServeAppTask, app *domain.AppServeApp, pl string) domain.StageResponse { +func makeStage(task *model.AppServeAppTask, app *model.AppServeApp, pl string) domain.StageResponse { taskStatus := task.Status strategy := task.Strategy @@ -774,7 +797,7 @@ func (h *AppServeAppHandler) UpdateAppServeApp(w http.ResponseWriter, r *http.Re // from existing app config. //appReq.SetDefaultValue() - var task domain.AppServeAppTask + var task model.AppServeAppTask //tasks := app.AppServeAppTasks //sort.Slice(tasks, func(i, j int) bool { // return tasks[i].CreatedAt.String() > tasks[j].CreatedAt.String() diff --git a/internal/delivery/http/audit.go b/internal/delivery/http/audit.go index 395d9112..2a7b2b99 100644 --- a/internal/delivery/http/audit.go +++ b/internal/delivery/http/audit.go @@ -34,7 +34,7 @@ func NewAuditHandler(h usecase.Usecase) *AuditHandler { // @Produce json // @Param body body domain.CreateAuditRequest true "create audit request" // @Success 200 {object} domain.CreateAuditResponse -// @Router /organizations/{organizationId}/audits [post] +// @Router /admin/audits [post] // @Security JWT func (h *AuditHandler) CreateAudit(w http.ResponseWriter, r *http.Request) { ErrorJSON(w, r, fmt.Errorf("need implementation")) @@ -54,19 +54,12 @@ func (h *AuditHandler) CreateAudit(w http.ResponseWriter, r *http.Request) { // @Param filter query []string false "filters" // @Param or query []string false "filters" // @Success 200 {object} domain.GetAuditsResponse -// @Router /organizations/{organizationId}/audits [get] +// @Router /admin/audits [get] // @Security JWT func (h *AuditHandler) GetAudits(w http.ResponseWriter, r *http.Request) { - vars := mux.Vars(r) - organizationId, ok := vars["organizationId"] - if !ok { - ErrorJSON(w, r, httpErrors.NewBadRequestError(fmt.Errorf("Invalid organizationId"), "C_INVALID_ORGANIZATION_ID", "")) - return - } - urlParams := r.URL.Query() pg := pagination.NewPagination(&urlParams) - audits, err := h.usecase.Fetch(r.Context(), organizationId, pg) + audits, err := h.usecase.Fetch(r.Context(), pg) if err != nil { ErrorJSON(w, r, err) return @@ -96,7 +89,7 @@ func (h *AuditHandler) GetAudits(w http.ResponseWriter, r *http.Request) { // @Produce json // @Param auditId path string true "auditId" // @Success 200 {object} domain.GetAuditResponse -// @Router /organizations/{organizationId}/audits/{auditId} [get] +// @Router /admin/audits/{auditId} [get] // @Security JWT func (h *AuditHandler) GetAudit(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) @@ -137,7 +130,7 @@ func (h *AuditHandler) GetAudit(w http.ResponseWriter, r *http.Request) { // @Produce json // @Param auditId path string true "auditId" // @Success 200 {object} nil -// @Router /organizations/{organizationId}/audits/{auditId} [delete] +// @Router /admin/audits/{auditId} [delete] // @Security JWT func (h *AuditHandler) DeleteAudit(w http.ResponseWriter, r *http.Request) { ErrorJSON(w, r, fmt.Errorf("need implementation")) diff --git a/internal/delivery/http/auth.go b/internal/delivery/http/auth.go index 72a56812..d2fea4d3 100644 --- a/internal/delivery/http/auth.go +++ b/internal/delivery/http/auth.go @@ -7,6 +7,7 @@ import ( "github.com/openinfradev/tks-api/internal" "github.com/openinfradev/tks-api/internal/middleware/audit" "github.com/openinfradev/tks-api/internal/middleware/auth/request" + "github.com/openinfradev/tks-api/internal/model" "github.com/openinfradev/tks-api/internal/serializer" "github.com/openinfradev/tks-api/internal/usecase" "github.com/openinfradev/tks-api/pkg/domain" @@ -61,7 +62,7 @@ func (h *AuthHandler) Login(w http.ResponseWriter, r *http.Request) { user, err := h.usecase.Login(input.AccountId, input.Password, input.OrganizationId) if err != nil { errorResponse, _ := httpErrors.ErrorResponse(err) - _, _ = h.auditUsecase.Create(r.Context(), domain.Audit{ + _, _ = h.auditUsecase.Create(r.Context(), model.Audit{ OrganizationId: input.OrganizationId, Group: "Auth", Message: fmt.Sprintf("[%s]님이 로그인에 실패하였습니다.", input.AccountId), @@ -73,7 +74,7 @@ func (h *AuthHandler) Login(w http.ResponseWriter, r *http.Request) { ErrorJSON(w, r, err) return } else { - _, _ = h.auditUsecase.Create(r.Context(), domain.Audit{ + _, _ = h.auditUsecase.Create(r.Context(), model.Audit{ OrganizationId: input.OrganizationId, Group: "Auth", Message: fmt.Sprintf("[%s]님이 로그인 하였습니다.", input.AccountId), diff --git a/internal/delivery/http/cloud-account.go b/internal/delivery/http/cloud-account.go index 15b4f6a1..5c29a04d 100644 --- a/internal/delivery/http/cloud-account.go +++ b/internal/delivery/http/cloud-account.go @@ -7,6 +7,7 @@ import ( "github.com/google/uuid" "github.com/gorilla/mux" "github.com/openinfradev/tks-api/internal/middleware/auth/request" + "github.com/openinfradev/tks-api/internal/model" "github.com/openinfradev/tks-api/internal/pagination" "github.com/openinfradev/tks-api/internal/serializer" "github.com/openinfradev/tks-api/internal/usecase" @@ -53,7 +54,7 @@ func (h *CloudAccountHandler) CreateCloudAccount(w http.ResponseWriter, r *http. return } - var dto domain.CloudAccount + var dto model.CloudAccount if err = serializer.Map(input, &dto); err != nil { log.InfoWithContext(r.Context(), err) } @@ -198,7 +199,7 @@ func (h *CloudAccountHandler) UpdateCloudAccount(w http.ResponseWriter, r *http. return } - var dto domain.CloudAccount + var dto model.CloudAccount if err = serializer.Map(input, &dto); err != nil { log.InfoWithContext(r.Context(), err) } @@ -248,7 +249,7 @@ func (h *CloudAccountHandler) DeleteCloudAccount(w http.ResponseWriter, r *http. return } - var dto domain.CloudAccount + var dto model.CloudAccount if err = serializer.Map(input, &dto); err != nil { log.InfoWithContext(r.Context(), err) } @@ -295,7 +296,11 @@ func (h *CloudAccountHandler) DeleteForceCloudAccount(w http.ResponseWriter, r * return } - ResponseJSON(w, r, http.StatusOK, nil) + out := domain.DeleteCloudAccountResponse{ + ID: cloudAccountId, + } + + ResponseJSON(w, r, http.StatusOK, out) } // CheckCloudAccountName godoc diff --git a/internal/delivery/http/cluster.go b/internal/delivery/http/cluster.go index 1f8fb6a9..d0811b04 100644 --- a/internal/delivery/http/cluster.go +++ b/internal/delivery/http/cluster.go @@ -4,8 +4,8 @@ import ( "fmt" "net/http" - "github.com/google/uuid" "github.com/gorilla/mux" + "github.com/openinfradev/tks-api/internal/model" "github.com/openinfradev/tks-api/internal/pagination" "github.com/openinfradev/tks-api/internal/serializer" "github.com/openinfradev/tks-api/internal/usecase" @@ -58,6 +58,13 @@ func (h *ClusterHandler) GetClusters(w http.ResponseWriter, r *http.Request) { log.InfoWithContext(r.Context(), err) continue } + + if cluster.Favorites != nil && len(*cluster.Favorites) > 0 { + out.Clusters[i].Favorited = true + } else { + out.Clusters[i].Favorited = false + } + } if out.Pagination, err = pg.Response(); err != nil { @@ -75,7 +82,7 @@ func (h *ClusterHandler) GetClusters(w http.ResponseWriter, r *http.Request) { // @Accept json // @Produce json // @Param clusterId path string true "clusterId" -// @Success 200 {object} domain.Cluster +// @Success 200 {object} domain.GetClusterResponse // @Router /clusters/{clusterId} [get] // @Security JWT func (h *ClusterHandler) GetCluster(w http.ResponseWriter, r *http.Request) { @@ -150,19 +157,13 @@ func (h *ClusterHandler) CreateCluster(w http.ResponseWriter, r *http.Request) { return } - var dto domain.Cluster + var dto model.Cluster if err = serializer.Map(input, &dto); err != nil { log.InfoWithContext(r.Context(), err) } - if err = serializer.Map(input, &dto.Conf); err != nil { - log.InfoWithContext(r.Context(), err) - } - - // [TODO] set default value dto.ClusterType = domain.ClusterType_USER - dto.Conf.SetDefault() - log.InfoWithContext(r.Context(), dto.Conf) + dto.SetDefaultConf() //txHandle := r.Context().Value("txHandle").(*gorm.DB) clusterId := domain.ClusterId("") @@ -210,18 +211,13 @@ func (h *ClusterHandler) ImportCluster(w http.ResponseWriter, r *http.Request) { return } - var dto domain.Cluster + var dto model.Cluster if err = serializer.Map(input, &dto); err != nil { log.InfoWithContext(r.Context(), err) } + dto.SetDefaultConf() - if err = serializer.Map(input, &dto.Conf); err != nil { - log.InfoWithContext(r.Context(), err) - } - dto.Conf.SetDefault() - log.InfoWithContext(r.Context(), dto.Conf) - - dto.CloudAccountId = uuid.Nil + dto.CloudAccountId = nil clusterId, err := h.usecase.Import(r.Context(), dto) if err != nil { ErrorJSON(w, r, err) @@ -270,7 +266,7 @@ func (h *ClusterHandler) InstallCluster(w http.ResponseWriter, r *http.Request) // @Accept json // @Produce json // @Param clusterId path string true "clusterId" -// @Success 200 {object} domain.Cluster +// @Success 200 {object} nil // @Router /clusters/{clusterId} [delete] // @Security JWT func (h *ClusterHandler) DeleteCluster(w http.ResponseWriter, r *http.Request) { diff --git a/internal/delivery/http/handler.go b/internal/delivery/http/handler.go index 680c338d..d2b6e180 100644 --- a/internal/delivery/http/handler.go +++ b/internal/delivery/http/handler.go @@ -1,6 +1,7 @@ package http import ( + "bytes" "encoding/json" "errors" "io" @@ -49,6 +50,7 @@ func UnmarshalRequestInput(r *http.Request, in any) error { if err != nil { return err } + r.Body = io.NopCloser(bytes.NewBuffer(body)) err = json.Unmarshal(body, &in) if err != nil { diff --git a/internal/delivery/http/organization.go b/internal/delivery/http/organization.go index 26bbb8d7..264a3611 100644 --- a/internal/delivery/http/organization.go +++ b/internal/delivery/http/organization.go @@ -6,6 +6,7 @@ import ( "github.com/gorilla/mux" "github.com/openinfradev/tks-api/internal/middleware/auth/request" + "github.com/openinfradev/tks-api/internal/model" "github.com/openinfradev/tks-api/internal/pagination" "github.com/openinfradev/tks-api/internal/serializer" "github.com/openinfradev/tks-api/internal/usecase" @@ -52,7 +53,7 @@ func (h *OrganizationHandler) CreateOrganization(w http.ResponseWriter, r *http. } ctx := r.Context() - var organization domain.Organization + var organization model.Organization if err = serializer.Map(input, &organization); err != nil { log.ErrorWithContext(r.Context(), err) } @@ -66,7 +67,7 @@ func (h *OrganizationHandler) CreateOrganization(w http.ResponseWriter, r *http. organization.ID = organizationId // Role 생성 - adminRole := domain.Role{ + adminRole := model.Role{ OrganizationID: organizationId, Name: "admin", Description: "admin", @@ -78,7 +79,7 @@ func (h *OrganizationHandler) CreateOrganization(w http.ResponseWriter, r *http. ErrorJSON(w, r, err) return } - userRole := domain.Role{ + userRole := model.Role{ OrganizationID: organizationId, Name: "user", Description: "user", @@ -216,7 +217,7 @@ func (h *OrganizationHandler) GetOrganization(w http.ResponseWriter, r *http.Req // @Accept json // @Produce json // @Param organizationId path string true "organizationId" -// @Success 200 {object} domain.Organization +// @Success 200 {object} domain.DeleteOrganizationResponse // @Router /organizations/{organizationId} [delete] // @Security JWT func (h *OrganizationHandler) DeleteOrganization(w http.ResponseWriter, r *http.Request) { @@ -253,7 +254,10 @@ func (h *OrganizationHandler) DeleteOrganization(w http.ResponseWriter, r *http. return } - ResponseJSON(w, r, http.StatusOK, nil) + out := domain.DeleteOrganizationResponse{ + ID: organizationId, + } + ResponseJSON(w, r, http.StatusOK, out) } // UpdateOrganization godoc diff --git a/internal/delivery/http/permission.go b/internal/delivery/http/permission.go index 22bdfb64..d7ca79d9 100644 --- a/internal/delivery/http/permission.go +++ b/internal/delivery/http/permission.go @@ -1,12 +1,15 @@ package http import ( + "net/http" + "github.com/gorilla/mux" + "github.com/openinfradev/tks-api/internal/model" + "github.com/openinfradev/tks-api/internal/serializer" "github.com/openinfradev/tks-api/internal/usecase" "github.com/openinfradev/tks-api/pkg/domain" "github.com/openinfradev/tks-api/pkg/httpErrors" "github.com/openinfradev/tks-api/pkg/log" - "net/http" ) type IPermissionHandler interface { @@ -32,19 +35,24 @@ func NewPermissionHandler(usecase usecase.Usecase) *PermissionHandler { // @Description Get Permission Templates // @Accept json // @Produce json -// @Success 200 {object} domain.PermissionSet +// @Success 200 {object} domain.PermissionSetResponse // @Router /permissions/templates [get] // @Security JWT func (h PermissionHandler) GetPermissionTemplates(w http.ResponseWriter, r *http.Request) { - permissionSet := domain.NewDefaultPermissionSet() + permissionSet := model.NewDefaultPermissionSet() + + var premissionSetResponse domain.PermissionSetResponse + if err := serializer.Map(permissionSet, &premissionSetResponse); err != nil { + log.InfoWithContext(r.Context(), err) + } var out domain.GetPermissionTemplatesResponse - out.Permissions = append(out.Permissions, permissionSet.Dashboard) - out.Permissions = append(out.Permissions, permissionSet.Stack) - out.Permissions = append(out.Permissions, permissionSet.SecurityPolicy) - out.Permissions = append(out.Permissions, permissionSet.ProjectManagement) - out.Permissions = append(out.Permissions, permissionSet.Notification) - out.Permissions = append(out.Permissions, permissionSet.Configuration) + out.Permissions = append(out.Permissions, premissionSetResponse.Dashboard) + out.Permissions = append(out.Permissions, premissionSetResponse.Stack) + out.Permissions = append(out.Permissions, premissionSetResponse.SecurityPolicy) + out.Permissions = append(out.Permissions, premissionSetResponse.ProjectManagement) + out.Permissions = append(out.Permissions, premissionSetResponse.Notification) + out.Permissions = append(out.Permissions, premissionSetResponse.Configuration) ResponseJSON(w, r, http.StatusOK, out) } @@ -56,7 +64,7 @@ func (h PermissionHandler) GetPermissionTemplates(w http.ResponseWriter, r *http // @Description Get Permissions By Role ID // @Accept json // @Produce json -// @Success 200 {object} domain.PermissionSet +// @Success 200 {object} domain.PermissionSetResponse // @Router /organizations/{organizationId}/roles/{roleId}/permissions [get] // @Security JWT func (h PermissionHandler) GetPermissionsByRoleId(w http.ResponseWriter, r *http.Request) { @@ -77,13 +85,18 @@ func (h PermissionHandler) GetPermissionsByRoleId(w http.ResponseWriter, r *http return } + var premissionSetResponse domain.PermissionSetResponse + if err := serializer.Map(permissionSet, &premissionSetResponse); err != nil { + log.InfoWithContext(r.Context(), err) + } + var out domain.GetPermissionsByRoleIdResponse - out.Permissions = append(out.Permissions, permissionSet.Dashboard) - out.Permissions = append(out.Permissions, permissionSet.Stack) - out.Permissions = append(out.Permissions, permissionSet.SecurityPolicy) - out.Permissions = append(out.Permissions, permissionSet.ProjectManagement) - out.Permissions = append(out.Permissions, permissionSet.Notification) - out.Permissions = append(out.Permissions, permissionSet.Configuration) + out.Permissions = append(out.Permissions, premissionSetResponse.Dashboard) + out.Permissions = append(out.Permissions, premissionSetResponse.Stack) + out.Permissions = append(out.Permissions, premissionSetResponse.SecurityPolicy) + out.Permissions = append(out.Permissions, premissionSetResponse.ProjectManagement) + out.Permissions = append(out.Permissions, premissionSetResponse.Notification) + out.Permissions = append(out.Permissions, premissionSetResponse.Configuration) ResponseJSON(w, r, http.StatusOK, out) } @@ -122,9 +135,15 @@ func (h PermissionHandler) UpdatePermissionsByRoleId(w http.ResponseWriter, r *h } log.Debugf("input: %+v", input) - for _, permission := range input.Permissions { - log.Debugf("permission: %+v", permission) - if err := h.permissionUsecase.UpdatePermission(permission); err != nil { + for _, permissionResponse := range input.Permissions { + log.Debugf("permissionResponse: %+v", permissionResponse) + + var permission model.Permission + if err := serializer.Map(permissionResponse, &permission); err != nil { + log.InfoWithContext(r.Context(), err) + } + + if err := h.permissionUsecase.UpdatePermission(&permission); err != nil { ErrorJSON(w, r, httpErrors.NewInternalServerError(err, "", "")) return } diff --git a/internal/delivery/http/policy-template.go b/internal/delivery/http/policy-template.go index 8126e00f..e747a98f 100644 --- a/internal/delivery/http/policy-template.go +++ b/internal/delivery/http/policy-template.go @@ -8,6 +8,7 @@ import ( "github.com/google/uuid" "github.com/gorilla/mux" + "github.com/openinfradev/tks-api/internal/model" "github.com/openinfradev/tks-api/internal/pagination" "github.com/openinfradev/tks-api/internal/serializer" "github.com/openinfradev/tks-api/internal/usecase" @@ -67,7 +68,7 @@ func (h *PolicyTemplateHandler) CreatePolicyTemplate(w http.ResponseWriter, r *h return } - var dto domain.PolicyTemplate + var dto model.PolicyTemplate if err = serializer.Map(input, &dto); err != nil { log.InfoWithContext(r.Context(), err) } diff --git a/internal/delivery/http/role.go b/internal/delivery/http/role.go index 1ad67b29..7fdb1157 100644 --- a/internal/delivery/http/role.go +++ b/internal/delivery/http/role.go @@ -1,14 +1,16 @@ package http import ( + "net/http" + "github.com/gorilla/mux" + "github.com/openinfradev/tks-api/internal/model" "github.com/openinfradev/tks-api/internal/pagination" "github.com/openinfradev/tks-api/internal/serializer" "github.com/openinfradev/tks-api/internal/usecase" "github.com/openinfradev/tks-api/pkg/domain" "github.com/openinfradev/tks-api/pkg/httpErrors" "github.com/openinfradev/tks-api/pkg/log" - "net/http" ) type IRoleHandler interface { @@ -67,7 +69,7 @@ func (h RoleHandler) CreateTksRole(w http.ResponseWriter, r *http.Request) { } // input to dto - dto := domain.Role{ + dto := model.Role{ OrganizationID: organizationId, Name: input.Name, Description: input.Description, @@ -82,7 +84,7 @@ func (h RoleHandler) CreateTksRole(w http.ResponseWriter, r *http.Request) { } // create permission - defaultPermissionSet := domain.NewDefaultPermissionSet() + defaultPermissionSet := model.NewDefaultPermissionSet() h.permissionUsecase.SetRoleIdToPermissionSet(roleId, defaultPermissionSet) err = h.permissionUsecase.CreatePermissionSet(defaultPermissionSet) if err != nil { @@ -256,7 +258,7 @@ func (h RoleHandler) UpdateTksRole(w http.ResponseWriter, r *http.Request) { } // input to dto - dto := domain.Role{ + dto := model.Role{ ID: roleId, Description: input.Description, } diff --git a/internal/delivery/http/stack-template.go b/internal/delivery/http/stack-template.go index 107e621b..60cad92a 100644 --- a/internal/delivery/http/stack-template.go +++ b/internal/delivery/http/stack-template.go @@ -8,6 +8,7 @@ import ( "github.com/google/uuid" "github.com/gorilla/mux" "github.com/openinfradev/tks-api/internal" + "github.com/openinfradev/tks-api/internal/model" "github.com/openinfradev/tks-api/internal/pagination" "github.com/openinfradev/tks-api/internal/serializer" "github.com/openinfradev/tks-api/internal/usecase" @@ -30,7 +31,7 @@ func NewStackTemplateHandler(h usecase.Usecase) *StackTemplateHandler { // CreateStackTemplate godoc // // @Tags StackTemplates -// @Summary Create StackTemplate 'NOT IMPLEMENTED' +// @Summary Create StackTemplate // @Description Create StackTemplate // @Accept json // @Produce json @@ -46,7 +47,7 @@ func (h *StackTemplateHandler) CreateStackTemplate(w http.ResponseWriter, r *htt return } - var dto domain.StackTemplate + var dto model.StackTemplate if err = serializer.Map(input, &dto); err != nil { log.InfoWithContext(r.Context(), err) } @@ -170,7 +171,7 @@ func (h *StackTemplateHandler) GetStackTemplate(w http.ResponseWriter, r *http.R // UpdateStackTemplate godoc // // @Tags StackTemplates -// @Summary Update StackTemplate 'NOT IMPLEMENTED' +// @Summary Update StackTemplate // @Description Update StackTemplate // @Accept json // @Produce json @@ -192,7 +193,7 @@ func (h *StackTemplateHandler) UpdateStackTemplate(w http.ResponseWriter, r *htt return } - var dto domain.StackTemplate + var dto model.StackTemplate if err := serializer.Map(r, &dto); err != nil { log.InfoWithContext(r.Context(), err) } @@ -209,7 +210,7 @@ func (h *StackTemplateHandler) UpdateStackTemplate(w http.ResponseWriter, r *htt // DeleteStackTemplate godoc // // @Tags StackTemplates -// @Summary Delete StackTemplate 'NOT IMPLEMENTED' +// @Summary Delete StackTemplate // @Description Delete StackTemplate // @Accept json // @Produce json @@ -287,7 +288,7 @@ func (h *StackTemplateHandler) UpdateStackTemplateOrganizations(w http.ResponseW return } - var dto domain.StackTemplate + var dto model.StackTemplate if err := serializer.Map(input, &dto); err != nil { log.InfoWithContext(r.Context(), err) } @@ -300,3 +301,117 @@ func (h *StackTemplateHandler) UpdateStackTemplateOrganizations(w http.ResponseW } ResponseJSON(w, r, http.StatusOK, nil) } + +// GetOrganizationStackTemplates godoc +// +// @Tags StackTemplates +// @Summary Get Organization StackTemplates +// @Description Get Organization StackTemplates +// @Accept json +// @Produce json +// @Param limit query string false "pageSize" +// @Param page query string false "pageNumber" +// @Param soertColumn query string false "sortColumn" +// @Param sortOrder query string false "sortOrder" +// @Param filters query []string false "filters" +// @Success 200 {object} domain.GetStackTemplatesResponse +// @Router /organizations/{organizationId}/stack-templates [get] +// @Security JWT +func (h *StackTemplateHandler) GetOrganizationStackTemplates(w http.ResponseWriter, r *http.Request) { + vars := mux.Vars(r) + organizationId, ok := vars["organizationId"] + if !ok { + ErrorJSON(w, r, httpErrors.NewBadRequestError(fmt.Errorf("Invalid organizationId"), "C_INVALID_ORGANIZATION_ID", "")) + return + } + + urlParams := r.URL.Query() + pg := pagination.NewPagination(&urlParams) + stackTemplates, err := h.usecase.FetchWithOrganization(r.Context(), organizationId, pg) + if err != nil { + ErrorJSON(w, r, err) + return + } + + var out domain.GetStackTemplatesResponse + out.StackTemplates = make([]domain.StackTemplateResponse, len(stackTemplates)) + for i, stackTemplate := range stackTemplates { + if err := serializer.Map(stackTemplate, &out.StackTemplates[i]); err != nil { + log.InfoWithContext(r.Context(), err) + } + + out.StackTemplates[i].Organizations = make([]domain.SimpleOrganizationResponse, len(stackTemplate.Organizations)) + for j, organization := range stackTemplate.Organizations { + if err := serializer.Map(organization, &out.StackTemplates[i].Organizations[j]); err != nil { + log.InfoWithContext(r.Context(), err) + } + } + + err := json.Unmarshal(stackTemplate.Services, &out.StackTemplates[i].Services) + if err != nil { + log.ErrorWithContext(r.Context(), err) + } + } + + if out.Pagination, err = pg.Response(); err != nil { + log.InfoWithContext(r.Context(), err) + } + + ResponseJSON(w, r, http.StatusOK, out) +} + +// GetOrganizationStackTemplate godoc +// +// @Tags StackTemplates +// @Summary Get Organization StackTemplate +// @Description Get Organization StackTemplate +// @Accept json +// @Produce json +// @Success 200 {object} domain.GetStackTemplateResponse +// @Router /organizations/{organizationId}/stack-templates/{stackTemplateId} [get] +// @Security JWT +func (h *StackTemplateHandler) GetOrganizationStackTemplate(w http.ResponseWriter, r *http.Request) { + vars := mux.Vars(r) + _, ok := vars["organizationId"] + if !ok { + ErrorJSON(w, r, httpErrors.NewBadRequestError(fmt.Errorf("Invalid organizationId"), "C_INVALID_ORGANIZATION_ID", "")) + return + } + + strId, ok := vars["stackTemplateId"] + if !ok { + ErrorJSON(w, r, httpErrors.NewBadRequestError(fmt.Errorf("invalid stackTemplateId"), "C_INVALID_STACK_TEMPLATE_ID", "")) + return + } + + stackTemplateId, err := uuid.Parse(strId) + if err != nil { + ErrorJSON(w, r, httpErrors.NewBadRequestError(errors.Wrap(err, "Failed to parse uuid %s"), "C_INVALID_STACK_TEMPLATE_ID", "")) + return + } + + stackTemplate, err := h.usecase.Get(r.Context(), stackTemplateId) + if err != nil { + ErrorJSON(w, r, err) + return + } + + var out domain.GetStackTemplateResponse + if err := serializer.Map(stackTemplate, &out.StackTemplate); err != nil { + log.InfoWithContext(r.Context(), err) + } + + out.StackTemplate.Organizations = make([]domain.SimpleOrganizationResponse, len(stackTemplate.Organizations)) + for i, organization := range stackTemplate.Organizations { + if err := serializer.Map(organization, &out.StackTemplate.Organizations[i]); err != nil { + log.InfoWithContext(r.Context(), err) + } + } + + err = json.Unmarshal(stackTemplate.Services, &out.StackTemplate.Services) + if err != nil { + log.ErrorWithContext(r.Context(), err) + } + + ResponseJSON(w, r, http.StatusOK, out) +} diff --git a/internal/delivery/http/stack.go b/internal/delivery/http/stack.go index fd84da4e..9a40cf22 100644 --- a/internal/delivery/http/stack.go +++ b/internal/delivery/http/stack.go @@ -6,6 +6,7 @@ import ( "net/http" "github.com/gorilla/mux" + "github.com/openinfradev/tks-api/internal/model" "github.com/openinfradev/tks-api/internal/pagination" "github.com/openinfradev/tks-api/internal/serializer" "github.com/openinfradev/tks-api/internal/usecase" @@ -51,13 +52,10 @@ func (h *StackHandler) CreateStack(w http.ResponseWriter, r *http.Request) { return } - var dto domain.Stack + var dto model.Stack if err = serializer.Map(input, &dto); err != nil { log.InfoWithContext(r.Context(), err) } - if err = serializer.Map(input, &dto.Conf); err != nil { - log.InfoWithContext(r.Context(), err) - } dto.OrganizationId = organizationId stackId, err := h.usecase.Create(r.Context(), dto) if err != nil { @@ -126,7 +124,10 @@ func (h *StackHandler) GetStacks(w http.ResponseWriter, r *http.Request) { for i, stack := range stacks { if err := serializer.Map(stack, &out.Stacks[i]); err != nil { log.InfoWithContext(r.Context(), err) - continue + } + + if err := serializer.Map(stack.CreatedAt, &out.Stacks[i].CreatedAt); err != nil { + log.InfoWithContext(r.Context(), err) } err = json.Unmarshal(stack.StackTemplate.Services, &out.Stacks[i].StackTemplate.Services) @@ -259,7 +260,7 @@ func (h *StackHandler) UpdateStack(w http.ResponseWriter, r *http.Request) { return } - var dto domain.Stack + var dto model.Stack if err = serializer.Map(input, &dto); err != nil { log.InfoWithContext(r.Context(), err) } @@ -302,7 +303,7 @@ func (h *StackHandler) DeleteStack(w http.ResponseWriter, r *http.Request) { return } - var dto domain.Stack + var dto model.Stack dto.ID = domain.StackId(strId) dto.OrganizationId = organizationId diff --git a/internal/delivery/http/user.go b/internal/delivery/http/user.go index 7df3a3bc..9fa3b8b7 100644 --- a/internal/delivery/http/user.go +++ b/internal/delivery/http/user.go @@ -9,6 +9,7 @@ import ( "github.com/gorilla/mux" "github.com/openinfradev/tks-api/internal/middleware/auth/request" + "github.com/openinfradev/tks-api/internal/model" "github.com/openinfradev/tks-api/internal/pagination" "github.com/openinfradev/tks-api/internal/serializer" "github.com/openinfradev/tks-api/internal/usecase" @@ -86,11 +87,11 @@ func (u UserHandler) Create(w http.ResponseWriter, r *http.Request) { } ctx := r.Context() - var user domain.User + var user model.User if err = serializer.Map(input, &user); err != nil { log.ErrorWithContext(r.Context(), err) } - user.Organization = domain.Organization{ + user.Organization = model.Organization{ ID: organizationId, } @@ -231,7 +232,7 @@ func (u UserHandler) List(w http.ResponseWriter, r *http.Request) { // @Produce json // @Param organizationId path string true "organizationId" // @Param accountId path string true "accountId" -// @Success 200 {object} domain.User +// @Success 200 {object} nil // @Router /organizations/{organizationId}/users/{accountId} [delete] // @Security JWT func (u UserHandler) Delete(w http.ResponseWriter, r *http.Request) { @@ -298,12 +299,12 @@ func (u UserHandler) Update(w http.ResponseWriter, r *http.Request) { } ctx := r.Context() - var user domain.User + var user model.User if err = serializer.Map(input, &user); err != nil { ErrorJSON(w, r, err) return } - user.Organization = domain.Organization{ + user.Organization = model.Organization{ ID: organizationId, } user.AccountId = accountId @@ -451,7 +452,7 @@ func (u UserHandler) UpdateMyProfile(w http.ResponseWriter, r *http.Request) { } ctx := r.Context() - var user domain.User + var user model.User if err = serializer.Map(input, &user); err != nil { log.ErrorWithContext(r.Context(), err) ErrorJSON(w, r, err) @@ -710,7 +711,7 @@ func (u UserHandler) Admin_Create(w http.ResponseWriter, r *http.Request) { } } - user := domain.User{ + user := model.User{ Name: input.Name, AccountId: input.AccountId, Email: input.Email, @@ -732,7 +733,7 @@ func (u UserHandler) Admin_Create(w http.ResponseWriter, r *http.Request) { } } - user.Organization = domain.Organization{ + user.Organization = model.Organization{ ID: organizationId, } @@ -973,14 +974,14 @@ func (u UserHandler) Admin_Update(w http.ResponseWriter, r *http.Request) { } ctx := r.Context() - user := domain.User{ + user := model.User{ AccountId: accountId, Name: input.Name, Email: input.Email, Department: input.Department, Description: input.Description, } - user.Organization = domain.Organization{ + user.Organization = model.Organization{ ID: organizationId, } diff --git a/internal/filter/settings.go b/internal/filter/settings.go index ac2a31a8..4e06fc48 100644 --- a/internal/filter/settings.go +++ b/internal/filter/settings.go @@ -316,6 +316,7 @@ func getField(field string, sch *schema.Schema, blacklist *Blacklist) (*schema.F if !ok || (relation.Type != schema.HasOne && relation.Type != schema.BelongsTo) { return nil, nil, "" } + s = relation.FieldSchema if blacklist != nil { blacklist = blacklist.Relations[v] @@ -330,6 +331,7 @@ func getField(field string, sch *schema.Schema, blacklist *Blacklist) (*schema.F if !ok { return nil, nil, "" } + return col, s, joinName } diff --git a/internal/keycloak/keycloak.go b/internal/keycloak/keycloak.go index 8d2252f5..610d59ad 100644 --- a/internal/keycloak/keycloak.go +++ b/internal/keycloak/keycloak.go @@ -10,7 +10,7 @@ import ( "time" "github.com/Nerzal/gocloak/v13" - "github.com/openinfradev/tks-api/pkg/domain" + "github.com/openinfradev/tks-api/internal/model" "github.com/openinfradev/tks-api/pkg/httpErrors" "github.com/openinfradev/tks-api/pkg/log" ) @@ -18,15 +18,15 @@ import ( type IKeycloak interface { InitializeKeycloak() error - LoginAdmin(accountId string, password string) (*domain.User, error) - Login(accountId string, password string, organizationId string) (*domain.User, error) + LoginAdmin(accountId string, password string) (*model.User, error) + Login(accountId string, password string, organizationId string) (*model.User, error) Logout(sessionId string, organizationId string) error CreateRealm(organizationId string) (string, error) - GetRealm(organizationId string) (*domain.Organization, error) - GetRealms() ([]*domain.Organization, error) + GetRealm(organizationId string) (*model.Organization, error) + GetRealms() ([]*model.Organization, error) DeleteRealm(organizationId string) error - UpdateRealm(organizationId string, organizationConfig domain.Organization) error + UpdateRealm(organizationId string, organizationConfig model.Organization) error CreateUser(organizationId string, user *gocloak.User) (string, error) GetUser(organizationId string, userAccountId string) (*gocloak.User, error) @@ -51,7 +51,7 @@ type Keycloak struct { adminCliToken *gocloak.JWT } -func (k *Keycloak) LoginAdmin(accountId string, password string) (*domain.User, error) { +func (k *Keycloak) LoginAdmin(accountId string, password string) (*model.User, error) { ctx := context.Background() JWTToken, err := k.client.LoginAdmin(ctx, accountId, password, DefaultMasterRealm) if err != nil { @@ -59,17 +59,17 @@ func (k *Keycloak) LoginAdmin(accountId string, password string) (*domain.User, return nil, err } - return &domain.User{Token: JWTToken.AccessToken}, nil + return &model.User{Token: JWTToken.AccessToken}, nil } -func (k *Keycloak) Login(accountId string, password string, organizationId string) (*domain.User, error) { +func (k *Keycloak) Login(accountId string, password string, organizationId string) (*model.User, error) { ctx := context.Background() JWTToken, err := k.client.Login(ctx, DefaultClientID, k.config.ClientSecret, organizationId, accountId, password) if err != nil { log.Error(err) return nil, err } - return &domain.User{Token: JWTToken.AccessToken}, nil + return &model.User{Token: JWTToken.AccessToken}, nil } func New(config *Config) IKeycloak { @@ -249,7 +249,7 @@ func (k *Keycloak) CreateRealm(organizationId string) (string, error) { return realmUUID, nil } -func (k *Keycloak) GetRealm(organizationId string) (*domain.Organization, error) { +func (k *Keycloak) GetRealm(organizationId string) (*model.Organization, error) { ctx := context.Background() token := k.adminCliToken realm, err := k.client.GetRealm(ctx, token.AccessToken, organizationId) @@ -260,14 +260,14 @@ func (k *Keycloak) GetRealm(organizationId string) (*domain.Organization, error) return k.reflectOrganization(*realm), nil } -func (k *Keycloak) GetRealms() ([]*domain.Organization, error) { +func (k *Keycloak) GetRealms() ([]*model.Organization, error) { ctx := context.Background() token := k.adminCliToken realms, err := k.client.GetRealms(ctx, token.AccessToken) if err != nil { return nil, err } - organization := make([]*domain.Organization, 0) + organization := make([]*model.Organization, 0) for _, realm := range realms { organization = append(organization, k.reflectOrganization(*realm)) } @@ -275,7 +275,7 @@ func (k *Keycloak) GetRealms() ([]*domain.Organization, error) { return organization, nil } -func (k *Keycloak) UpdateRealm(organizationId string, organizationConfig domain.Organization) error { +func (k *Keycloak) UpdateRealm(organizationId string, organizationConfig model.Organization) error { ctx := context.Background() token := k.adminCliToken realm := k.reflectRealmRepresentation(organizationConfig) @@ -844,14 +844,14 @@ func (k *Keycloak) createDefaultClient(ctx context.Context, accessToken string, return id, nil } -func (k *Keycloak) reflectOrganization(org gocloak.RealmRepresentation) *domain.Organization { - return &domain.Organization{ +func (k *Keycloak) reflectOrganization(org gocloak.RealmRepresentation) *model.Organization { + return &model.Organization{ ID: *org.ID, Name: *org.Realm, } } -func (k *Keycloak) reflectRealmRepresentation(org domain.Organization) *gocloak.RealmRepresentation { +func (k *Keycloak) reflectRealmRepresentation(org model.Organization) *gocloak.RealmRepresentation { return &gocloak.RealmRepresentation{ Realm: gocloak.StringP(org.Name), } diff --git a/internal/middleware/audit/audit-map.go b/internal/middleware/audit/audit-map.go index 85a80d9d..863b71fd 100644 --- a/internal/middleware/audit/audit-map.go +++ b/internal/middleware/audit/audit-map.go @@ -19,7 +19,6 @@ var auditMap = map[internalApi.Endpoint]fnAudit{ if err := json.Unmarshal(in, &input); err != nil { log.Error(err) } - if isSuccess(statusCode) { return fmt.Sprintf("스택 [%s]을 생성하였습니다.", input.Name), "" } else { @@ -30,22 +29,101 @@ var auditMap = map[internalApi.Endpoint]fnAudit{ if err := json.Unmarshal(in, &input); err != nil { log.Error(err) } - if isSuccess(statusCode) { return fmt.Sprintf("프로젝트 [%s]를 생성하였습니다.", input.Name), "" } else { - return "프로젝트 [%s]를 생성하는데 실패하였습니다. ", errorText(out) + return fmt.Sprintf("프로젝트 [%s]을 생성하는데 실패하였습니다.", input.Name), errorText(out) } }, internalApi.CreateCloudAccount: func(out *bytes.Buffer, in []byte, statusCode int) (message string, description string) { input := domain.CreateCloudAccountRequest{} if err := json.Unmarshal(in, &input); err != nil { log.Error(err) } - if isSuccess(statusCode) { return fmt.Sprintf("클라우드 어카운트 [%s]를 생성하였습니다.", input.Name), "" } else { - return "프로젝트 [%s]를 생성하는데 실패하였습니다. ", errorText(out) + return fmt.Sprintf("클라우드 어카운트 [%s]을 생성하는데 실패하였습니다.", input.Name), errorText(out) + } + }, internalApi.DeleteCloudAccount: func(out *bytes.Buffer, in []byte, statusCode int) (message string, description string) { + if isSuccess(statusCode) { + output := domain.DeleteCloudAccountResponse{} + if err := json.Unmarshal(in, &output); err != nil { + log.Error(err) + } + return fmt.Sprintf("클라우드어카운트 [ID:%s]를 삭제하였습니다.", output.ID), "" + } else { + return "클라우드어카운트 [%s]를 삭제하는데 실패하였습니다. ", errorText(out) + } + }, internalApi.CreateUser: func(out *bytes.Buffer, in []byte, statusCode int) (message string, description string) { + input := domain.CreateUserRequest{} + if err := json.Unmarshal(in, &input); err != nil { + log.Error(err) + } + if isSuccess(statusCode) { + return fmt.Sprintf("사용자 [%s]를 생성하였습니다.", input.Name), "" + } else { + return fmt.Sprintf("사용자 [%s]을 생성하는데 실패하였습니다.", input.Name), errorText(out) + } + }, internalApi.CreateOrganization: func(out *bytes.Buffer, in []byte, statusCode int) (message string, description string) { + input := domain.CreateOrganizationRequest{} + if err := json.Unmarshal(in, &input); err != nil { + log.Error(err) + } + if isSuccess(statusCode) { + return fmt.Sprintf("조직 [%s]를 생성하였습니다.", input.Name), "" + } else { + return fmt.Sprintf("조직 [%s]을 생성하는데 실패하였습니다.", input.Name), errorText(out) + } + }, internalApi.DeleteOrganization: func(out *bytes.Buffer, in []byte, statusCode int) (message string, description string) { + if isSuccess(statusCode) { + output := domain.DeleteOrganizationResponse{} + if err := json.Unmarshal(in, &output); err != nil { + log.Error(err) + } + return fmt.Sprintf("조직 [ID:%s]를 삭제하였습니다.", output.ID), "" + } else { + return "조직 [%s]를 삭제하는데 실패하였습니다. ", errorText(out) + } + }, internalApi.CreateAppServeApp: func(out *bytes.Buffer, in []byte, statusCode int) (message string, description string) { + input := domain.CreateAppServeAppRequest{} + if err := json.Unmarshal(in, &input); err != nil { + log.Error(err) + } + if isSuccess(statusCode) { + return fmt.Sprintf("앱서빙 [%s]를 생성하였습니다.", input.Name), "" + } else { + return fmt.Sprintf("앱서빙 [%s]을 생성하는데 실패하였습니다.", input.Name), errorText(out) + } + }, internalApi.Admin_CreateStackTemplate: func(out *bytes.Buffer, in []byte, statusCode int) (message string, description string) { + input := domain.CreateStackTemplateRequest{} + if err := json.Unmarshal(in, &input); err != nil { + log.Error(err) + } + log.Info(input) + if isSuccess(statusCode) { + return fmt.Sprintf("스택 템플릿 [%s]를 생성하였습니다.", input.Name), "" + } else { + return fmt.Sprintf("스택 템플릿 [%s]을 생성하는데 실패하였습니다.", input.Name), errorText(out) + } + }, internalApi.Admin_CreateUser: func(out *bytes.Buffer, in []byte, statusCode int) (message string, description string) { + input := domain.CreateUserRequest{} + if err := json.Unmarshal(in, &input); err != nil { + log.Error(err) + } + if isSuccess(statusCode) { + return fmt.Sprintf("어드민 [%s]를 생성하였습니다.", input.Name), "" + } else { + return fmt.Sprintf("어드민 [%s]을 생성하는데 실패하였습니다.", input.Name), errorText(out) + } + }, internalApi.CreatePolicyTemplate: func(out *bytes.Buffer, in []byte, statusCode int) (message string, description string) { + input := domain.CreatePolicyTemplateRequest{} + if err := json.Unmarshal(in, &input); err != nil { + log.Error(err) + } + if isSuccess(statusCode) { + return fmt.Sprintf("폴리시템플릿 [%s]를 생성하였습니다.", input.TemplateName), "" + } else { + return fmt.Sprintf("폴리시템플릿 [%s]을 생성하는데 실패하였습니다.", input.TemplateName), errorText(out) } }, } diff --git a/internal/middleware/audit/audit.go b/internal/middleware/audit/audit.go index 428f8d35..12360269 100644 --- a/internal/middleware/audit/audit.go +++ b/internal/middleware/audit/audit.go @@ -10,8 +10,8 @@ import ( internalApi "github.com/openinfradev/tks-api/internal/delivery/api" "github.com/openinfradev/tks-api/internal/middleware/auth/request" "github.com/openinfradev/tks-api/internal/middleware/logging" + "github.com/openinfradev/tks-api/internal/model" "github.com/openinfradev/tks-api/internal/repository" - "github.com/openinfradev/tks-api/pkg/domain" "github.com/openinfradev/tks-api/pkg/log" ) @@ -59,7 +59,7 @@ func (a *defaultAudit) WithAudit(endpoint internalApi.Endpoint, handler http.Han message, description = fn(lrw.GetBody(), body, statusCode) r.Body = io.NopCloser(bytes.NewBuffer(body)) - dto := domain.Audit{ + dto := model.Audit{ OrganizationId: organizationId, Group: internalApi.ApiMap[endpoint].Group, Message: message, diff --git a/internal/model/alert.go b/internal/model/alert.go new file mode 100644 index 00000000..5d360781 --- /dev/null +++ b/internal/model/alert.go @@ -0,0 +1,60 @@ +package model + +import ( + "time" + + "github.com/google/uuid" + "github.com/openinfradev/tks-api/pkg/domain" + "gorm.io/datatypes" + "gorm.io/gorm" +) + +// Models +type Alert struct { + gorm.Model + + ID uuid.UUID `gorm:"primarykey"` + OrganizationId string + Organization Organization `gorm:"foreignKey:OrganizationId"` + Name string + Code string + Description string + Grade string + Message string + ClusterId domain.ClusterId + Cluster Cluster `gorm:"foreignKey:ClusterId"` + Node string + CheckPoint string + GrafanaUrl string + FiredAt *time.Time `gorm:"-:all"` + TakedAt *time.Time `gorm:"-:all"` + ClosedAt *time.Time `gorm:"-:all"` + TakedSec int `gorm:"-:all"` + ProcessingSec int `gorm:"-:all"` + LastTaker User `gorm:"-:all"` + AlertActions []AlertAction + Summary string + RawData datatypes.JSON + Status domain.AlertActionStatus `gorm:"index"` +} + +func (c *Alert) BeforeCreate(tx *gorm.DB) (err error) { + c.ID = uuid.New() + return nil +} + +type AlertAction struct { + gorm.Model + + ID uuid.UUID `gorm:"primarykey"` + AlertId uuid.UUID + Content string + Status domain.AlertActionStatus + TakerId *uuid.UUID `gorm:"type:uuid"` + Taker User `gorm:"foreignKey:TakerId"` +} + +func (c *AlertAction) BeforeCreate(tx *gorm.DB) (err error) { + c.ID = uuid.New() + return nil +} diff --git a/internal/model/app-group.go b/internal/model/app-group.go new file mode 100644 index 00000000..fea48726 --- /dev/null +++ b/internal/model/app-group.go @@ -0,0 +1,47 @@ +package model + +import ( + "github.com/google/uuid" + "github.com/openinfradev/tks-api/internal/helper" + "github.com/openinfradev/tks-api/pkg/domain" + "gorm.io/datatypes" + "gorm.io/gorm" +) + +// Models +type AppGroup struct { + gorm.Model + + ID domain.AppGroupId `gorm:"primarykey"` + AppGroupType domain.AppGroupType + ClusterId domain.ClusterId + Name string + Description string + WorkflowId string + Status domain.AppGroupStatus + StatusDesc string + CreatorId *uuid.UUID `gorm:"type:uuid"` + Creator User `gorm:"foreignKey:CreatorId"` + UpdatorId *uuid.UUID `gorm:"type:uuid"` + Updator User `gorm:"foreignKey:UpdatorId"` +} + +func (c *AppGroup) BeforeCreate(tx *gorm.DB) (err error) { + c.ID = domain.AppGroupId(helper.GenerateApplicaionGroupId()) + return nil +} + +type Application struct { + gorm.Model + + ID uuid.UUID `gorm:"primarykey;type:uuid"` + AppGroupId domain.AppGroupId + Endpoint string + Metadata datatypes.JSON + Type domain.ApplicationType +} + +func (c *Application) BeforeCreate(tx *gorm.DB) (err error) { + c.ID = uuid.New() + return nil +} diff --git a/internal/model/app-serve-app.go b/internal/model/app-serve-app.go new file mode 100644 index 00000000..4b6e779e --- /dev/null +++ b/internal/model/app-serve-app.go @@ -0,0 +1,67 @@ +package model + +import ( + "time" + + "github.com/google/uuid" + "gorm.io/gorm" +) + +type AppServeApp struct { + ID string `gorm:"primarykey" json:"id,omitempty"` + Name string `gorm:"index" json:"name,omitempty"` // application name + Namespace string `json:"namespace,omitempty"` // application namespace + OrganizationId string `json:"organizationId,omitempty"` // contractId is a contract ID which this app belongs to + ProjectId string `json:"projectId,omitempty"` // project ID which this app belongs to + Type string `json:"type,omitempty"` // type (build/deploy/all) + AppType string `json:"appType,omitempty"` // appType (spring/springboot) + EndpointUrl string `json:"endpointUrl,omitempty"` // endpoint URL of deployed app + PreviewEndpointUrl string `json:"previewEndpointUrl,omitempty"` // preview svc endpoint URL in B/G deployment + TargetClusterId string `json:"targetClusterId,omitempty"` // target cluster to which the app is deployed + TargetClusterName string `gorm:"-:all" json:"targetClusterName,omitempty"` // target cluster name + Status string `gorm:"index" json:"status,omitempty"` // status is status of deployed app + GrafanaUrl string `json:"grafanaUrl,omitempty"` // grafana dashboard URL for deployed app + CreatedAt time.Time `gorm:"autoCreateTime:false" json:"createdAt" ` + UpdatedAt *time.Time `gorm:"autoUpdateTime:false" json:"updatedAt"` + DeletedAt *time.Time `json:"deletedAt"` + AppServeAppTasks []AppServeAppTask `gorm:"foreignKey:AppServeAppId" json:"appServeAppTasks"` +} + +type AppServeAppTask struct { + ID string `gorm:"primarykey" json:"id,omitempty"` + AppServeAppId string `gorm:"not null" json:"appServeAppId,omitempty"` // ID for appServeApp that this task belongs to + Version string `json:"version,omitempty"` // application version + Status string `json:"status,omitempty"` // status is app status + Output string `json:"output,omitempty"` // output for task result + ArtifactUrl string `json:"artifactUrl,omitempty"` // URL of java app artifact (Eg, Jar) + ImageUrl string `json:"imageUrl,omitempty"` // URL of built image for app + ExecutablePath string `json:"executablePath,omitempty"` // Executable path of app image + Profile string `json:"profile,omitempty"` // java app profile + AppConfig string `json:"appConfig,omitempty"` // java app config + AppSecret string `json:"appSecret,omitempty"` // java app secret + ExtraEnv string `json:"extraEnv,omitempty"` // env variable list for java app + Port string `json:"port,omitempty"` // java app port + ResourceSpec string `json:"resourceSpec,omitempty"` // resource spec of app pod + HelmRevision int32 `gorm:"default:0" json:"helmRevision,omitempty"` // revision of deployed helm release + Strategy string `json:"strategy,omitempty"` // deployment strategy (eg, rolling-update) + RollbackVersion string `json:"rollbackVersion,omitempty"` // rollback target version + PvEnabled bool `json:"pvEnabled"` + PvStorageClass string `json:"pvStorageClass"` + PvAccessMode string `json:"pvAccessMode"` + PvSize string `json:"pvSize"` + PvMountPath string `json:"pvMountPath"` + AvailableRollback bool `gorm:"-:all" json:"availableRollback"` + CreatedAt time.Time `gorm:"autoCreateTime:false" json:"createdAt"` // createdAt is a creation timestamp for the application + UpdatedAt *time.Time `gorm:"autoUpdateTime:false" json:"updatedAt"` + DeletedAt *time.Time `json:"deletedAt"` +} + +func (a *AppServeApp) BeforeCreate(tx *gorm.DB) (err error) { + a.ID = uuid.New().String() + return nil +} + +func (t *AppServeAppTask) BeforeCreate(tx *gorm.DB) (err error) { + t.ID = uuid.New().String() + return nil +} diff --git a/internal/model/audit.go b/internal/model/audit.go new file mode 100644 index 00000000..bfa853c1 --- /dev/null +++ b/internal/model/audit.go @@ -0,0 +1,26 @@ +package model + +import ( + "github.com/google/uuid" + "gorm.io/gorm" +) + +// Models +type Audit struct { + gorm.Model + + ID uuid.UUID `gorm:"primarykey"` + OrganizationId string + Organization Organization `gorm:"foreignKey:OrganizationId"` + Group string + Message string + Description string + ClientIP string + UserId *uuid.UUID `gorm:"type:uuid"` + User User `gorm:"foreignKey:UserId"` +} + +func (c *Audit) BeforeCreate(tx *gorm.DB) (err error) { + c.ID = uuid.New() + return nil +} diff --git a/internal/model/cloud-account.go b/internal/model/cloud-account.go new file mode 100644 index 00000000..33d3a14b --- /dev/null +++ b/internal/model/cloud-account.go @@ -0,0 +1,38 @@ +package model + +import ( + "github.com/google/uuid" + "github.com/openinfradev/tks-api/pkg/domain" + "gorm.io/gorm" +) + +// Models +type CloudAccount struct { + gorm.Model + + ID uuid.UUID `gorm:"primarykey"` + OrganizationId string + Organization Organization `gorm:"foreignKey:OrganizationId"` + Name string `gorm:"index"` + Description string `gorm:"index"` + Resource string + CloudService string + WorkflowId string + Status domain.CloudAccountStatus + StatusDesc string + AwsAccountId string + AccessKeyId string `gorm:"-:all"` + SecretAccessKey string `gorm:"-:all"` + SessionToken string `gorm:"-:all"` + Clusters int `gorm:"-:all"` + CreatedIAM bool + CreatorId *uuid.UUID `gorm:"type:uuid"` + Creator User `gorm:"foreignKey:CreatorId"` + UpdatorId *uuid.UUID `gorm:"type:uuid"` + Updator User `gorm:"foreignKey:UpdatorId"` +} + +func (c *CloudAccount) BeforeCreate(tx *gorm.DB) (err error) { + c.ID = uuid.New() + return nil +} diff --git a/internal/model/cluster.go b/internal/model/cluster.go new file mode 100644 index 00000000..8ca4b764 --- /dev/null +++ b/internal/model/cluster.go @@ -0,0 +1,84 @@ +package model + +import ( + "github.com/google/uuid" + "github.com/openinfradev/tks-api/pkg/domain" + "gorm.io/gorm" +) + +// Models +type Cluster struct { + gorm.Model + + ID domain.ClusterId `gorm:"primarykey"` + Name string `gorm:"index"` + CloudService string `gorm:"default:AWS"` + OrganizationId string + Organization Organization `gorm:"foreignKey:OrganizationId"` + Description string `gorm:"index"` + WorkflowId string + Status domain.ClusterStatus + StatusDesc string + CloudAccountId *uuid.UUID + CloudAccount CloudAccount `gorm:"foreignKey:CloudAccountId"` + StackTemplateId uuid.UUID + StackTemplate StackTemplate `gorm:"foreignKey:StackTemplateId"` + Favorites *[]ClusterFavorite + ClusterType domain.ClusterType `gorm:"default:0"` + ByoClusterEndpointHost string + ByoClusterEndpointPort int + IsStack bool `gorm:"default:false"` + TksCpNode int + TksCpNodeMax int + TksCpNodeType string + TksInfraNode int + TksInfraNodeMax int + TksInfraNodeType string + TksUserNode int + TksUserNodeMax int + TksUserNodeType string + Kubeconfig []byte `gorm:"-:all"` + CreatorId *uuid.UUID `gorm:"type:uuid"` + Creator User `gorm:"foreignKey:CreatorId"` + UpdatorId *uuid.UUID `gorm:"type:uuid"` + Updator User `gorm:"foreignKey:UpdatorId"` +} + +func (m *Cluster) SetDefaultConf() { + m.TksCpNodeMax = m.TksCpNode + + if m.TksInfraNode == 0 { + m.TksInfraNode = 3 + } + m.TksInfraNodeMax = m.TksInfraNode + + if m.TksUserNode == 0 { + m.TksUserNode = 1 + } + m.TksUserNodeMax = m.TksUserNode + + if m.TksCpNodeType == "" { + m.TksCpNodeType = "t3.xlarge" + } + if m.TksInfraNodeType == "" { + m.TksInfraNodeType = "t3.2xlarge" + } + if m.TksUserNodeType == "" { + m.TksUserNodeType = "t3.large" + } +} + +type ClusterFavorite struct { + gorm.Model + + ID uuid.UUID `gorm:"primarykey;type:uuid"` + ClusterId domain.ClusterId + Cluster Cluster `gorm:"foreignKey:ClusterId"` + UserId uuid.UUID `gorm:"type:uuid"` + User User `gorm:"foreignKey:UserId"` +} + +func (c *ClusterFavorite) BeforeCreate(tx *gorm.DB) (err error) { + c.ID = uuid.New() + return nil +} diff --git a/internal/model/dashboard.go b/internal/model/dashboard.go new file mode 100644 index 00000000..3cb73ce4 --- /dev/null +++ b/internal/model/dashboard.go @@ -0,0 +1,4 @@ +package model + +// Dashboard 는 DB repository 접근이 없이 외부 데이터만을 참조하므로, 일단 pkg/domain 의 model 을 사용하도록 해둡니다. +// 즉, usecase 에서 직접 pkg/domain 을 참조하도록 해 두었습니다. diff --git a/internal/model/end-point.go b/internal/model/end-point.go new file mode 100644 index 00000000..912fa0ce --- /dev/null +++ b/internal/model/end-point.go @@ -0,0 +1,11 @@ +package model + +import ( + "time" +) + +type Endpoint struct { + Name string `gorm:"primary_key;type:text;not null;unique" json:"name"` + Group string `gorm:"type:text;" json:"group"` + CreatedAt time.Time +} diff --git a/internal/model/organization.go b/internal/model/organization.go new file mode 100644 index 00000000..74264c16 --- /dev/null +++ b/internal/model/organization.go @@ -0,0 +1,21 @@ +package model + +import ( + "gorm.io/gorm" + + "github.com/openinfradev/tks-api/pkg/domain" +) + +type Organization struct { + gorm.Model + + ID string `gorm:"primarykey;type:varchar(36);not null"` + Name string + Description string + Phone string + PrimaryClusterId string + WorkflowId string + Status domain.OrganizationStatus + StatusDesc string + Creator string +} diff --git a/internal/model/permission.go b/internal/model/permission.go new file mode 100644 index 00000000..b83824af --- /dev/null +++ b/internal/model/permission.go @@ -0,0 +1,615 @@ +package model + +import ( + "github.com/google/uuid" + "github.com/openinfradev/tks-api/internal/delivery/api" + "github.com/openinfradev/tks-api/internal/helper" + "gorm.io/gorm" +) + +type PermissionKind string + +const ( + DashBoardPermission PermissionKind = "대시보드" + StackPermission PermissionKind = "스택 관리" + SecurityPolicyPermission PermissionKind = "보안/정책 관리" + ProjectManagementPermission PermissionKind = "프로젝트 관리" + NotificationPermission PermissionKind = "알림" + ConfigurationPermission PermissionKind = "설정" +) + +type Permission struct { + gorm.Model + + ID uuid.UUID `gorm:"primarykey;type:uuid;" json:"ID"` + Name string `json:"name"` + + IsAllowed *bool `gorm:"type:boolean;" json:"is_allowed,omitempty"` + RoleID *string `json:"role_id,omitempty"` + Role *Role `gorm:"foreignKey:RoleID;references:ID;" json:"role,omitempty"` + Endpoints []*Endpoint `gorm:"many2many:permission_endpoints;" json:"endpoints,omitempty"` + // omit empty + + ParentID *uuid.UUID `json:"parent_id,omitempty"` + Parent *Permission `gorm:"foreignKey:ParentID;references:ID;" json:"parent,omitempty"` + Children []*Permission `gorm:"foreignKey:ParentID;references:ID;" json:"children,omitempty"` +} + +func (p *Permission) BeforeCreate(tx *gorm.DB) (err error) { + if p.ID == uuid.Nil { + p.ID = uuid.New() + } + return nil +} + +type PermissionSet struct { + Dashboard *Permission `gorm:"-:all" json:"dashboard,omitempty"` + Stack *Permission `gorm:"-:all" json:"stack,omitempty"` + SecurityPolicy *Permission `gorm:"-:all" json:"security_policy,omitempty"` + ProjectManagement *Permission `gorm:"-:all" json:"project_management,omitempty"` + Notification *Permission `gorm:"-:all" json:"notification,omitempty"` + Configuration *Permission `gorm:"-:all" json:"configuration,omitempty"` +} + +func NewDefaultPermissionSet() *PermissionSet { + return &PermissionSet{ + Dashboard: newDashboard(), + Stack: newStack(), + SecurityPolicy: newSecurityPolicy(), + ProjectManagement: newProjectManagement(), + Notification: newNotification(), + Configuration: newConfiguration(), + } +} + +func GetEdgePermission(root *Permission, edgePermissions []*Permission, f *func(permission Permission) bool) []*Permission { + if root.Children == nil { + return append(edgePermissions, root) + } + + for _, child := range root.Children { + if f != nil && !(*f)(*child) { + continue + } + edgePermissions = GetEdgePermission(child, edgePermissions, f) + } + + return edgePermissions +} + +func SetRoleIDToPermission(roleID string, permission *Permission) { + permission.RoleID = helper.StringP(roleID) +} + +func endpointObjects(eps ...api.Endpoint) []*Endpoint { + var result []*Endpoint + for _, ep := range eps { + result = append(result, &Endpoint{ + Name: api.ApiMap[ep].Name, + Group: api.ApiMap[ep].Group, + }) + } + return result +} + +func newDashboard() *Permission { + dashboard := &Permission{ + Name: string(DashBoardPermission), + Children: []*Permission{ + { + Name: "대시보드", + Children: []*Permission{ + { + Name: "조회", + IsAllowed: helper.BoolP(false), + Endpoints: endpointObjects( + api.GetChartsDashboard, + api.GetChartDashboard, + api.GetStacksDashboard, + api.GetResourcesDashboard, + ), + }, + }, + }, + { + Name: "대시보드 설정", + Children: []*Permission{ + { + Name: "조회", + IsAllowed: helper.BoolP(false), + }, + { + Name: "생성", + IsAllowed: helper.BoolP(false), + }, + { + Name: "수정", + IsAllowed: helper.BoolP(false), + }, + { + Name: "삭제", + IsAllowed: helper.BoolP(false), + }, + }, + }, + }, + } + + return dashboard +} + +func newStack() *Permission { + stack := &Permission{ + Name: string(StackPermission), + Children: []*Permission{ + { + Name: "조회", + IsAllowed: helper.BoolP(false), + Endpoints: endpointObjects( + api.GetStacks, + api.GetStack, + api.CheckStackName, + api.GetStackStatus, + api.GetStackKubeConfig, + + api.SetFavoriteStack, + api.DeleteFavoriteStack, + ), + }, + { + Name: "생성", + IsAllowed: helper.BoolP(false), + Endpoints: endpointObjects( + api.CreateStack, + api.InstallStack, + ), + }, + { + Name: "수정", + IsAllowed: helper.BoolP(false), + Endpoints: endpointObjects( + api.UpdateStack, + ), + }, + { + Name: "삭제", + IsAllowed: helper.BoolP(false), + Endpoints: endpointObjects( + api.DeleteStack, + ), + }, + }, + } + + return stack +} + +func newSecurityPolicy() *Permission { + security_policy := &Permission{ + Name: string(SecurityPolicyPermission), + Children: []*Permission{ + { + Name: "보안/정책", + Children: []*Permission{ + { + Name: "조회", + IsAllowed: helper.BoolP(false), + }, + { + Name: "생성", + IsAllowed: helper.BoolP(false), + }, + { + Name: "수정", + IsAllowed: helper.BoolP(false), + }, + { + Name: "삭제", + IsAllowed: helper.BoolP(false), + }, + }, + }, + }, + } + + return security_policy +} + +func newProjectManagement() *Permission { + projectManagement := &Permission{ + Name: string(ProjectManagementPermission), + Children: []*Permission{ + { + Name: "프로젝트", + Children: []*Permission{ + { + Name: "조회", + IsAllowed: helper.BoolP(false), + Endpoints: endpointObjects( + api.GetProjects, + api.GetProject, + ), + }, + { + Name: "생성", + IsAllowed: helper.BoolP(false), + Endpoints: endpointObjects( + api.CreateProject, + ), + }, + }, + }, + { + Name: "앱 서빙", + Children: []*Permission{ + { + Name: "조회", + IsAllowed: helper.BoolP(false), + Endpoints: endpointObjects( + api.GetAppServeApps, + api.GetAppServeApp, + api.GetNumOfAppsOnStack, + api.GetAppServeAppLatestTask, + api.IsAppServeAppExist, + api.IsAppServeAppNameExist, + ), + }, + { + Name: "빌드", + IsAllowed: helper.BoolP(false), + Endpoints: endpointObjects( + api.CreateAppServeApp, + api.IsAppServeAppExist, + api.IsAppServeAppNameExist, + api.UpdateAppServeApp, + api.UpdateAppServeAppEndpoint, + api.UpdateAppServeAppStatus, + api.RollbackAppServeApp, + ), + }, + { + Name: "배포", + IsAllowed: helper.BoolP(false), + Endpoints: endpointObjects( + api.CreateAppServeApp, + api.IsAppServeAppExist, + api.IsAppServeAppNameExist, + api.UpdateAppServeApp, + api.UpdateAppServeAppEndpoint, + api.UpdateAppServeAppStatus, + api.RollbackAppServeApp, + ), + }, + { + Name: "삭제", + IsAllowed: helper.BoolP(false), + Endpoints: endpointObjects( + api.DeleteAppServeApp, + ), + }, + }, + }, + { + Name: "설정-일반", + Children: []*Permission{ + { + Name: "조회", + IsAllowed: helper.BoolP(false), + Endpoints: endpointObjects( + api.GetProjects, + api.GetProject, + + api.GetProjectRoles, + api.GetProjectRole, + ), + }, + { + Name: "수정", + IsAllowed: helper.BoolP(false), + Endpoints: endpointObjects( + api.UpdateProject, + ), + }, + { + Name: "삭제", + IsAllowed: helper.BoolP(false), + Endpoints: endpointObjects( + api.DeleteProject, + ), + }, + }, + }, + { + Name: "설정-멤버", + Children: []*Permission{ + { + Name: "조회", + IsAllowed: helper.BoolP(false), + Endpoints: endpointObjects( + api.GetProjectMembers, + api.GetProjectMember, + api.GetProjectRoles, + api.GetProjectRole, + ), + }, + { + Name: "생성", + IsAllowed: helper.BoolP(false), + Endpoints: endpointObjects( + api.AddProjectMember, + ), + }, + { + Name: "수정", + IsAllowed: helper.BoolP(false), + Endpoints: endpointObjects( + api.UpdateProjectMemberRole, + ), + }, + { + Name: "삭제", + IsAllowed: helper.BoolP(false), + Endpoints: endpointObjects( + api.RemoveProjectMember, + ), + }, + }, + }, + { + Name: "설정-네임스페이스", + Children: []*Permission{ + { + Name: "조회", + IsAllowed: helper.BoolP(false), + Endpoints: endpointObjects( + api.GetProjectNamespaces, + api.GetProjectNamespace, + ), + }, + { + Name: "생성", + IsAllowed: helper.BoolP(false), + Endpoints: endpointObjects( + api.CreateProjectNamespace, + ), + }, + { + Name: "수정", + IsAllowed: helper.BoolP(false), + Endpoints: endpointObjects(), + }, + { + Name: "삭제", + IsAllowed: helper.BoolP(false), + Endpoints: endpointObjects( + api.DeleteProjectNamespace, + ), + }, + }, + }, + }, + } + + return projectManagement +} + +func newNotification() *Permission { + notification := &Permission{ + Name: string(NotificationPermission), + Children: []*Permission{ + { + Name: "시스템 경고", + Children: []*Permission{ + { + Name: "조회", + IsAllowed: helper.BoolP(false), + }, + }, + }, + { + Name: "보안/정책 감사로그", + Children: []*Permission{ + { + Name: "조회", + IsAllowed: helper.BoolP(false), + }, + }, + }, + }, + } + + return notification +} + +func newConfiguration() *Permission { + configuration := &Permission{ + Name: string(ConfigurationPermission), + Children: []*Permission{ + { + Name: "일반", + Children: []*Permission{ + { + Name: "조회", + IsAllowed: helper.BoolP(false), + }, + { + Name: "수정", + IsAllowed: helper.BoolP(false), + }, + }, + }, + { + Name: "클라우드 계정", + Children: []*Permission{ + { + Name: "조회", + IsAllowed: helper.BoolP(false), + }, + { + Name: "생성", + IsAllowed: helper.BoolP(false), + }, + { + Name: "수정", + IsAllowed: helper.BoolP(false), + }, + { + Name: "삭제", + IsAllowed: helper.BoolP(false), + }, + }, + }, + { + Name: "스택 템플릿", + Children: []*Permission{ + { + Name: "조회", + IsAllowed: helper.BoolP(false), + }, + }, + }, + { + Name: "프로젝트 관리", + Children: []*Permission{ + { + Name: "조회", + IsAllowed: helper.BoolP(false), + }, + { + Name: "생성", + IsAllowed: helper.BoolP(false), + }, + { + Name: "수정", + IsAllowed: helper.BoolP(false), + }, + { + Name: "삭제", + IsAllowed: helper.BoolP(false), + }, + }, + }, + { + Name: "사용자", + Children: []*Permission{ + { + Name: "조회", + IsAllowed: helper.BoolP(false), + }, + { + Name: "생성", + IsAllowed: helper.BoolP(false), + }, + { + Name: "수정", + IsAllowed: helper.BoolP(false), + }, + { + Name: "삭제", + IsAllowed: helper.BoolP(false), + }, + }, + }, + { + Name: "사용자 권한 관리", + Children: []*Permission{ + { + Name: "조회", + IsAllowed: helper.BoolP(false), + }, + { + Name: "생성", + IsAllowed: helper.BoolP(false), + }, + { + Name: "수정", + IsAllowed: helper.BoolP(false), + }, + { + Name: "삭제", + IsAllowed: helper.BoolP(false), + }, + }, + }, + { + Name: "알림 설정", + Children: []*Permission{ + { + Name: "조회", + IsAllowed: helper.BoolP(false), + }, + { + Name: "생성", + IsAllowed: helper.BoolP(false), + }, + { + Name: "수정", + IsAllowed: helper.BoolP(false), + }, + { + Name: "삭제", + IsAllowed: helper.BoolP(false), + }, + }, + }, + }, + } + + return configuration +} + +func (p *PermissionSet) SetAllowedPermissionSet() { + edgePermissions := make([]*Permission, 0) + edgePermissions = append(edgePermissions, GetEdgePermission(p.Dashboard, edgePermissions, nil)...) + edgePermissions = append(edgePermissions, GetEdgePermission(p.Stack, edgePermissions, nil)...) + edgePermissions = append(edgePermissions, GetEdgePermission(p.SecurityPolicy, edgePermissions, nil)...) + edgePermissions = append(edgePermissions, GetEdgePermission(p.ProjectManagement, edgePermissions, nil)...) + edgePermissions = append(edgePermissions, GetEdgePermission(p.Notification, edgePermissions, nil)...) + edgePermissions = append(edgePermissions, GetEdgePermission(p.Configuration, edgePermissions, nil)...) + + for _, permission := range edgePermissions { + permission.IsAllowed = helper.BoolP(true) + } + + return +} + +func (p *PermissionSet) SetUserPermissionSet() { + f := func(permission Permission) bool { + return permission.Name == "조회" + } + edgePermissions := make([]*Permission, 0) + edgePermissions = append(edgePermissions, GetEdgePermission(p.Dashboard, edgePermissions, nil)...) + edgePermissions = append(edgePermissions, GetEdgePermission(p.Stack, edgePermissions, &f)...) + edgePermissions = append(edgePermissions, GetEdgePermission(p.SecurityPolicy, edgePermissions, &f)...) + edgePermissions = append(edgePermissions, GetEdgePermission(p.ProjectManagement, edgePermissions, &f)...) + edgePermissions = append(edgePermissions, GetEdgePermission(p.Notification, edgePermissions, &f)...) + //edgePermissions = append(edgePermissions, GetEdgePermission(p.Configuration, edgePermissions, &f)...) + + for _, permission := range edgePermissions { + permission.IsAllowed = helper.BoolP(true) + } + + return +} + +func (p *PermissionSet) SetRoleId(roleId string) { + setRoleIdToPermission(p.Dashboard, roleId) + setRoleIdToPermission(p.Stack, roleId) + setRoleIdToPermission(p.SecurityPolicy, roleId) + setRoleIdToPermission(p.ProjectManagement, roleId) + setRoleIdToPermission(p.Notification, roleId) + setRoleIdToPermission(p.Configuration, roleId) +} + +func setRoleIdToPermission(root *Permission, roleId string) { + root.RoleID = helper.StringP(roleId) + + if root.Children == nil { + return + } + + for _, child := range root.Children { + setRoleIdToPermission(child, roleId) + } +} diff --git a/internal/model/policy-template.go b/internal/model/policy-template.go new file mode 100644 index 00000000..430c4b7d --- /dev/null +++ b/internal/model/policy-template.go @@ -0,0 +1,48 @@ +package model + +import ( + "github.com/google/uuid" + "github.com/openinfradev/tks-api/pkg/domain" + "gorm.io/gorm" +) + +type PolicyTemplateSupportedVersion struct { + gorm.Model + + PolicyTemplateId uuid.UUID `gorm:"index:template_version,unique"` + Version string `gorm:"index:template_version,unique"` + + ParameterSchema string `gorm:"type:text"` + Rego string `gorm:"type:text"` + Libs string `gorm:"type:text"` +} + +type PolicyTemplate struct { + gorm.Model + + ID uuid.UUID `gorm:"primarykey;type:varchar(36);not null"` + Type string // Org or Tks + Name string + Version string + SupportedVersions []PolicyTemplateSupportedVersion `gorm:"foreignKey:PolicyTemplateId"` + Description string + Kind string + Deprecated bool + Mandatory bool // Tks 인 경우에는 무시 + Severity string + PermittedOrganizations []Organization `gorm:"many2many:policy_template_permitted_organiations;"` + TemplateName string `gorm:"-:all" json:"templateName"` + ParametersSchema []domain.ParameterDef `gorm:"-:all" json:"parametersSchema,omitempty"` + Rego string `gorm:"-:all"` + Libs []string `gorm:"-:all"` + PermittedOrganizationIds []string `gorm:"-:all"` + CreatorId *uuid.UUID `gorm:"type:uuid"` + Creator User `gorm:"foreignKey:CreatorId"` + UpdatorId *uuid.UUID `gorm:"type:uuid"` + Updator User `gorm:"foreignKey:UpdatorId"` +} + +func (c *PolicyTemplate) BeforeCreate(tx *gorm.DB) (err error) { + c.ID = uuid.New() + return nil +} diff --git a/internal/model/role.go b/internal/model/role.go new file mode 100644 index 00000000..01f6497a --- /dev/null +++ b/internal/model/role.go @@ -0,0 +1,27 @@ +package model + +import ( + "time" + + "github.com/google/uuid" + "gorm.io/gorm" +) + +func (r *Role) BeforeCreate(tx *gorm.DB) (err error) { + r.ID = uuid.New().String() + return nil +} + +type Role struct { + gorm.Model + + ID string `gorm:"primarykey;" json:"id"` + Name string `json:"name"` + OrganizationID string `json:"organizationId"` + Organization Organization `gorm:"foreignKey:OrganizationID;references:ID;" json:"organization"` + Type string `json:"type"` + Description string `json:"description"` + Creator uuid.UUID `json:"creator"` + CreatedAt time.Time `json:"createdAt"` + UpdatedAt time.Time `json:"updatedAt"` +} diff --git a/internal/model/stack-template.go b/internal/model/stack-template.go new file mode 100644 index 00000000..c74cad06 --- /dev/null +++ b/internal/model/stack-template.go @@ -0,0 +1,40 @@ +package model + +import ( + "github.com/google/uuid" + "gorm.io/datatypes" + "gorm.io/gorm" +) + +type StackTemplate struct { + gorm.Model + + ID uuid.UUID `gorm:"primarykey"` + Name string `gorm:"index"` + Description string `gorm:"index"` + Template string + TemplateType string + Version string + CloudService string + Platform string + KubeVersion string + KubeType string + Organizations []Organization `gorm:"many2many:stack_template_organizations"` + Services datatypes.JSON + ServiceIds []string `gorm:"-:all"` + OrganizationIds []string `gorm:"-:all"` + CreatorId *uuid.UUID `gorm:"type:uuid"` + Creator User `gorm:"foreignKey:CreatorId"` + UpdatorId *uuid.UUID `gorm:"type:uuid"` + Updator User `gorm:"foreignKey:UpdatorId"` +} + +func (c *StackTemplate) BeforeCreate(tx *gorm.DB) (err error) { + c.ID = uuid.New() + return nil +} + +type StackTemplateOrganization struct { + StackTemplateId uuid.UUID `gorm:"primarykey"` + OrganizationId string `gorm:"primarykey"` +} diff --git a/internal/model/stack.go b/internal/model/stack.go new file mode 100644 index 00000000..72300ee5 --- /dev/null +++ b/internal/model/stack.go @@ -0,0 +1,45 @@ +package model + +import ( + "github.com/google/uuid" + "github.com/openinfradev/tks-api/pkg/domain" + "gorm.io/gorm" +) + +type Stack = struct { + gorm.Model + + ID domain.StackId + Name string + Description string + ClusterId string + OrganizationId string + CloudService string + CloudAccountId uuid.UUID + CloudAccount CloudAccount + StackTemplateId uuid.UUID + StackTemplate StackTemplate + Status domain.StackStatus + StatusDesc string + PrimaryCluster bool + GrafanaUrl string + CreatorId *uuid.UUID + Creator User + UpdatorId *uuid.UUID + Updator User + Favorited bool + ClusterEndpoint string + Resource domain.DashboardStack +} + +type StackConf struct { + TksCpNode int + TksCpNodeMax int + TksCpNodeType string + TksInfraNode int + TksInfraNodeMax int + TksInfraNodeType string + TksUserNode int + TksUserNodeMax int + TksUserNodeType string +} diff --git a/internal/model/user.go b/internal/model/user.go new file mode 100644 index 00000000..96303110 --- /dev/null +++ b/internal/model/user.go @@ -0,0 +1,34 @@ +package model + +import ( + "time" + + "github.com/google/uuid" + "gorm.io/gorm" +) + +type User struct { + ID uuid.UUID `gorm:"primarykey;type:uuid" json:"id"` + AccountId string `json:"accountId"` + Password string `gorm:"-:all" json:"password"` + Name string `json:"name"` + Token string `json:"token"` + RoleId string + Role Role `gorm:"foreignKey:RoleId;references:ID" json:"role"` + OrganizationId string + Organization Organization `gorm:"foreignKey:OrganizationId;references:ID" json:"organization"` + Creator string `json:"creator"` + CreatedAt time.Time `json:"createdAt"` + UpdatedAt time.Time `json:"updatedAt"` + PasswordUpdatedAt time.Time `json:"passwordUpdatedAt"` + PasswordExpired bool `json:"passwordExpired"` + + Email string `json:"email"` + Department string `json:"department"` + Description string `json:"description"` +} + +func (g *User) BeforeCreate(tx *gorm.DB) (err error) { + g.PasswordUpdatedAt = time.Now() + return nil +} diff --git a/internal/pagination/pagination.go b/internal/pagination/pagination.go index 0de16f10..591a498c 100644 --- a/internal/pagination/pagination.go +++ b/internal/pagination/pagination.go @@ -9,6 +9,8 @@ import ( "github.com/openinfradev/tks-api/internal/helper" "github.com/openinfradev/tks-api/internal/serializer" "github.com/openinfradev/tks-api/pkg/domain" + "golang.org/x/text/cases" + "golang.org/x/text/language" "gorm.io/gorm" "goyave.dev/goyave/v4" @@ -84,6 +86,10 @@ func (p *Pagination) GetFilters() []Filter { return p.Filters } +func (p *Pagination) AddFilter(f Filter) { + p.Filters = append(p.Filters, f) +} + func (p *Pagination) MakePaginationRequest() { if p.PaginationRequest == nil { p.PaginationRequest = &goyave.Request{} @@ -114,9 +120,11 @@ func (p *Pagination) MakePaginationRequest() { } pgSorts = append(pgSorts, &pgSort) + pgJoins := filter.Join{} + p.PaginationRequest.Data = map[string]interface{}{ - "filter": pgFilters, - //"join": pgJoins, + "filter": pgFilters, + "join": pgJoins, "page": p.Page, "per_page": p.Limit, "sort": pgSorts, @@ -212,7 +220,7 @@ func NewPagination(urlParams *url.Values) *Pagination { releation := "" arrColumns := strings.Split(column, ".") if len(arrColumns) > 1 { - releation = arrColumns[0] + releation = cases.Title(language.English, cases.Compact).String(arrColumns[0]) column = arrColumns[1] } diff --git a/internal/repository/alert.go b/internal/repository/alert.go index 4e8c8575..2d35f536 100644 --- a/internal/repository/alert.go +++ b/internal/repository/alert.go @@ -4,27 +4,25 @@ import ( "time" "github.com/google/uuid" - "gorm.io/datatypes" "gorm.io/gorm" "gorm.io/gorm/clause" + "github.com/openinfradev/tks-api/internal/model" "github.com/openinfradev/tks-api/internal/pagination" - "github.com/openinfradev/tks-api/internal/serializer" "github.com/openinfradev/tks-api/pkg/domain" - "github.com/openinfradev/tks-api/pkg/log" ) // Interfaces type IAlertRepository interface { - Get(alertId uuid.UUID) (domain.Alert, error) - GetByName(organizationId string, name string) (domain.Alert, error) - Fetch(organizationId string, pg *pagination.Pagination) ([]domain.Alert, error) - FetchPodRestart(organizationId string, start time.Time, end time.Time) ([]domain.Alert, error) - Create(dto domain.Alert) (alertId uuid.UUID, err error) - Update(dto domain.Alert) (err error) - Delete(dto domain.Alert) (err error) - - CreateAlertAction(dto domain.AlertAction) (alertActionId uuid.UUID, err error) + Get(alertId uuid.UUID) (model.Alert, error) + GetByName(organizationId string, name string) (model.Alert, error) + Fetch(organizationId string, pg *pagination.Pagination) ([]model.Alert, error) + FetchPodRestart(organizationId string, start time.Time, end time.Time) ([]model.Alert, error) + Create(dto model.Alert) (alertId uuid.UUID, err error) + Update(dto model.Alert) (err error) + Delete(dto model.Alert) (err error) + + CreateAlertAction(dto model.AlertAction) (alertActionId uuid.UUID, err error) } type AlertRepository struct { @@ -37,114 +35,55 @@ func NewAlertRepository(db *gorm.DB) IAlertRepository { } } -// Models -type Alert struct { - gorm.Model - - ID uuid.UUID `gorm:"primarykey"` - OrganizationId string - Organization domain.Organization `gorm:"foreignKey:OrganizationId"` - Name string - Code string - Description string - Grade string - Message string - ClusterId domain.ClusterId - Cluster Cluster `gorm:"foreignKey:ClusterId"` - Node string - CheckPoint string - GrafanaUrl string - Summary string - AlertActions []AlertAction - RawData datatypes.JSON - Status domain.AlertActionStatus `gorm:"index"` -} - -func (c *Alert) BeforeCreate(tx *gorm.DB) (err error) { - c.ID = uuid.New() - return nil -} - -type AlertAction struct { - gorm.Model - - ID uuid.UUID `gorm:"primarykey"` - AlertId uuid.UUID - Content string - Status domain.AlertActionStatus - TakerId *uuid.UUID `gorm:"type:uuid"` - Taker domain.User `gorm:"foreignKey:TakerId"` -} - -func (c *AlertAction) BeforeCreate(tx *gorm.DB) (err error) { - c.ID = uuid.New() - return nil -} - // Logics -func (r *AlertRepository) Get(alertId uuid.UUID) (out domain.Alert, err error) { - var alert Alert - res := r.db.Preload("AlertActions.Taker").Preload(clause.Associations).First(&alert, "id = ?", alertId) +func (r *AlertRepository) Get(alertId uuid.UUID) (out model.Alert, err error) { + res := r.db.Preload("AlertActions.Taker").Preload(clause.Associations).First(&out, "id = ?", alertId) if res.Error != nil { - return domain.Alert{}, res.Error + return model.Alert{}, res.Error } - out = reflectAlert(alert) return } -func (r *AlertRepository) GetByName(organizationId string, name string) (out domain.Alert, err error) { - var alert Alert - res := r.db.Preload("AlertActions.Taker").Preload(clause.Associations).First(&alert, "organization_id = ? AND name = ?", organizationId, name) - +func (r *AlertRepository) GetByName(organizationId string, name string) (out model.Alert, err error) { + res := r.db.Preload("AlertActions.Taker").Preload(clause.Associations).First(&out, "organization_id = ? AND name = ?", organizationId, name) if res.Error != nil { - return domain.Alert{}, res.Error + return model.Alert{}, res.Error } - out = reflectAlert(alert) return } -func (r *AlertRepository) Fetch(organizationId string, pg *pagination.Pagination) (out []domain.Alert, err error) { - var alerts []Alert +func (r *AlertRepository) Fetch(organizationId string, pg *pagination.Pagination) (out []model.Alert, err error) { if pg == nil { pg = pagination.NewPagination(nil) } - _, res := pg.Fetch(r.db.Model(&Alert{}). + _, res := pg.Fetch(r.db.Model(&model.Alert{}). Preload("AlertActions", func(db *gorm.DB) *gorm.DB { return db.Order("created_at ASC") }).Preload("AlertActions.Taker"). Preload("Cluster", "status = 2"). Preload("Organization"). Joins("join clusters on clusters.id = alerts.cluster_id AND clusters.status = 2"). - Where("alerts.organization_id = ?", organizationId), &alerts) + Where("alerts.organization_id = ?", organizationId), &out) if res.Error != nil { return nil, res.Error } - - for _, alert := range alerts { - out = append(out, reflectAlert(alert)) - } return } -func (r *AlertRepository) FetchPodRestart(organizationId string, start time.Time, end time.Time) (out []domain.Alert, err error) { - var alerts []Alert +func (r *AlertRepository) FetchPodRestart(organizationId string, start time.Time, end time.Time) (out []model.Alert, err error) { res := r.db.Preload(clause.Associations).Order("created_at DESC"). Where("organization_id = ? AND name = 'pod-restart-frequently' AND created_at BETWEEN ? AND ?", organizationId, start, end). - Find(&alerts) + Find(&out) if res.Error != nil { return nil, res.Error } - - for _, alert := range alerts { - out = append(out, reflectAlert(alert)) - } return } -func (r *AlertRepository) Create(dto domain.Alert) (alertId uuid.UUID, err error) { - alert := Alert{ +func (r *AlertRepository) Create(dto model.Alert) (alertId uuid.UUID, err error) { + alert := model.Alert{ OrganizationId: dto.OrganizationId, Name: dto.Name, Code: dto.Code, @@ -166,8 +105,8 @@ func (r *AlertRepository) Create(dto domain.Alert) (alertId uuid.UUID, err error return alert.ID, nil } -func (r *AlertRepository) Update(dto domain.Alert) (err error) { - res := r.db.Model(&Alert{}). +func (r *AlertRepository) Update(dto model.Alert) (err error) { + res := r.db.Model(&model.Alert{}). Where("id = ?", dto.ID). Updates(map[string]interface{}{"Description": dto.Description}) if res.Error != nil { @@ -176,16 +115,16 @@ func (r *AlertRepository) Update(dto domain.Alert) (err error) { return nil } -func (r *AlertRepository) Delete(dto domain.Alert) (err error) { - res := r.db.Delete(&Alert{}, "id = ?", dto.ID) +func (r *AlertRepository) Delete(dto model.Alert) (err error) { + res := r.db.Delete(&model.Alert{}, "id = ?", dto.ID) if res.Error != nil { return res.Error } return nil } -func (r *AlertRepository) CreateAlertAction(dto domain.AlertAction) (alertActionId uuid.UUID, err error) { - alert := AlertAction{ +func (r *AlertRepository) CreateAlertAction(dto model.AlertAction) (alertActionId uuid.UUID, err error) { + alert := model.AlertAction{ AlertId: dto.AlertId, Content: dto.Content, Status: dto.Status, @@ -195,7 +134,7 @@ func (r *AlertRepository) CreateAlertAction(dto domain.AlertAction) (alertAction if res.Error != nil { return uuid.Nil, res.Error } - res = r.db.Model(&Alert{}). + res = r.db.Model(&model.Alert{}). Where("id = ?", dto.AlertId). Update("status", dto.Status) if res.Error != nil { @@ -204,25 +143,3 @@ func (r *AlertRepository) CreateAlertAction(dto domain.AlertAction) (alertAction return alert.ID, nil } - -func reflectAlert(alert Alert) (out domain.Alert) { - if err := serializer.Map(alert.Model, &out); err != nil { - log.Error(err) - } - if err := serializer.Map(alert, &out); err != nil { - log.Error(err) - } - - out.AlertActions = make([]domain.AlertAction, len(alert.AlertActions)) - for i, alertAction := range alert.AlertActions { - if err := serializer.Map(alertAction.Model, &out.AlertActions[i]); err != nil { - log.Error(err) - continue - } - if err := serializer.Map(alertAction, &out.AlertActions[i]); err != nil { - log.Error(err) - continue - } - } - return -} diff --git a/internal/repository/app-group.go b/internal/repository/app-group.go index d78aa1bc..bd824996 100644 --- a/internal/repository/app-group.go +++ b/internal/repository/app-group.go @@ -3,26 +3,24 @@ package repository import ( "fmt" - "github.com/google/uuid" "gorm.io/datatypes" "gorm.io/gorm" - "github.com/openinfradev/tks-api/internal/helper" + "github.com/openinfradev/tks-api/internal/model" "github.com/openinfradev/tks-api/internal/pagination" - "github.com/openinfradev/tks-api/internal/serializer" "github.com/openinfradev/tks-api/pkg/domain" "github.com/openinfradev/tks-api/pkg/log" ) // Interfaces type IAppGroupRepository interface { - Fetch(clusterId domain.ClusterId, pg *pagination.Pagination) (res []domain.AppGroup, err error) - Get(id domain.AppGroupId) (domain.AppGroup, error) - Create(dto domain.AppGroup) (id domain.AppGroupId, err error) - Update(dto domain.AppGroup) (err error) + Fetch(clusterId domain.ClusterId, pg *pagination.Pagination) (res []model.AppGroup, err error) + Get(id domain.AppGroupId) (model.AppGroup, error) + Create(dto model.AppGroup) (id domain.AppGroupId, err error) + Update(dto model.AppGroup) (err error) Delete(id domain.AppGroupId) error - GetApplications(id domain.AppGroupId, applicationType domain.ApplicationType) (applications []domain.Application, err error) - UpsertApplication(dto domain.Application) error + GetApplications(id domain.AppGroupId, applicationType domain.ApplicationType) (applications []model.Application, err error) + UpsertApplication(dto model.Application) error InitWorkflow(appGroupId domain.AppGroupId, workflowId string, status domain.AppGroupStatus) error InitWorkflowDescription(clusterId domain.ClusterId) error } @@ -37,76 +35,31 @@ func NewAppGroupRepository(db *gorm.DB) IAppGroupRepository { } } -// Models -type AppGroup struct { - gorm.Model - - ID domain.AppGroupId `gorm:"primarykey"` - AppGroupType domain.AppGroupType - ClusterId domain.ClusterId - Name string - Description string - WorkflowId string - Status domain.AppGroupStatus - StatusDesc string - CreatorId *uuid.UUID `gorm:"type:uuid"` - Creator domain.User `gorm:"foreignKey:CreatorId"` - UpdatorId *uuid.UUID `gorm:"type:uuid"` - Updator domain.User `gorm:"foreignKey:UpdatorId"` -} - -func (c *AppGroup) BeforeCreate(tx *gorm.DB) (err error) { - c.ID = domain.AppGroupId(helper.GenerateApplicaionGroupId()) - return nil -} - -type Application struct { - gorm.Model - - ID uuid.UUID `gorm:"primarykey;type:uuid"` - AppGroupId domain.AppGroupId - Endpoint string - Metadata datatypes.JSON - Type domain.ApplicationType -} - -func (c *Application) BeforeCreate(tx *gorm.DB) (err error) { - c.ID = uuid.New() - return nil -} - // Logics -func (r *AppGroupRepository) Fetch(clusterId domain.ClusterId, pg *pagination.Pagination) (out []domain.AppGroup, err error) { - var appGroups []AppGroup +func (r *AppGroupRepository) Fetch(clusterId domain.ClusterId, pg *pagination.Pagination) (out []model.AppGroup, err error) { if pg == nil { pg = pagination.NewPagination(nil) } - _, res := pg.Fetch(r.db.Model(&AppGroup{}). - Where("cluster_id = ?", clusterId), &appGroups) + _, res := pg.Fetch(r.db.Model(&model.AppGroup{}). + Where("cluster_id = ?", clusterId), &out) if res.Error != nil { return nil, res.Error } - for _, appGroup := range appGroups { - outAppGroup := reflectAppGroup(appGroup) - out = append(out, outAppGroup) - } return out, nil } -func (r *AppGroupRepository) Get(id domain.AppGroupId) (domain.AppGroup, error) { - var appGroup AppGroup - res := r.db.First(&appGroup, "id = ?", id) +func (r *AppGroupRepository) Get(id domain.AppGroupId) (out model.AppGroup, err error) { + res := r.db.First(&out, "id = ?", id) if res.RowsAffected == 0 || res.Error != nil { - return domain.AppGroup{}, fmt.Errorf("Not found appGroup for %s", id) + return model.AppGroup{}, fmt.Errorf("Not found appGroup for %s", id) } - resAppGroup := reflectAppGroup(appGroup) - return resAppGroup, nil + return out, nil } -func (r *AppGroupRepository) Create(dto domain.AppGroup) (appGroupId domain.AppGroupId, err error) { - appGroup := AppGroup{ +func (r *AppGroupRepository) Create(dto model.AppGroup) (appGroupId domain.AppGroupId, err error) { + appGroup := model.AppGroup{ ClusterId: dto.ClusterId, AppGroupType: dto.AppGroupType, Name: dto.Name, @@ -124,8 +77,8 @@ func (r *AppGroupRepository) Create(dto domain.AppGroup) (appGroupId domain.AppG return appGroup.ID, nil } -func (r *AppGroupRepository) Update(dto domain.AppGroup) (err error) { - res := r.db.Model(&AppGroup{}). +func (r *AppGroupRepository) Update(dto model.AppGroup) (err error) { + res := r.db.Model(&model.AppGroup{}). Where("id = ?", dto.ID). Updates(map[string]interface{}{ "ClusterId": dto.ClusterId, @@ -141,35 +94,30 @@ func (r *AppGroupRepository) Update(dto domain.AppGroup) (err error) { } func (r *AppGroupRepository) Delete(id domain.AppGroupId) error { - res := r.db.Unscoped().Delete(&AppGroup{}, "id = ?", id) + res := r.db.Unscoped().Delete(&model.AppGroup{}, "id = ?", id) if res.Error != nil { return fmt.Errorf("could not delete appGroup %s", id) } return nil } -func (r *AppGroupRepository) GetApplications(id domain.AppGroupId, applicationType domain.ApplicationType) (out []domain.Application, err error) { - var applications []Application - res := r.db.Where("app_group_id = ? AND type = ?", id, applicationType).Find(&applications) +func (r *AppGroupRepository) GetApplications(id domain.AppGroupId, applicationType domain.ApplicationType) (out []model.Application, err error) { + res := r.db.Where("app_group_id = ? AND type = ?", id, applicationType).Find(&out) if res.Error != nil { return nil, res.Error } - for _, application := range applications { - outApplication := reflectApplication(application) - out = append(out, outApplication) - } return out, nil } -func (r *AppGroupRepository) UpsertApplication(dto domain.Application) error { - res := r.db.Where(Application{ +func (r *AppGroupRepository) UpsertApplication(dto model.Application) error { + res := r.db.Where(model.Application{ AppGroupId: dto.AppGroupId, - Type: dto.ApplicationType, + Type: dto.Type, }). - Assign(Application{ + Assign(model.Application{ Endpoint: dto.Endpoint, Metadata: datatypes.JSON([]byte(dto.Metadata))}). - FirstOrCreate(&Application{}) + FirstOrCreate(&model.Application{}) if res.Error != nil { return res.Error } @@ -178,7 +126,7 @@ func (r *AppGroupRepository) UpsertApplication(dto domain.Application) error { } func (r *AppGroupRepository) InitWorkflow(appGroupId domain.AppGroupId, workflowId string, status domain.AppGroupStatus) error { - res := r.db.Model(&AppGroup{}). + res := r.db.Model(&model.AppGroup{}). Where("ID = ?", appGroupId). Updates(map[string]interface{}{"Status": status, "WorkflowId": workflowId, "StatusDesc": ""}) @@ -190,7 +138,7 @@ func (r *AppGroupRepository) InitWorkflow(appGroupId domain.AppGroupId, workflow } func (r *AppGroupRepository) InitWorkflowDescription(clusterId domain.ClusterId) error { - res := r.db.Model(&AppGroup{}). + res := r.db.Model(&model.AppGroup{}). Where("cluster_id = ?", clusterId). Updates(map[string]interface{}{"WorkflowId": "", "StatusDesc": ""}) @@ -200,22 +148,3 @@ func (r *AppGroupRepository) InitWorkflowDescription(clusterId domain.ClusterId) return nil } - -func reflectAppGroup(appGroup AppGroup) (out domain.AppGroup) { - if err := serializer.Map(appGroup.Model, &out); err != nil { - log.Error(err) - } - if err := serializer.Map(appGroup, &out); err != nil { - log.Error(err) - } - return -} - -func reflectApplication(application Application) (out domain.Application) { - if err := serializer.Map(application, &out); err != nil { - log.Error(err) - } - out.Metadata = application.Metadata.String() - return - -} diff --git a/internal/repository/app-serve-app.go b/internal/repository/app-serve-app.go index 479f4e77..a1d3e291 100644 --- a/internal/repository/app-serve-app.go +++ b/internal/repository/app-serve-app.go @@ -4,6 +4,7 @@ import ( "fmt" "time" + "github.com/openinfradev/tks-api/internal/model" "github.com/openinfradev/tks-api/internal/pagination" "github.com/openinfradev/tks-api/pkg/domain" "github.com/openinfradev/tks-api/pkg/log" @@ -11,19 +12,19 @@ import ( ) type IAppServeAppRepository interface { - CreateAppServeApp(app *domain.AppServeApp) (appId string, taskId string, err error) - GetAppServeApps(organizationId string, showAll bool, pg *pagination.Pagination) ([]domain.AppServeApp, error) - GetAppServeAppById(appId string) (*domain.AppServeApp, error) + CreateAppServeApp(app *model.AppServeApp) (appId string, taskId string, err error) + GetAppServeApps(organizationId string, showAll bool, pg *pagination.Pagination) ([]model.AppServeApp, error) + GetAppServeAppById(appId string) (*model.AppServeApp, error) - GetAppServeAppTasksByAppId(appId string, pg *pagination.Pagination) ([]domain.AppServeAppTask, error) - GetAppServeAppTaskById(taskId string) (*domain.AppServeAppTask, *domain.AppServeApp, error) + GetAppServeAppTasksByAppId(appId string, pg *pagination.Pagination) ([]model.AppServeAppTask, error) + GetAppServeAppTaskById(taskId string) (*model.AppServeAppTask, *model.AppServeApp, error) - GetAppServeAppLatestTask(appId string) (*domain.AppServeAppTask, error) + GetAppServeAppLatestTask(appId string) (*model.AppServeAppTask, error) GetNumOfAppsOnStack(organizationId string, clusterId string) (int64, error) IsAppServeAppExist(appId string) (int64, error) IsAppServeAppNameExist(orgId string, appName string) (int64, error) - CreateTask(task *domain.AppServeAppTask) (taskId string, err error) + CreateTask(task *model.AppServeAppTask) (taskId string, err error) UpdateStatus(appId string, taskId string, status string, output string) error UpdateEndpoint(appId string, taskId string, endpoint string, previewEndpoint string, helmRevision int32) error GetTaskCountById(appId string) (int64, error) @@ -39,7 +40,7 @@ func NewAppServeAppRepository(db *gorm.DB) IAppServeAppRepository { } } -func (r *AppServeAppRepository) CreateAppServeApp(app *domain.AppServeApp) (appId string, taskId string, err error) { +func (r *AppServeAppRepository) CreateAppServeApp(app *model.AppServeApp) (appId string, taskId string, err error) { res := r.db.Create(&app) if res.Error != nil { @@ -51,7 +52,7 @@ func (r *AppServeAppRepository) CreateAppServeApp(app *domain.AppServeApp) (appI // Update creates new appServeApp task for existing appServeApp. func (r *AppServeAppRepository) CreateTask( - task *domain.AppServeAppTask) (string, error) { + task *model.AppServeAppTask) (string, error) { res := r.db.Create(task) if res.Error != nil { return "", res.Error @@ -60,14 +61,14 @@ func (r *AppServeAppRepository) CreateTask( return task.ID, nil } -func (r *AppServeAppRepository) GetAppServeApps(organizationId string, showAll bool, pg *pagination.Pagination) (apps []domain.AppServeApp, err error) { - var clusters []Cluster +func (r *AppServeAppRepository) GetAppServeApps(organizationId string, showAll bool, pg *pagination.Pagination) (apps []model.AppServeApp, err error) { + var clusters []model.Cluster if pg == nil { pg = pagination.NewPagination(nil) } // TODO: should return different records based on showAll param - _, res := pg.Fetch(r.db.Model(&domain.AppServeApp{}). + _, res := pg.Fetch(r.db.Model(&model.AppServeApp{}). Where("app_serve_apps.organization_id = ? AND status <> 'DELETE_SUCCESS'", organizationId), &apps) if res.Error != nil { return nil, fmt.Errorf("error while finding appServeApps with organizationId: %s", organizationId) @@ -97,9 +98,9 @@ func (r *AppServeAppRepository) GetAppServeApps(organizationId string, showAll b return } -func (r *AppServeAppRepository) GetAppServeAppById(appId string) (*domain.AppServeApp, error) { - var app domain.AppServeApp - var cluster Cluster +func (r *AppServeAppRepository) GetAppServeAppById(appId string) (*model.AppServeApp, error) { + var app model.AppServeApp + var cluster model.Cluster res := r.db.Where("id = ?", appId).First(&app) if res.Error != nil { @@ -123,12 +124,12 @@ func (r *AppServeAppRepository) GetAppServeAppById(appId string) (*domain.AppSer return &app, nil } -func (r *AppServeAppRepository) GetAppServeAppTasksByAppId(appId string, pg *pagination.Pagination) (tasks []domain.AppServeAppTask, err error) { +func (r *AppServeAppRepository) GetAppServeAppTasksByAppId(appId string, pg *pagination.Pagination) (tasks []model.AppServeAppTask, err error) { if pg == nil { pg = pagination.NewPagination(nil) } - _, res := pg.Fetch(r.db.Model(&domain.AppServeAppTask{}). + _, res := pg.Fetch(r.db.Model(&model.AppServeAppTask{}). Where("app_serve_app_tasks.app_serve_app_id = ?", appId), &tasks) if res.Error != nil { return nil, fmt.Errorf("Error while finding tasks with appId: %s", appId) @@ -143,9 +144,9 @@ func (r *AppServeAppRepository) GetAppServeAppTasksByAppId(appId string, pg *pag } // Return single task info along with its parent app info -func (r *AppServeAppRepository) GetAppServeAppTaskById(taskId string) (*domain.AppServeAppTask, *domain.AppServeApp, error) { - var task domain.AppServeAppTask - var app domain.AppServeApp +func (r *AppServeAppRepository) GetAppServeAppTaskById(taskId string) (*model.AppServeAppTask, *model.AppServeApp, error) { + var task model.AppServeAppTask + var app model.AppServeApp // Retrieve task info res := r.db.Where("id = ?", taskId).First(&task) @@ -170,8 +171,8 @@ func (r *AppServeAppRepository) GetAppServeAppTaskById(taskId string) (*domain.A return &task, &app, nil } -func (r *AppServeAppRepository) GetAppServeAppLatestTask(appId string) (*domain.AppServeAppTask, error) { - var task domain.AppServeAppTask +func (r *AppServeAppRepository) GetAppServeAppLatestTask(appId string) (*model.AppServeAppTask, error) { + var task model.AppServeAppTask // TODO: Does this work?? where's app ID here? res := r.db.Order("created_at desc").First(&task) @@ -187,7 +188,7 @@ func (r *AppServeAppRepository) GetAppServeAppLatestTask(appId string) (*domain. } func (r *AppServeAppRepository) GetNumOfAppsOnStack(organizationId string, clusterId string) (int64, error) { - var apps []domain.AppServeApp + var apps []model.AppServeApp queryStr := fmt.Sprintf("organization_id = '%s' AND target_cluster_id = '%s' AND status <> 'DELETE_SUCCESS'", organizationId, clusterId) res := r.db.Find(&apps, queryStr) @@ -227,7 +228,7 @@ func (r *AppServeAppRepository) IsAppServeAppNameExist(orgId string, appName str func (r *AppServeAppRepository) UpdateStatus(appId string, taskId string, status string, output string) error { now := time.Now() - app := domain.AppServeApp{ + app := model.AppServeApp{ ID: appId, Status: status, UpdatedAt: &now, @@ -237,7 +238,7 @@ func (r *AppServeAppRepository) UpdateStatus(appId string, taskId string, status return fmt.Errorf("UpdateStatus: nothing updated in AppServeApp with ID %s", appId) } - task := domain.AppServeAppTask{ + task := model.AppServeAppTask{ ID: taskId, Status: status, Output: output, @@ -249,16 +250,16 @@ func (r *AppServeAppRepository) UpdateStatus(appId string, taskId string, status } //// Update task status - //res := r.db.Model(&domain.AppServeAppTask{}). + //res := r.db.Model(&model.AppServeAppTask{}). // Where("ID = ?", taskId). - // Updates(domain.AppServeAppTask{Status: status, Output: output}) + // Updates(model.AppServeAppTask{Status: status, Output: output}) // //if res.Error != nil || res.RowsAffected == 0 { // return fmt.Errorf("UpdateStatus: nothing updated in AppServeAppTask with ID %s", taskId) //} // //// Update status of the app. - //res = r.db.Model(&domain.AppServeApp{}). + //res = r.db.Model(&model.AppServeApp{}). // Where("ID = ?", appId). // Update("Status", status) //if res.Error != nil || res.RowsAffected == 0 { @@ -270,14 +271,14 @@ func (r *AppServeAppRepository) UpdateStatus(appId string, taskId string, status func (r *AppServeAppRepository) UpdateEndpoint(appId string, taskId string, endpoint string, previewEndpoint string, helmRevision int32) error { now := time.Now() - app := domain.AppServeApp{ + app := model.AppServeApp{ ID: appId, EndpointUrl: endpoint, PreviewEndpointUrl: previewEndpoint, UpdatedAt: &now, } - task := domain.AppServeAppTask{ + task := model.AppServeAppTask{ ID: taskId, HelmRevision: helmRevision, UpdatedAt: &now, @@ -316,7 +317,7 @@ func (r *AppServeAppRepository) UpdateEndpoint(appId string, taskId string, endp func (r *AppServeAppRepository) GetTaskCountById(appId string) (int64, error) { var count int64 - if err := r.db.Model(&domain.AppServeAppTask{}).Where("AppServeAppId = ?", appId).Count(&count); err != nil { + if err := r.db.Model(&model.AppServeAppTask{}).Where("AppServeAppId = ?", appId).Count(&count); err != nil { return 0, fmt.Errorf("could not select count AppServeAppTask with ID: %s", appId) } return count, nil diff --git a/internal/repository/audit.go b/internal/repository/audit.go index bbee184c..f7e0c5dd 100644 --- a/internal/repository/audit.go +++ b/internal/repository/audit.go @@ -7,17 +7,15 @@ import ( "gorm.io/gorm" "gorm.io/gorm/clause" + "github.com/openinfradev/tks-api/internal/model" "github.com/openinfradev/tks-api/internal/pagination" - "github.com/openinfradev/tks-api/internal/serializer" - "github.com/openinfradev/tks-api/pkg/domain" - "github.com/openinfradev/tks-api/pkg/log" ) // Interfaces type IAuditRepository interface { - Get(auditId uuid.UUID) (domain.Audit, error) - Fetch(organizationId string, pg *pagination.Pagination) ([]domain.Audit, error) - Create(dto domain.Audit) (auditId uuid.UUID, err error) + Get(auditId uuid.UUID) (model.Audit, error) + Fetch(pg *pagination.Pagination) ([]model.Audit, error) + Create(dto model.Audit) (auditId uuid.UUID, err error) Delete(auditId uuid.UUID) (err error) } @@ -31,59 +29,30 @@ func NewAuditRepository(db *gorm.DB) IAuditRepository { } } -// Models -type Audit struct { - gorm.Model - - ID uuid.UUID `gorm:"primarykey"` - OrganizationId string - Organization domain.Organization `gorm:"foreignKey:OrganizationId"` - Group string - Message string - Description string - ClientIP string - UserId *uuid.UUID `gorm:"type:uuid"` - User domain.User `gorm:"foreignKey:UserId"` -} - -func (c *Audit) BeforeCreate(tx *gorm.DB) (err error) { - c.ID = uuid.New() - return nil -} - // Logics -func (r *AuditRepository) Get(auditId uuid.UUID) (out domain.Audit, err error) { - var audit Audit - res := r.db.Preload(clause.Associations).First(&audit, "id = ?", auditId) +func (r *AuditRepository) Get(auditId uuid.UUID) (out model.Audit, err error) { + res := r.db.Preload(clause.Associations).First(&out, "id = ?", auditId) if res.Error != nil { return } - out = reflectAudit(audit) return } -func (r *AuditRepository) Fetch(organizationId string, pg *pagination.Pagination) (out []domain.Audit, err error) { - var audits []Audit - +func (r *AuditRepository) Fetch(pg *pagination.Pagination) (out []model.Audit, err error) { if pg == nil { pg = pagination.NewPagination(nil) } - db := r.db.Model(&Audit{}).Preload(clause.Associations).Where("organization_id = ?", organizationId) - _, res := pg.Fetch(db, &audits) + db := r.db.Model(&model.Audit{}).Preload(clause.Associations) + _, res := pg.Fetch(db, &out) if res.Error != nil { return nil, res.Error } - - for _, audit := range audits { - out = append(out, reflectAudit(audit)) - } - return } -func (r *AuditRepository) Create(dto domain.Audit) (auditId uuid.UUID, err error) { - audit := Audit{ +func (r *AuditRepository) Create(dto model.Audit) (auditId uuid.UUID, err error) { + audit := model.Audit{ OrganizationId: dto.OrganizationId, Group: dto.Group, Message: dto.Message, @@ -100,13 +69,3 @@ func (r *AuditRepository) Create(dto domain.Audit) (auditId uuid.UUID, err error func (r *AuditRepository) Delete(auditId uuid.UUID) (err error) { return fmt.Errorf("to be implemented") } - -func reflectAudit(audit Audit) (out domain.Audit) { - if err := serializer.Map(audit.Model, &out); err != nil { - log.Error(err) - } - if err := serializer.Map(audit, &out); err != nil { - log.Error(err) - } - return -} diff --git a/internal/repository/cloud-account.go b/internal/repository/cloud-account.go index 5d9a7de9..08f635c8 100644 --- a/internal/repository/cloud-account.go +++ b/internal/repository/cloud-account.go @@ -7,20 +7,19 @@ import ( "gorm.io/gorm" "gorm.io/gorm/clause" + "github.com/openinfradev/tks-api/internal/model" "github.com/openinfradev/tks-api/internal/pagination" - "github.com/openinfradev/tks-api/internal/serializer" "github.com/openinfradev/tks-api/pkg/domain" - "github.com/openinfradev/tks-api/pkg/log" ) // Interfaces type ICloudAccountRepository interface { - Get(cloudAccountId uuid.UUID) (domain.CloudAccount, error) - GetByName(organizationId string, name string) (domain.CloudAccount, error) - GetByAwsAccountId(awsAccountId string) (domain.CloudAccount, error) - Fetch(organizationId string, pg *pagination.Pagination) ([]domain.CloudAccount, error) - Create(dto domain.CloudAccount) (cloudAccountId uuid.UUID, err error) - Update(dto domain.CloudAccount) (err error) + Get(cloudAccountId uuid.UUID) (model.CloudAccount, error) + GetByName(organizationId string, name string) (model.CloudAccount, error) + GetByAwsAccountId(awsAccountId string) (model.CloudAccount, error) + Fetch(organizationId string, pg *pagination.Pagination) ([]model.CloudAccount, error) + Create(dto model.CloudAccount) (cloudAccountId uuid.UUID, err error) + Update(dto model.CloudAccount) (err error) Delete(cloudAccountId uuid.UUID) (err error) InitWorkflow(cloudAccountId uuid.UUID, workflowId string, status domain.CloudAccountStatus) (err error) } @@ -35,86 +34,46 @@ func NewCloudAccountRepository(db *gorm.DB) ICloudAccountRepository { } } -// Models -type CloudAccount struct { - gorm.Model - - ID uuid.UUID `gorm:"primarykey"` - OrganizationId string - Organization domain.Organization `gorm:"foreignKey:OrganizationId"` - Name string `gorm:"index"` - Description string `gorm:"index"` - Resource string - CloudService string - WorkflowId string - Status domain.CloudAccountStatus - StatusDesc string - AwsAccountId string - CreatedIAM bool - CreatorId *uuid.UUID `gorm:"type:uuid"` - Creator domain.User `gorm:"foreignKey:CreatorId"` - UpdatorId *uuid.UUID `gorm:"type:uuid"` - Updator domain.User `gorm:"foreignKey:UpdatorId"` -} - -func (c *CloudAccount) BeforeCreate(tx *gorm.DB) (err error) { - c.ID = uuid.New() - return nil -} - // Logics -func (r *CloudAccountRepository) Get(cloudAccountId uuid.UUID) (out domain.CloudAccount, err error) { - var cloudAccount CloudAccount - res := r.db.Preload(clause.Associations).First(&cloudAccount, "id = ?", cloudAccountId) +func (r *CloudAccountRepository) Get(cloudAccountId uuid.UUID) (out model.CloudAccount, err error) { + res := r.db.Preload(clause.Associations).First(&out, "id = ?", cloudAccountId) if res.Error != nil { - return domain.CloudAccount{}, res.Error + return model.CloudAccount{}, res.Error } - out = reflectCloudAccount(cloudAccount) return } -func (r *CloudAccountRepository) GetByName(organizationId string, name string) (out domain.CloudAccount, err error) { - var cloudAccount CloudAccount - res := r.db.Preload(clause.Associations).First(&cloudAccount, "organization_id = ? AND name = ?", organizationId, name) - +func (r *CloudAccountRepository) GetByName(organizationId string, name string) (out model.CloudAccount, err error) { + res := r.db.Preload(clause.Associations).First(&out, "organization_id = ? AND name = ?", organizationId, name) if res.Error != nil { - return domain.CloudAccount{}, res.Error + return model.CloudAccount{}, res.Error } - out = reflectCloudAccount(cloudAccount) return } -func (r *CloudAccountRepository) GetByAwsAccountId(awsAccountId string) (out domain.CloudAccount, err error) { - var cloudAccount CloudAccount - res := r.db.Preload(clause.Associations).First(&cloudAccount, "aws_account_id = ? AND status != ?", awsAccountId, domain.CloudAccountStatus_DELETED) - +func (r *CloudAccountRepository) GetByAwsAccountId(awsAccountId string) (out model.CloudAccount, err error) { + res := r.db.Preload(clause.Associations).First(&out, "aws_account_id = ? AND status != ?", awsAccountId, domain.CloudAccountStatus_DELETED) if res.Error != nil { - return domain.CloudAccount{}, res.Error + return model.CloudAccount{}, res.Error } - out = reflectCloudAccount(cloudAccount) return } -func (r *CloudAccountRepository) Fetch(organizationId string, pg *pagination.Pagination) (out []domain.CloudAccount, err error) { - var cloudAccounts []CloudAccount +func (r *CloudAccountRepository) Fetch(organizationId string, pg *pagination.Pagination) (out []model.CloudAccount, err error) { if pg == nil { pg = pagination.NewPagination(nil) } - _, res := pg.Fetch(r.db.Model(&CloudAccount{}). + _, res := pg.Fetch(r.db.Model(&model.CloudAccount{}). Preload(clause.Associations). - Where("organization_id = ? AND status != ?", organizationId, domain.CloudAccountStatus_DELETED), &cloudAccounts) + Where("organization_id = ? AND status != ?", organizationId, domain.CloudAccountStatus_DELETED), &out) if res.Error != nil { return nil, res.Error } - - for _, cloudAccount := range cloudAccounts { - out = append(out, reflectCloudAccount(cloudAccount)) - } return } -func (r *CloudAccountRepository) Create(dto domain.CloudAccount) (cloudAccountId uuid.UUID, err error) { - cloudAccount := CloudAccount{ +func (r *CloudAccountRepository) Create(dto model.CloudAccount) (cloudAccountId uuid.UUID, err error) { + cloudAccount := model.CloudAccount{ OrganizationId: dto.OrganizationId, Name: dto.Name, Description: dto.Description, @@ -123,7 +82,7 @@ func (r *CloudAccountRepository) Create(dto domain.CloudAccount) (cloudAccountId AwsAccountId: dto.AwsAccountId, CreatedIAM: false, Status: domain.CloudAccountStatus_PENDING, - CreatorId: &dto.CreatorId} + CreatorId: dto.CreatorId} res := r.db.Create(&cloudAccount) if res.Error != nil { return uuid.Nil, res.Error @@ -131,8 +90,8 @@ func (r *CloudAccountRepository) Create(dto domain.CloudAccount) (cloudAccountId return cloudAccount.ID, nil } -func (r *CloudAccountRepository) Update(dto domain.CloudAccount) (err error) { - res := r.db.Model(&CloudAccount{}). +func (r *CloudAccountRepository) Update(dto model.CloudAccount) (err error) { + res := r.db.Model(&model.CloudAccount{}). Where("id = ?", dto.ID). Updates(map[string]interface{}{"Description": dto.Description, "Resource": dto.Resource, "UpdatorId": dto.UpdatorId}) if res.Error != nil { @@ -142,7 +101,7 @@ func (r *CloudAccountRepository) Update(dto domain.CloudAccount) (err error) { } func (r *CloudAccountRepository) Delete(cloudAccountId uuid.UUID) (err error) { - res := r.db.Delete(&CloudAccount{}, "id = ?", cloudAccountId) + res := r.db.Delete(&model.CloudAccount{}, "id = ?", cloudAccountId) if res.Error != nil { return res.Error } @@ -150,7 +109,7 @@ func (r *CloudAccountRepository) Delete(cloudAccountId uuid.UUID) (err error) { } func (r *CloudAccountRepository) InitWorkflow(cloudAccountId uuid.UUID, workflowId string, status domain.CloudAccountStatus) error { - res := r.db.Model(&CloudAccount{}). + res := r.db.Model(&model.CloudAccount{}). Where("ID = ?", cloudAccountId). Updates(map[string]interface{}{"Status": status, "WorkflowId": workflowId}) @@ -160,13 +119,3 @@ func (r *CloudAccountRepository) InitWorkflow(cloudAccountId uuid.UUID, workflow return nil } - -func reflectCloudAccount(cloudAccount CloudAccount) (out domain.CloudAccount) { - if err := serializer.Map(cloudAccount.Model, &out); err != nil { - log.Error(err) - } - if err := serializer.Map(cloudAccount, &out); err != nil { - log.Error(err) - } - return -} diff --git a/internal/repository/cluster.go b/internal/repository/cluster.go index e637c040..05d2cb00 100644 --- a/internal/repository/cluster.go +++ b/internal/repository/cluster.go @@ -8,8 +8,8 @@ import ( "gorm.io/gorm/clause" "github.com/openinfradev/tks-api/internal/helper" + "github.com/openinfradev/tks-api/internal/model" "github.com/openinfradev/tks-api/internal/pagination" - "github.com/openinfradev/tks-api/internal/serializer" "github.com/openinfradev/tks-api/pkg/domain" "github.com/openinfradev/tks-api/pkg/log" ) @@ -17,13 +17,13 @@ import ( // Interfaces type IClusterRepository interface { WithTrx(*gorm.DB) IClusterRepository - Fetch(pg *pagination.Pagination) (res []domain.Cluster, err error) - FetchByCloudAccountId(cloudAccountId uuid.UUID, pg *pagination.Pagination) (res []domain.Cluster, err error) - FetchByOrganizationId(organizationId string, userId uuid.UUID, pg *pagination.Pagination) (res []domain.Cluster, err error) - Get(id domain.ClusterId) (domain.Cluster, error) - GetByName(organizationId string, name string) (domain.Cluster, error) - Create(dto domain.Cluster) (clusterId domain.ClusterId, err error) - Update(dto domain.Cluster) (err error) + Fetch(pg *pagination.Pagination) (res []model.Cluster, err error) + FetchByCloudAccountId(cloudAccountId uuid.UUID, pg *pagination.Pagination) (res []model.Cluster, err error) + FetchByOrganizationId(organizationId string, userId uuid.UUID, pg *pagination.Pagination) (res []model.Cluster, err error) + Get(id domain.ClusterId) (model.Cluster, error) + GetByName(organizationId string, name string) (model.Cluster, error) + Create(dto model.Cluster) (clusterId domain.ClusterId, err error) + Update(dto model.Cluster) (err error) Delete(id domain.ClusterId) error InitWorkflow(clusterId domain.ClusterId, workflowId string, status domain.ClusterStatus) error @@ -45,58 +45,6 @@ func NewClusterRepository(db *gorm.DB) IClusterRepository { } } -// Models -type Cluster struct { - gorm.Model - - ID domain.ClusterId `gorm:"primarykey"` - Name string `gorm:"index"` - CloudService string `gorm:"default:AWS"` - OrganizationId string - Organization domain.Organization `gorm:"foreignKey:OrganizationId"` - Description string `gorm:"index"` - WorkflowId string - Status domain.ClusterStatus - StatusDesc string - CloudAccountId *uuid.UUID - CloudAccount CloudAccount `gorm:"foreignKey:CloudAccountId"` - StackTemplateId uuid.UUID - StackTemplate StackTemplate `gorm:"foreignKey:StackTemplateId"` - Favorites *[]ClusterFavorite - ClusterType domain.ClusterType `gorm:"default:0"` - ByoClusterEndpointHost string - ByoClusterEndpointPort int - IsStack bool `gorm:"default:false"` - TksCpNode int - TksCpNodeMax int - TksCpNodeType string - TksInfraNode int - TksInfraNodeMax int - TksInfraNodeType string - TksUserNode int - TksUserNodeMax int - TksUserNodeType string - CreatorId *uuid.UUID `gorm:"type:uuid"` - Creator domain.User `gorm:"foreignKey:CreatorId"` - UpdatorId *uuid.UUID `gorm:"type:uuid"` - Updator domain.User `gorm:"foreignKey:UpdatorId"` -} - -type ClusterFavorite struct { - gorm.Model - - ID uuid.UUID `gorm:"primarykey;type:uuid"` - ClusterId domain.ClusterId - Cluster Cluster `gorm:"foreignKey:ClusterId"` - UserId uuid.UUID `gorm:"type:uuid"` - User domain.User `gorm:"foreignKey:UserId"` -} - -func (c *ClusterFavorite) BeforeCreate(tx *gorm.DB) (err error) { - c.ID = uuid.New() - return nil -} - // Logics func (r *ClusterRepository) WithTrx(trxHandle *gorm.DB) IClusterRepository { if trxHandle == nil { @@ -107,91 +55,70 @@ func (r *ClusterRepository) WithTrx(trxHandle *gorm.DB) IClusterRepository { return r } -func (r *ClusterRepository) Fetch(pg *pagination.Pagination) (out []domain.Cluster, err error) { - var clusters []Cluster +func (r *ClusterRepository) Fetch(pg *pagination.Pagination) (out []model.Cluster, err error) { if pg == nil { pg = pagination.NewPagination(nil) } - _, res := pg.Fetch(r.db, &clusters) + _, res := pg.Fetch(r.db.Model(&model.Cluster{}).Preload(clause.Associations), &out) if res.Error != nil { return nil, res.Error } - for _, cluster := range clusters { - outCluster := reflectCluster(cluster) - out = append(out, outCluster) - } return } -func (r *ClusterRepository) FetchByOrganizationId(organizationId string, userId uuid.UUID, pg *pagination.Pagination) (out []domain.Cluster, err error) { - var clusters []Cluster +func (r *ClusterRepository) FetchByOrganizationId(organizationId string, userId uuid.UUID, pg *pagination.Pagination) (out []model.Cluster, err error) { if pg == nil { pg = pagination.NewPagination(nil) } - _, res := pg.Fetch(r.db.Model(&Cluster{}). + _, res := pg.Fetch(r.db.Model(&model.Cluster{}). Preload(clause.Associations). Joins("left outer join cluster_favorites on clusters.id = cluster_favorites.cluster_id AND cluster_favorites.user_id = ?", userId). Where("organization_id = ? AND status != ?", organizationId, domain.ClusterStatus_DELETED). - Order("cluster_favorites.cluster_id"), &clusters) - + Order("cluster_favorites.cluster_id"), &out) if res.Error != nil { return nil, res.Error } - for _, cluster := range clusters { - outCluster := reflectCluster(cluster) - out = append(out, outCluster) - } - return } -func (r *ClusterRepository) FetchByCloudAccountId(cloudAccountId uuid.UUID, pg *pagination.Pagination) (out []domain.Cluster, err error) { - var clusters []Cluster +func (r *ClusterRepository) FetchByCloudAccountId(cloudAccountId uuid.UUID, pg *pagination.Pagination) (out []model.Cluster, err error) { if pg == nil { pg = pagination.NewPagination(nil) } - _, res := pg.Fetch(r.db.Model(&Cluster{}).Preload("CloudAccount"). - Where("cloud_account_id = ?", cloudAccountId), &clusters) + _, res := pg.Fetch(r.db.Model(&model.Cluster{}).Preload("CloudAccount"). + Where("cloud_account_id = ?", cloudAccountId), &out) if res.Error != nil { return nil, res.Error } - for _, cluster := range clusters { - outCluster := reflectCluster(cluster) - out = append(out, outCluster) - } return } -func (r *ClusterRepository) Get(id domain.ClusterId) (out domain.Cluster, err error) { - var cluster Cluster - res := r.db.Preload(clause.Associations).First(&cluster, "id = ?", id) +func (r *ClusterRepository) Get(id domain.ClusterId) (out model.Cluster, err error) { + res := r.db.Preload(clause.Associations).First(&out, "id = ?", id) if res.Error != nil { - return domain.Cluster{}, res.Error + return model.Cluster{}, res.Error } - out = reflectCluster(cluster) return } -func (r *ClusterRepository) GetByName(organizationId string, name string) (out domain.Cluster, err error) { - var cluster Cluster - res := r.db.Preload(clause.Associations).First(&cluster, "organization_id = ? AND name = ?", organizationId, name) +func (r *ClusterRepository) GetByName(organizationId string, name string) (out model.Cluster, err error) { + res := r.db.Preload(clause.Associations).First(&out, "organization_id = ? AND name = ?", organizationId, name) if res.Error != nil { - return domain.Cluster{}, res.Error + return model.Cluster{}, res.Error } - out = reflectCluster(cluster) return } -func (r *ClusterRepository) Create(dto domain.Cluster) (clusterId domain.ClusterId, err error) { +func (r *ClusterRepository) Create(dto model.Cluster) (clusterId domain.ClusterId, err error) { var cloudAccountId *uuid.UUID - cloudAccountId = &dto.CloudAccountId - if dto.CloudService == domain.CloudService_BYOH || dto.CloudAccountId == uuid.Nil { + cloudAccountId = dto.CloudAccountId + if dto.CloudService == domain.CloudService_BYOH || *dto.CloudAccountId == uuid.Nil { cloudAccountId = nil } - cluster := Cluster{ + cluster := model.Cluster{ ID: domain.ClusterId(helper.GenerateClusterId()), OrganizationId: dto.OrganizationId, Name: dto.Name, @@ -206,15 +133,15 @@ func (r *ClusterRepository) Create(dto domain.Cluster) (clusterId domain.Cluster ByoClusterEndpointHost: dto.ByoClusterEndpointHost, ByoClusterEndpointPort: dto.ByoClusterEndpointPort, IsStack: dto.IsStack, - TksCpNode: dto.Conf.TksCpNode, - TksCpNodeMax: dto.Conf.TksCpNodeMax, - TksCpNodeType: dto.Conf.TksCpNodeType, - TksInfraNode: dto.Conf.TksInfraNode, - TksInfraNodeMax: dto.Conf.TksInfraNodeMax, - TksInfraNodeType: dto.Conf.TksInfraNodeType, - TksUserNode: dto.Conf.TksUserNode, - TksUserNodeMax: dto.Conf.TksUserNodeMax, - TksUserNodeType: dto.Conf.TksUserNodeType, + TksCpNode: dto.TksCpNode, + TksCpNodeMax: dto.TksCpNodeMax, + TksCpNodeType: dto.TksCpNodeType, + TksInfraNode: dto.TksInfraNode, + TksInfraNodeMax: dto.TksInfraNodeMax, + TksInfraNodeType: dto.TksInfraNodeType, + TksUserNode: dto.TksUserNode, + TksUserNodeMax: dto.TksUserNodeMax, + TksUserNodeType: dto.TksUserNodeType, } if dto.ID != "" { cluster.ID = dto.ID @@ -230,15 +157,15 @@ func (r *ClusterRepository) Create(dto domain.Cluster) (clusterId domain.Cluster } func (r *ClusterRepository) Delete(clusterId domain.ClusterId) error { - res := r.db.Unscoped().Delete(&Cluster{}, "id = ?", clusterId) + res := r.db.Unscoped().Delete(&model.Cluster{}, "id = ?", clusterId) if res.Error != nil { return fmt.Errorf("could not delete cluster for clusterId %s", clusterId) } return nil } -func (r *ClusterRepository) Update(dto domain.Cluster) error { - res := r.db.Model(&Cluster{}). +func (r *ClusterRepository) Update(dto model.Cluster) error { + res := r.db.Model(&model.Cluster{}). Where("id = ?", dto.ID). Updates(map[string]interface{}{"Description": dto.Description, "UpdatorId": dto.UpdatorId}) if res.Error != nil { @@ -248,7 +175,7 @@ func (r *ClusterRepository) Update(dto domain.Cluster) error { } func (r *ClusterRepository) InitWorkflow(clusterId domain.ClusterId, workflowId string, status domain.ClusterStatus) error { - res := r.db.Model(&Cluster{}). + res := r.db.Model(&model.Cluster{}). Where("ID = ?", clusterId). Updates(map[string]interface{}{"Status": status, "WorkflowId": workflowId, "StatusDesc": ""}) @@ -260,7 +187,7 @@ func (r *ClusterRepository) InitWorkflow(clusterId domain.ClusterId, workflowId } func (r *ClusterRepository) InitWorkflowDescription(clusterId domain.ClusterId) error { - res := r.db.Model(&AppGroup{}). + res := r.db.Model(&model.AppGroup{}). Where("id = ?", clusterId). Updates(map[string]interface{}{"WorkflowId": "", "StatusDesc": ""}) @@ -272,7 +199,7 @@ func (r *ClusterRepository) InitWorkflowDescription(clusterId domain.ClusterId) } func (r *ClusterRepository) SetFavorite(clusterId domain.ClusterId, userId uuid.UUID) error { - var clusterFavorites []ClusterFavorite + var clusterFavorites []model.ClusterFavorite res := r.db.Where("cluster_id = ? AND user_id = ?", clusterId, userId).Find(&clusterFavorites) if res.Error != nil { log.Info(res.Error) @@ -283,7 +210,7 @@ func (r *ClusterRepository) SetFavorite(clusterId domain.ClusterId, userId uuid. return nil } - clusterFavorite := ClusterFavorite{ + clusterFavorite := model.ClusterFavorite{ ClusterId: clusterId, UserId: userId, } @@ -297,34 +224,10 @@ func (r *ClusterRepository) SetFavorite(clusterId domain.ClusterId, userId uuid. } func (r *ClusterRepository) DeleteFavorite(clusterId domain.ClusterId, userId uuid.UUID) error { - res := r.db.Unscoped().Delete(&ClusterFavorite{}, "cluster_id = ? AND user_id = ?", clusterId, userId) + res := r.db.Unscoped().Delete(&model.ClusterFavorite{}, "cluster_id = ? AND user_id = ?", clusterId, userId) if res.Error != nil { log.Error(res.Error) return fmt.Errorf("could not delete cluster favorite for clusterId %s, userId %s", clusterId, userId) } return nil } - -func reflectCluster(cluster Cluster) (out domain.Cluster) { - if err := serializer.Map(cluster.Model, &out); err != nil { - log.Error(err) - } - - if err := serializer.Map(cluster, &out); err != nil { - log.Error(err) - } - - if err := serializer.Map(cluster, &out.Conf); err != nil { - log.Error(err) - } - out.StackTemplate.Services = cluster.StackTemplate.Services - - if cluster.Favorites != nil && len(*cluster.Favorites) > 0 { - out.Favorited = true - - } else { - out.Favorited = false - } - - return -} diff --git a/internal/repository/endpoint.go b/internal/repository/endpoint.go index 707d8d58..2b290779 100644 --- a/internal/repository/endpoint.go +++ b/internal/repository/endpoint.go @@ -2,16 +2,17 @@ package repository import ( "fmt" + "math" + + "github.com/openinfradev/tks-api/internal/model" "github.com/openinfradev/tks-api/internal/pagination" - "github.com/openinfradev/tks-api/pkg/domain" "gorm.io/gorm" - "math" ) type IEndpointRepository interface { - Create(endpoint *domain.Endpoint) error - List(pg *pagination.Pagination) ([]*domain.Endpoint, error) - Get(id uint) (*domain.Endpoint, error) + Create(endpoint *model.Endpoint) error + List(pg *pagination.Pagination) ([]*model.Endpoint, error) + Get(id uint) (*model.Endpoint, error) } type EndpointRepository struct { @@ -24,8 +25,8 @@ func NewEndpointRepository(db *gorm.DB) *EndpointRepository { } } -func (e *EndpointRepository) Create(endpoint *domain.Endpoint) error { - obj := &domain.Endpoint{ +func (e *EndpointRepository) Create(endpoint *model.Endpoint) error { + obj := &model.Endpoint{ Name: endpoint.Name, Group: endpoint.Group, } @@ -37,14 +38,14 @@ func (e *EndpointRepository) Create(endpoint *domain.Endpoint) error { return nil } -func (e *EndpointRepository) List(pg *pagination.Pagination) ([]*domain.Endpoint, error) { - var endpoints []*domain.Endpoint +func (e *EndpointRepository) List(pg *pagination.Pagination) ([]*model.Endpoint, error) { + var endpoints []*model.Endpoint if pg == nil { pg = pagination.NewPagination(nil) } filterFunc := CombinedGormFilter("endpoints", pg.GetFilters(), pg.CombinedFilter) - db := filterFunc(e.db.Model(&domain.Endpoint{})) + db := filterFunc(e.db.Model(&model.Endpoint{})) db.Count(&pg.TotalRows) pg.TotalPages = int(math.Ceil(float64(pg.TotalRows) / float64(pg.Limit))) @@ -58,14 +59,14 @@ func (e *EndpointRepository) List(pg *pagination.Pagination) ([]*domain.Endpoint return endpoints, nil } -func (e *EndpointRepository) Get(id uint) (*domain.Endpoint, error) { - var obj domain.Endpoint +func (e *EndpointRepository) Get(id uint) (*model.Endpoint, error) { + var obj model.Endpoint if err := e.db.Preload("Permission").First(&obj, "id = ?", id).Error; err != nil { return nil, err } - return &domain.Endpoint{ + return &model.Endpoint{ Name: obj.Name, Group: obj.Group, }, nil diff --git a/internal/repository/organization.go b/internal/repository/organization.go index a7839166..69ed3cce 100644 --- a/internal/repository/organization.go +++ b/internal/repository/organization.go @@ -2,8 +2,8 @@ package repository import ( "github.com/google/uuid" + "github.com/openinfradev/tks-api/internal/model" "github.com/openinfradev/tks-api/internal/pagination" - "github.com/openinfradev/tks-api/internal/serializer" "github.com/openinfradev/tks-api/pkg/domain" "github.com/openinfradev/tks-api/pkg/log" "gorm.io/gorm" @@ -11,10 +11,10 @@ import ( // Interfaces type IOrganizationRepository interface { - Create(organizationId string, name string, creator uuid.UUID, phone string, description string) (domain.Organization, error) - Fetch(pg *pagination.Pagination) (res *[]domain.Organization, err error) - Get(organizationId string) (res domain.Organization, err error) - Update(organizationId string, in domain.UpdateOrganizationRequest) (domain.Organization, error) + Create(organizationId string, name string, creator uuid.UUID, phone string, description string) (model.Organization, error) + Fetch(pg *pagination.Pagination) (res *[]model.Organization, err error) + Get(organizationId string) (res model.Organization, err error) + Update(organizationId string, in domain.UpdateOrganizationRequest) (model.Organization, error) UpdatePrimaryClusterId(organizationId string, primaryClusterId string) error Delete(organizationId string) (err error) InitWorkflow(organizationId string, workflowId string, status domain.OrganizationStatus) error @@ -40,7 +40,7 @@ func NewOrganizationRepository(db *gorm.DB) IOrganizationRepository { // Description string // Phone string // WorkflowId string -// Status domain.OrganizationStatus +// Status model.OrganizationStatus // StatusDesc string // Creator uuid.UUID // PrimaryClusterId string // allow null @@ -52,8 +52,8 @@ func NewOrganizationRepository(db *gorm.DB) IOrganizationRepository { //} func (r *OrganizationRepository) Create(organizationId string, name string, creator uuid.UUID, phone string, - description string) (domain.Organization, error) { - organization := domain.Organization{ + description string) (model.Organization, error) { + organization := model.Organization{ ID: organizationId, Name: name, Creator: creator.String(), @@ -64,45 +64,36 @@ func (r *OrganizationRepository) Create(organizationId string, name string, crea res := r.db.Create(&organization) if res.Error != nil { log.Errorf("error is :%s(%T)", res.Error.Error(), res.Error) - return domain.Organization{}, res.Error + return model.Organization{}, res.Error } - return r.reflect(organization), nil + return organization, nil } -func (r *OrganizationRepository) Fetch(pg *pagination.Pagination) (*[]domain.Organization, error) { - var organizations []domain.Organization - var out []domain.Organization +func (r *OrganizationRepository) Fetch(pg *pagination.Pagination) (out *[]model.Organization, err error) { if pg == nil { pg = pagination.NewPagination(nil) } - _, res := pg.Fetch(r.db, &organizations) + _, res := pg.Fetch(r.db, &out) if res.Error != nil { return nil, res.Error } - - for _, organization := range organizations { - outOrganization := r.reflect(organization) - out = append(out, outOrganization) - } - return &out, nil + return } -func (r *OrganizationRepository) Get(id string) (domain.Organization, error) { - var organization domain.Organization - res := r.db.First(&organization, "id = ?", id) +func (r *OrganizationRepository) Get(id string) (out model.Organization, err error) { + res := r.db.First(&out, "id = ?", id) if res.Error != nil { log.Errorf("error is :%s(%T)", res.Error.Error(), res.Error) - return domain.Organization{}, res.Error + return model.Organization{}, res.Error } - return r.reflect(organization), nil + return } -func (r *OrganizationRepository) Update(organizationId string, in domain.UpdateOrganizationRequest) (domain.Organization, error) { - var organization domain.Organization - res := r.db.Model(&domain.Organization{}). +func (r *OrganizationRepository) Update(organizationId string, in domain.UpdateOrganizationRequest) (out model.Organization, err error) { + res := r.db.Model(&model.Organization{}). Where("id = ?", organizationId). Updates(map[string]interface{}{ "name": in.Name, @@ -112,19 +103,19 @@ func (r *OrganizationRepository) Update(organizationId string, in domain.UpdateO if res.Error != nil { log.Errorf("error is :%s(%T)", res.Error.Error(), res.Error) - return domain.Organization{}, res.Error + return model.Organization{}, res.Error } - res = r.db.Model(&domain.Organization{}).Where("id = ?", organizationId).Find(&organization) + res = r.db.Model(&model.Organization{}).Where("id = ?", organizationId).Find(&out) if res.Error != nil { log.Errorf("error is :%s(%T)", res.Error.Error(), res.Error) - return domain.Organization{}, res.Error + return model.Organization{}, res.Error } - return r.reflect(organization), nil + return } func (r *OrganizationRepository) UpdatePrimaryClusterId(organizationId string, primaryClusterId string) error { - res := r.db.Model(&domain.Organization{}). + res := r.db.Model(&model.Organization{}). Where("id = ?", organizationId). Updates(map[string]interface{}{ "primary_cluster_id": primaryClusterId, @@ -138,7 +129,7 @@ func (r *OrganizationRepository) UpdatePrimaryClusterId(organizationId string, p } func (r *OrganizationRepository) Delete(organizationId string) error { - res := r.db.Delete(&domain.Organization{}, "id = ?", organizationId) + res := r.db.Delete(&model.Organization{}, "id = ?", organizationId) if res.Error != nil { log.Errorf("error is :%s(%T)", res.Error.Error(), res.Error) return res.Error @@ -148,7 +139,7 @@ func (r *OrganizationRepository) Delete(organizationId string) error { } func (r *OrganizationRepository) InitWorkflow(organizationId string, workflowId string, status domain.OrganizationStatus) error { - res := r.db.Model(&domain.Organization{}). + res := r.db.Model(&model.Organization{}). Where("ID = ?", organizationId). Updates(map[string]interface{}{"Status": status, "WorkflowId": workflowId}) if res.Error != nil { @@ -157,15 +148,3 @@ func (r *OrganizationRepository) InitWorkflow(organizationId string, workflowId } return nil } - -func (r *OrganizationRepository) reflect(organization domain.Organization) (out domain.Organization) { - if err := serializer.Map(organization.Model, &out); err != nil { - log.Error(err) - } - if err := serializer.Map(organization, &out); err != nil { - log.Error(err) - } - out.Creator = organization.Creator - return - -} diff --git a/internal/repository/permission.go b/internal/repository/permission.go index db097922..ebed52e6 100644 --- a/internal/repository/permission.go +++ b/internal/repository/permission.go @@ -2,16 +2,16 @@ package repository import ( "github.com/google/uuid" - "github.com/openinfradev/tks-api/pkg/domain" + "github.com/openinfradev/tks-api/internal/model" "gorm.io/gorm" ) type IPermissionRepository interface { - Create(permission *domain.Permission) error - List(roleId string) ([]*domain.Permission, error) - Get(id uuid.UUID) (*domain.Permission, error) + Create(permission *model.Permission) error + List(roleId string) ([]*model.Permission, error) + Get(id uuid.UUID) (*model.Permission, error) Delete(id uuid.UUID) error - Update(permission *domain.Permission) error + Update(permission *model.Permission) error } type PermissionRepository struct { @@ -24,7 +24,7 @@ func NewPermissionRepository(db *gorm.DB) *PermissionRepository { } } -func (r PermissionRepository) Create(p *domain.Permission) error { +func (r PermissionRepository) Create(p *model.Permission) error { //var parent *Permission //var children []*Permission // @@ -49,8 +49,8 @@ func (r PermissionRepository) Create(p *domain.Permission) error { return r.db.Create(p).Error } -func (r PermissionRepository) List(roleId string) ([]*domain.Permission, error) { - var permissions []*domain.Permission +func (r PermissionRepository) List(roleId string) ([]*model.Permission, error) { + var permissions []*model.Permission err := r.db.Preload("Children.Children.Children.Children").Where("parent_id IS NULL AND role_id = ?", roleId).Find(&permissions).Error if err != nil { @@ -60,8 +60,8 @@ func (r PermissionRepository) List(roleId string) ([]*domain.Permission, error) return permissions, nil } -func (r PermissionRepository) Get(id uuid.UUID) (*domain.Permission, error) { - permission := &domain.Permission{} +func (r PermissionRepository) Get(id uuid.UUID) (*model.Permission, error) { + permission := &model.Permission{} result := r.db.Preload("Children.Children.Children").Preload("Parent").First(&permission, "id = ?", id) if result.Error != nil { return nil, result.Error @@ -71,10 +71,10 @@ func (r PermissionRepository) Get(id uuid.UUID) (*domain.Permission, error) { } func (r PermissionRepository) Delete(id uuid.UUID) error { - return r.db.Delete(&domain.Permission{}, "id = ?", id).Error + return r.db.Delete(&model.Permission{}, "id = ?", id).Error } -func (r PermissionRepository) Update(p *domain.Permission) error { +func (r PermissionRepository) Update(p *model.Permission) error { // update on is_allowed - return r.db.Model(&domain.Permission{}).Where("id = ?", p.ID).Updates(map[string]interface{}{"is_allowed": p.IsAllowed}).Error + return r.db.Model(&model.Permission{}).Where("id = ?", p.ID).Updates(map[string]interface{}{"is_allowed": p.IsAllowed}).Error } diff --git a/internal/repository/policy-template.go b/internal/repository/policy-template.go index bc12f8fe..7500369b 100644 --- a/internal/repository/policy-template.go +++ b/internal/repository/policy-template.go @@ -6,6 +6,7 @@ import ( "strings" "github.com/google/uuid" + "github.com/openinfradev/tks-api/internal/model" "github.com/openinfradev/tks-api/internal/pagination" "github.com/openinfradev/tks-api/internal/serializer" "github.com/openinfradev/tks-api/pkg/domain" @@ -16,18 +17,18 @@ import ( ) type IPolicyTemplateRepository interface { - Create(dto domain.PolicyTemplate) (policyTemplateId uuid.UUID, err error) + Create(dto model.PolicyTemplate) (policyTemplateId uuid.UUID, err error) Update(dto domain.UpdatePolicyTemplateUpdate) (err error) - Fetch(pg *pagination.Pagination) (out []domain.PolicyTemplate, err error) - GetByName(policyTemplateName string) (out *domain.PolicyTemplate, err error) - GetByKind(policyTemplateKind string) (out *domain.PolicyTemplate, err error) - GetByID(policyTemplateId uuid.UUID) (out *domain.PolicyTemplate, err error) + Fetch(pg *pagination.Pagination) (out []model.PolicyTemplate, err error) + GetByName(policyTemplateName string) (out *model.PolicyTemplate, err error) + GetByKind(policyTemplateKind string) (out *model.PolicyTemplate, err error) + GetByID(policyTemplateId uuid.UUID) (out *model.PolicyTemplate, err error) Delete(policyTemplateId uuid.UUID) (err error) ExistByName(policyTemplateName string) (exist bool, err error) ExistByKind(policyTemplateKind string) (exist bool, err error) ExistByID(policyTemplateId uuid.UUID) (exist bool, err error) ListPolicyTemplateVersions(policyTemplateId uuid.UUID) (policyTemplateVersionsReponse *domain.ListPolicyTemplateVersionsResponse, err error) - GetPolicyTemplateVersion(policyTemplateId uuid.UUID, version string) (policyTemplateVersionsReponse *domain.PolicyTemplate, err error) + GetPolicyTemplateVersion(policyTemplateId uuid.UUID, version string) (policyTemplateVersionsReponse *model.PolicyTemplate, err error) DeletePolicyTemplateVersion(policyTemplateId uuid.UUID, version string) (err error) CreatePolicyTemplateVersion(policyTemplateId uuid.UUID, newVersion string, schema []domain.ParameterDef, rego string, libs []string) (version string, err error) } @@ -42,54 +43,18 @@ func NewPolicyTemplateRepository(db *gorm.DB) IPolicyTemplateRepository { } } -type PolicyTemplateSupportedVersion struct { - gorm.Model - - PolicyTemplateId uuid.UUID `gorm:"index:template_version,unique"` - Version string `gorm:"index:template_version,unique"` - - ParameterSchema string `gorm:"type:text"` - Rego string `gorm:"type:text"` - Libs string `gorm:"type:text"` -} - -type PolicyTemplate struct { - gorm.Model - - ID uuid.UUID `gorm:"primarykey;type:varchar(36);not null"` - Type string // Org or Tks - Name string - Version string - SupportedVersions []PolicyTemplateSupportedVersion `gorm:"foreignKey:PolicyTemplateId"` - Description string - Kind string - Deprecated bool - Mandatory bool // Tks 인 경우에는 무시 - Severity string - PermittedOrganizations []domain.Organization `gorm:"many2many:policy_template_permitted_organiations;"` - CreatorId *uuid.UUID `gorm:"type:uuid"` - Creator domain.User `gorm:"foreignKey:CreatorId"` - UpdatorId *uuid.UUID `gorm:"type:uuid"` - Updator domain.User `gorm:"foreignKey:UpdatorId"` -} - -func (c *PolicyTemplate) BeforeCreate(tx *gorm.DB) (err error) { - c.ID = uuid.New() - return nil -} - -func (r *PolicyTemplateRepository) Create(dto domain.PolicyTemplate) (policyTemplateId uuid.UUID, err error) { +func (r *PolicyTemplateRepository) Create(dto model.PolicyTemplate) (policyTemplateId uuid.UUID, err error) { jsonByte, err := json.Marshal(dto.ParametersSchema) if err != nil { return uuid.Nil, err } - policyTemplate := PolicyTemplate{ + policyTemplate := model.PolicyTemplate{ Type: "tks", Name: dto.TemplateName, Version: "v1.0.0", - SupportedVersions: []PolicyTemplateSupportedVersion{ + SupportedVersions: []model.PolicyTemplateSupportedVersion{ { Version: "v1.0.0", ParameterSchema: string(jsonByte), @@ -111,9 +76,9 @@ func (r *PolicyTemplateRepository) Create(dto domain.PolicyTemplate) (policyTemp } if dto.PermittedOrganizationIds != nil { - permittedOrganizations := make([]domain.Organization, len(dto.PermittedOrganizationIds)) + permittedOrganizations := make([]model.Organization, len(dto.PermittedOrganizationIds)) for i, permittedOrganizationId := range dto.PermittedOrganizationIds { - permittedOrganizations[i] = domain.Organization{ID: permittedOrganizationId} + permittedOrganizations[i] = model.Organization{ID: permittedOrganizationId} } err = tx.Model(&policyTemplate).Association("PermittedOrganizations").Replace(permittedOrganizations) @@ -156,14 +121,14 @@ func (r *PolicyTemplateRepository) Update(dto domain.UpdatePolicyTemplateUpdate) fmt.Printf("--updateMap=%+v\n--", updateMap) - var policyTemplate PolicyTemplate + var policyTemplate model.PolicyTemplate policyTemplate.ID = dto.ID return r.db.Transaction(func(tx *gorm.DB) error { if dto.PermittedOrganizationIds != nil { - permittedOrganizations := make([]domain.Organization, len(*dto.PermittedOrganizationIds)) + permittedOrganizations := make([]model.Organization, len(*dto.PermittedOrganizationIds)) for i, permittedOrganizationId := range *dto.PermittedOrganizationIds { - permittedOrganizations[i] = domain.Organization{ID: permittedOrganizationId} + permittedOrganizations[i] = model.Organization{ID: permittedOrganizationId} } err = r.db.Model(&policyTemplate).Limit(1). @@ -189,20 +154,20 @@ func (r *PolicyTemplateRepository) Update(dto domain.UpdatePolicyTemplateUpdate) }) } -func (r *PolicyTemplateRepository) Fetch(pg *pagination.Pagination) (out []domain.PolicyTemplate, err error) { - var policyTemplates []PolicyTemplate +func (r *PolicyTemplateRepository) Fetch(pg *pagination.Pagination) (out []model.PolicyTemplate, err error) { + var policyTemplates []model.PolicyTemplate if pg == nil { pg = pagination.NewPagination(nil) } - _, res := pg.Fetch(r.db.Preload(clause.Associations).Model(&PolicyTemplate{}). + _, res := pg.Fetch(r.db.Preload(clause.Associations).Model(&model.PolicyTemplate{}). Where("type = 'tks'"), &policyTemplates) if res.Error != nil { return nil, res.Error } for _, policyTemplate := range policyTemplates { - var policyTemplateVersion PolicyTemplateSupportedVersion + var policyTemplateVersion model.PolicyTemplateSupportedVersion res = r.db. Where("policy_template_id = ? and version = ?", policyTemplate.ID, policyTemplate.Version). First(&policyTemplateVersion) @@ -221,7 +186,7 @@ func (r *PolicyTemplateRepository) Fetch(pg *pagination.Pagination) (out []domai return out, nil } -func (r *PolicyTemplateRepository) reflectPolicyTemplate(policyTemplate PolicyTemplate, policyTemplateVersion PolicyTemplateSupportedVersion) (out domain.PolicyTemplate) { +func (r *PolicyTemplateRepository) reflectPolicyTemplate(policyTemplate model.PolicyTemplate, policyTemplateVersion model.PolicyTemplateSupportedVersion) (out model.PolicyTemplate) { if err := serializer.Map(policyTemplate.Model, &out); err != nil { log.Error(err) } @@ -229,7 +194,7 @@ func (r *PolicyTemplateRepository) reflectPolicyTemplate(policyTemplate PolicyTe log.Error(err) } out.TemplateName = policyTemplate.Name - out.ID = domain.PolicyTemplateId(policyTemplate.ID.String()) + out.ID = policyTemplate.ID var schemas []domain.ParameterDef @@ -241,14 +206,20 @@ func (r *PolicyTemplateRepository) reflectPolicyTemplate(policyTemplate PolicyTe } } - out.PermittedOrganizations = make([]domain.PermittedOrganization, len(policyTemplate.PermittedOrganizations)) - for i, org := range policyTemplate.PermittedOrganizations { - out.PermittedOrganizations[i] = domain.PermittedOrganization{ - OrganizationId: org.ID, - OrganizationName: org.Name, - Permitted: true, + // ktkfree : 이 부분은 재 구현 부탁 드립니다. + // PermittedOrganizations 필드가 model 과 response 를 위한 객체의 형이 다르네요. + // 아울러 reflect 는 repository 가 아닌 usecase 에 표현되는게 더 좋겠습니다. + + /* + out.PermittedOrganizations = make([]domain.PermittedOrganization, len(policyTemplate.PermittedOrganizations)) + for i, org := range policyTemplate.PermittedOrganizations { + out.PermittedOrganizations[i] = domain.PermittedOrganization{ + OrganizationId: org.ID, + OrganizationName: org.Name, + Permitted: true, + } } - } + */ out.Rego = policyTemplateVersion.Rego out.Libs = strings.Split(policyTemplateVersion.Libs, "---\n") @@ -259,7 +230,7 @@ func (r *PolicyTemplateRepository) reflectPolicyTemplate(policyTemplate PolicyTe func (r *PolicyTemplateRepository) ExistsBy(key string, value interface{}) (exists bool, err error) { query := fmt.Sprintf("%s = ?", key) - var policyTemplate PolicyTemplate + var policyTemplate model.PolicyTemplate res := r.db.Where(query, value). First(&policyTemplate) @@ -288,10 +259,10 @@ func (r *PolicyTemplateRepository) ExistByID(policyTemplateId uuid.UUID) (exist return r.ExistsBy("id", policyTemplateId) } -func (r *PolicyTemplateRepository) GetBy(key string, value interface{}) (out *domain.PolicyTemplate, err error) { +func (r *PolicyTemplateRepository) GetBy(key string, value interface{}) (out *model.PolicyTemplate, err error) { query := fmt.Sprintf("%s = ?", key) - var policyTemplate PolicyTemplate + var policyTemplate model.PolicyTemplate res := r.db.Preload(clause.Associations).Where(query, value). First(&policyTemplate) @@ -305,7 +276,7 @@ func (r *PolicyTemplateRepository) GetBy(key string, value interface{}) (out *do } } - var policyTemplateVersion PolicyTemplateSupportedVersion + var policyTemplateVersion model.PolicyTemplateSupportedVersion res = r.db.Limit(1). Where("policy_template_id = ? and version = ?", policyTemplate.ID, policyTemplate.Version). First(&policyTemplateVersion) @@ -327,7 +298,7 @@ func (r *PolicyTemplateRepository) GetBy(key string, value interface{}) (out *do return &result, nil } -func (r *PolicyTemplateRepository) GetByID(policyTemplateId uuid.UUID) (out *domain.PolicyTemplate, err error) { +func (r *PolicyTemplateRepository) GetByID(policyTemplateId uuid.UUID) (out *model.PolicyTemplate, err error) { return r.GetBy("id", policyTemplateId) // var policyTemplate PolicyTemplate @@ -349,7 +320,7 @@ func (r *PolicyTemplateRepository) GetByID(policyTemplateId uuid.UUID) (out *dom // return &result, nil } -func (r *PolicyTemplateRepository) GetByName(policyTemplateName string) (out *domain.PolicyTemplate, err error) { +func (r *PolicyTemplateRepository) GetByName(policyTemplateName string) (out *model.PolicyTemplate, err error) { return r.GetBy("name", policyTemplateName) // var policyTemplate PolicyTemplate @@ -371,21 +342,21 @@ func (r *PolicyTemplateRepository) GetByName(policyTemplateName string) (out *do // return &result, nil } -func (r *PolicyTemplateRepository) GetByKind(policyTemplateKind string) (out *domain.PolicyTemplate, err error) { +func (r *PolicyTemplateRepository) GetByKind(policyTemplateKind string) (out *model.PolicyTemplate, err error) { return r.GetBy("kind", policyTemplateKind) } func (r *PolicyTemplateRepository) Delete(policyTemplateId uuid.UUID) (err error) { return r.db.Transaction(func(tx *gorm.DB) error { - if err := tx.Where("policy_template_id = ?", policyTemplateId).Delete(&PolicyTemplateSupportedVersion{}).Error; err != nil { + if err := tx.Where("policy_template_id = ?", policyTemplateId).Delete(&model.PolicyTemplateSupportedVersion{}).Error; err != nil { return err } - if err := tx.Model(&PolicyTemplate{ID: policyTemplateId}).Association("PermittedOrganizations").Clear(); err != nil { + if err := tx.Model(&model.PolicyTemplate{ID: policyTemplateId}).Association("PermittedOrganizations").Clear(); err != nil { return err } - if err := tx.Where("id = ?", policyTemplateId).Delete(&PolicyTemplate{}).Error; err != nil { + if err := tx.Where("id = ?", policyTemplateId).Delete(&model.PolicyTemplate{}).Error; err != nil { return err } @@ -394,7 +365,7 @@ func (r *PolicyTemplateRepository) Delete(policyTemplateId uuid.UUID) (err error } func (r *PolicyTemplateRepository) ListPolicyTemplateVersions(policyTemplateId uuid.UUID) (policyTemplateVersionsReponse *domain.ListPolicyTemplateVersionsResponse, err error) { - var supportedVersions []PolicyTemplateSupportedVersion + var supportedVersions []model.PolicyTemplateSupportedVersion res := r.db.Where("policy_template_id = ?", policyTemplateId).Find(&supportedVersions) if res.Error != nil { @@ -420,8 +391,8 @@ func (r *PolicyTemplateRepository) ListPolicyTemplateVersions(policyTemplateId u return result, nil } -func (r *PolicyTemplateRepository) GetPolicyTemplateVersion(policyTemplateId uuid.UUID, version string) (policyTemplateVersionsReponse *domain.PolicyTemplate, err error) { - var policyTemplateVersion PolicyTemplateSupportedVersion +func (r *PolicyTemplateRepository) GetPolicyTemplateVersion(policyTemplateId uuid.UUID, version string) (policyTemplateVersionsReponse *model.PolicyTemplate, err error) { + var policyTemplateVersion model.PolicyTemplateSupportedVersion res := r.db. Where("policy_template_id = ? and version = ?", policyTemplateId, version). First(&policyTemplateVersion) @@ -435,7 +406,7 @@ func (r *PolicyTemplateRepository) GetPolicyTemplateVersion(policyTemplateId uui } } - var policyTemplate PolicyTemplate + var policyTemplate model.PolicyTemplate res = r.db. Where("id = ?", policyTemplateId). First(&policyTemplate) @@ -455,7 +426,7 @@ func (r *PolicyTemplateRepository) GetPolicyTemplateVersion(policyTemplateId uui } func (r *PolicyTemplateRepository) DeletePolicyTemplateVersion(policyTemplateId uuid.UUID, version string) (err error) { - var policyTemplate PolicyTemplate + var policyTemplate model.PolicyTemplate res := r.db.Select("version").First(&policyTemplate) if res.Error != nil { @@ -475,7 +446,7 @@ func (r *PolicyTemplateRepository) DeletePolicyTemplateVersion(policyTemplateId // TODO: Operator에 현재 버전 사용중인 정책이 있는지 체크 필요 - var policyTemplateVersion PolicyTemplateSupportedVersion + var policyTemplateVersion model.PolicyTemplateSupportedVersion res = r.db.Where("policy_template_id = ? and version = ?", policyTemplateId, version). Delete(&policyTemplateVersion) if res.Error != nil { @@ -492,7 +463,7 @@ func (r *PolicyTemplateRepository) DeletePolicyTemplateVersion(policyTemplateId } func (r *PolicyTemplateRepository) CreatePolicyTemplateVersion(policyTemplateId uuid.UUID, newVersion string, schema []domain.ParameterDef, rego string, libs []string) (version string, err error) { - var policyTemplateVersion PolicyTemplateSupportedVersion + var policyTemplateVersion model.PolicyTemplateSupportedVersion res := r.db.Limit(1). Where("policy_template_id = ? and version = ?", policyTemplateId, version). First(&policyTemplateVersion) @@ -525,7 +496,7 @@ func (r *PolicyTemplateRepository) CreatePolicyTemplateVersion(policyTemplateId return "", parseErr } - newPolicyTemplateVersion := &PolicyTemplateSupportedVersion{ + newPolicyTemplateVersion := &model.PolicyTemplateSupportedVersion{ PolicyTemplateId: policyTemplateId, Version: newVersion, Rego: rego, @@ -538,7 +509,7 @@ func (r *PolicyTemplateRepository) CreatePolicyTemplateVersion(policyTemplateId return err } - if err := tx.Model(&PolicyTemplate{}).Where("id = ?", policyTemplateId).Update("version", newVersion).Error; err != nil { + if err := tx.Model(&model.PolicyTemplate{}).Where("id = ?", policyTemplateId).Update("version", newVersion).Error; err != nil { return err } diff --git a/internal/repository/role.go b/internal/repository/role.go index d7bdb198..ab5c7f50 100644 --- a/internal/repository/role.go +++ b/internal/repository/role.go @@ -2,29 +2,30 @@ package repository import ( "fmt" + "math" + + "github.com/openinfradev/tks-api/internal/model" "github.com/openinfradev/tks-api/internal/pagination" - "github.com/openinfradev/tks-api/pkg/domain" "gorm.io/gorm" - "math" ) type IRoleRepository interface { - Create(roleObj *domain.Role) (string, error) - List(pg *pagination.Pagination) ([]*domain.Role, error) - ListTksRoles(organizationId string, pg *pagination.Pagination) ([]*domain.Role, error) - Get(id string) (*domain.Role, error) - GetTksRole(id string) (*domain.Role, error) - GetTksRoleByRoleName(roleName string) (*domain.Role, error) + Create(roleObj *model.Role) (string, error) + List(pg *pagination.Pagination) ([]*model.Role, error) + ListTksRoles(organizationId string, pg *pagination.Pagination) ([]*model.Role, error) + Get(id string) (*model.Role, error) + GetTksRole(id string) (*model.Role, error) + GetTksRoleByRoleName(roleName string) (*model.Role, error) Delete(id string) error - Update(roleObj *domain.Role) error + Update(roleObj *model.Role) error } type RoleRepository struct { db *gorm.DB } -func (r RoleRepository) GetTksRoleByRoleName(roleName string) (*domain.Role, error) { - var role domain.Role +func (r RoleRepository) GetTksRoleByRoleName(roleName string) (*model.Role, error) { + var role model.Role if err := r.db.Preload("Role").First(&role, "Role.name = ?", roleName).Error; err != nil { return nil, err } @@ -32,7 +33,7 @@ func (r RoleRepository) GetTksRoleByRoleName(roleName string) (*domain.Role, err return &role, nil } -func (r RoleRepository) Create(roleObj *domain.Role) (string, error) { +func (r RoleRepository) Create(roleObj *model.Role) (string, error) { if roleObj == nil { return "", fmt.Errorf("roleObj is nil") } @@ -43,14 +44,14 @@ func (r RoleRepository) Create(roleObj *domain.Role) (string, error) { return roleObj.ID, nil } -func (r RoleRepository) List(pg *pagination.Pagination) ([]*domain.Role, error) { - var roles []*domain.Role +func (r RoleRepository) List(pg *pagination.Pagination) ([]*model.Role, error) { + var roles []*model.Role if pg == nil { pg = pagination.NewPagination(nil) } filterFunc := CombinedGormFilter("roles", pg.GetFilters(), pg.CombinedFilter) - db := filterFunc(r.db.Model(&domain.Role{})) + db := filterFunc(r.db.Model(&model.Role{})) db.Count(&pg.TotalRows) pg.TotalPages = int(math.Ceil(float64(pg.TotalRows) / float64(pg.Limit))) @@ -65,14 +66,14 @@ func (r RoleRepository) List(pg *pagination.Pagination) ([]*domain.Role, error) return roles, nil } -func (r RoleRepository) ListTksRoles(organizationId string, pg *pagination.Pagination) ([]*domain.Role, error) { - var roles []*domain.Role +func (r RoleRepository) ListTksRoles(organizationId string, pg *pagination.Pagination) ([]*model.Role, error) { + var roles []*model.Role if pg == nil { pg = pagination.NewPagination(nil) } filterFunc := CombinedGormFilter("roles", pg.GetFilters(), pg.CombinedFilter) - db := filterFunc(r.db.Model(&domain.Role{})) + db := filterFunc(r.db.Model(&model.Role{})) db.Count(&pg.TotalRows) pg.TotalPages = int(math.Ceil(float64(pg.TotalRows) / float64(pg.Limit))) @@ -91,8 +92,8 @@ func (r RoleRepository) ListTksRoles(organizationId string, pg *pagination.Pagin return roles, nil } -func (r RoleRepository) Get(id string) (*domain.Role, error) { - var role domain.Role +func (r RoleRepository) Get(id string) (*model.Role, error) { + var role model.Role if err := r.db.First(&role, "id = ?", id).Error; err != nil { return nil, err } @@ -100,8 +101,8 @@ func (r RoleRepository) Get(id string) (*domain.Role, error) { return &role, nil } -func (r RoleRepository) GetTksRole(id string) (*domain.Role, error) { - var role domain.Role +func (r RoleRepository) GetTksRole(id string) (*model.Role, error) { + var role model.Role if err := r.db.First(&role, "id = ?", id).Error; err != nil { return nil, err } @@ -109,12 +110,12 @@ func (r RoleRepository) GetTksRole(id string) (*domain.Role, error) { return &role, nil } -func (r RoleRepository) Update(roleObj *domain.Role) error { +func (r RoleRepository) Update(roleObj *model.Role) error { if roleObj == nil { return fmt.Errorf("roleObj is nil") } - err := r.db.Model(&domain.Role{}).Where("id = ?", roleObj.ID).Updates(domain.Role{ + err := r.db.Model(&model.Role{}).Where("id = ?", roleObj.ID).Updates(model.Role{ Name: roleObj.Name, Description: roleObj.Description, }).Error @@ -127,7 +128,7 @@ func (r RoleRepository) Update(roleObj *domain.Role) error { } func (r RoleRepository) Delete(id string) error { - if err := r.db.Delete(&domain.Role{}, "id = ?", id).Error; err != nil { + if err := r.db.Delete(&model.Role{}, "id = ?", id).Error; err != nil { return err } diff --git a/internal/repository/stack-template.go b/internal/repository/stack-template.go index 9c55df46..103aec44 100644 --- a/internal/repository/stack-template.go +++ b/internal/repository/stack-template.go @@ -2,24 +2,22 @@ package repository import ( "github.com/google/uuid" - "gorm.io/datatypes" "gorm.io/gorm" "gorm.io/gorm/clause" + "github.com/openinfradev/tks-api/internal/model" "github.com/openinfradev/tks-api/internal/pagination" - "github.com/openinfradev/tks-api/internal/serializer" - "github.com/openinfradev/tks-api/pkg/domain" - "github.com/openinfradev/tks-api/pkg/log" ) // Interfaces type IStackTemplateRepository interface { - Get(stackTemplateId uuid.UUID) (domain.StackTemplate, error) - Fetch(pg *pagination.Pagination) ([]domain.StackTemplate, error) - Create(dto domain.StackTemplate) (stackTemplateId uuid.UUID, err error) - Update(dto domain.StackTemplate) (err error) - Delete(dto domain.StackTemplate) (err error) - UpdateOrganizations(stackTemplateId uuid.UUID, organizationIds []domain.Organization) (err error) + Get(stackTemplateId uuid.UUID) (model.StackTemplate, error) + Fetch(pg *pagination.Pagination) ([]model.StackTemplate, error) + FetchWithOrganization(organizationId string, pg *pagination.Pagination) (out []model.StackTemplate, err error) + Create(dto model.StackTemplate) (stackTemplateId uuid.UUID, err error) + Update(dto model.StackTemplate) (err error) + Delete(dto model.StackTemplate) (err error) + UpdateOrganizations(stackTemplateId uuid.UUID, organizationIds []model.Organization) (err error) } type StackTemplateRepository struct { @@ -32,87 +30,52 @@ func NewStackTemplateRepository(db *gorm.DB) IStackTemplateRepository { } } -// Models -type StackTemplate struct { - gorm.Model - - ID uuid.UUID `gorm:"primarykey"` - Name string `gorm:"index"` - Description string `gorm:"index"` - Template string - TemplateType string - Version string - CloudService string - Platform string - KubeVersion string - KubeType string - Organizations []domain.Organization `gorm:"many2many:stack_template_organizations"` - Services datatypes.JSON - CreatorId *uuid.UUID `gorm:"type:uuid"` - Creator domain.User `gorm:"foreignKey:CreatorId"` - UpdatorId *uuid.UUID `gorm:"type:uuid"` - Updator domain.User `gorm:"foreignKey:UpdatorId"` -} - -func (c *StackTemplate) BeforeCreate(tx *gorm.DB) (err error) { - c.ID = uuid.New() - return nil -} - // Logics -func (r *StackTemplateRepository) Get(stackTemplateId uuid.UUID) (out domain.StackTemplate, err error) { - var stackTemplate StackTemplate - res := r.db.Preload(clause.Associations).First(&stackTemplate, "id = ?", stackTemplateId) +func (r *StackTemplateRepository) Get(stackTemplateId uuid.UUID) (out model.StackTemplate, err error) { + res := r.db.Preload(clause.Associations).First(&out, "id = ?", stackTemplateId) if res.Error != nil { - return domain.StackTemplate{}, res.Error + return model.StackTemplate{}, res.Error } - out = reflectStackTemplate(stackTemplate) return } -// [TODO] organizationId 별로 생성하지 않고, 하나의 stackTemplate 을 모든 organization 에서 재사용한다. ( 5월 한정, 추후 rearchitecture 필요) -func (r *StackTemplateRepository) Fetch(pg *pagination.Pagination) (out []domain.StackTemplate, err error) { - var stackTemplates []StackTemplate - +func (r *StackTemplateRepository) Fetch(pg *pagination.Pagination) (out []model.StackTemplate, err error) { if pg == nil { pg = pagination.NewPagination(nil) } - _, res := pg.Fetch(r.db.Preload(clause.Associations), &stackTemplates) + _, res := pg.Fetch(r.db.Preload(clause.Associations), &out) if res.Error != nil { return nil, res.Error } + return +} - for _, stackTemplate := range stackTemplates { - out = append(out, reflectStackTemplate(stackTemplate)) +func (r *StackTemplateRepository) FetchWithOrganization(organizationId string, pg *pagination.Pagination) (out []model.StackTemplate, err error) { + if pg == nil { + pg = pagination.NewPagination(nil) } + _, res := pg.Fetch( + r.db.Preload(clause.Associations). + Joins("JOIN stack_template_organizations ON stack_template_organizations.stack_template_id = stack_templates.id AND stack_template_organizations.organization_id = ?", organizationId), + &out) + if res.Error != nil { + return nil, res.Error + } return } -func (r *StackTemplateRepository) Create(dto domain.StackTemplate) (stackTemplateId uuid.UUID, err error) { - stackTemplate := StackTemplate{ - Name: dto.Name, - Description: dto.Description, - Template: dto.Template, - TemplateType: dto.TemplateType, - Version: dto.Version, - CloudService: dto.CloudService, - Platform: dto.Platform, - KubeVersion: dto.KubeVersion, - KubeType: dto.KubeType, - Services: dto.Services, - CreatorId: &dto.CreatorId, - UpdatorId: &dto.CreatorId} - res := r.db.Create(&stackTemplate) +func (r *StackTemplateRepository) Create(dto model.StackTemplate) (stackTemplateId uuid.UUID, err error) { + res := r.db.Create(&dto) if res.Error != nil { return uuid.Nil, res.Error } - return stackTemplate.ID, nil + return dto.ID, nil } -func (r *StackTemplateRepository) Update(dto domain.StackTemplate) (err error) { - res := r.db.Model(&StackTemplate{}). +func (r *StackTemplateRepository) Update(dto model.StackTemplate) (err error) { + res := r.db.Model(&model.StackTemplate{}). Where("id = ?", dto.ID). Updates(map[string]interface{}{ "Template": dto.Template, @@ -131,16 +94,16 @@ func (r *StackTemplateRepository) Update(dto domain.StackTemplate) (err error) { return nil } -func (r *StackTemplateRepository) Delete(dto domain.StackTemplate) (err error) { - res := r.db.Delete(&StackTemplate{}, "id = ?", dto.ID) +func (r *StackTemplateRepository) Delete(dto model.StackTemplate) (err error) { + res := r.db.Delete(&model.StackTemplate{}, "id = ?", dto.ID) if res.Error != nil { return res.Error } return nil } -func (r *StackTemplateRepository) UpdateOrganizations(stackTemplateId uuid.UUID, organizations []domain.Organization) (err error) { - var stackTemplate = StackTemplate{} +func (r *StackTemplateRepository) UpdateOrganizations(stackTemplateId uuid.UUID, organizations []model.Organization) (err error) { + var stackTemplate = model.StackTemplate{} res := r.db.Preload("Organizations").First(&stackTemplate, "id = ?", stackTemplateId) if res.Error != nil { return res.Error @@ -152,15 +115,3 @@ func (r *StackTemplateRepository) UpdateOrganizations(stackTemplateId uuid.UUID, return nil } - -func reflectStackTemplate(stackTemplate StackTemplate) (out domain.StackTemplate) { - if err := serializer.Map(stackTemplate.Model, &out); err != nil { - log.Error(err) - } - if err := serializer.Map(stackTemplate, &out); err != nil { - log.Error(err) - } - - out.Services = stackTemplate.Services - return -} diff --git a/internal/repository/user.go b/internal/repository/user.go index 12ed1a50..fcfd4981 100644 --- a/internal/repository/user.go +++ b/internal/repository/user.go @@ -4,8 +4,8 @@ import ( "time" "github.com/google/uuid" + "github.com/openinfradev/tks-api/internal/model" "github.com/openinfradev/tks-api/internal/pagination" - "github.com/openinfradev/tks-api/pkg/domain" "github.com/openinfradev/tks-api/pkg/httpErrors" "github.com/openinfradev/tks-api/pkg/log" "gorm.io/gorm" @@ -14,13 +14,13 @@ import ( // Interface type IUserRepository interface { CreateWithUuid(uuid uuid.UUID, accountId string, name string, email string, - department string, description string, organizationId string, roleId string) (domain.User, error) - List(filters ...FilterFunc) (out *[]domain.User, err error) - ListWithPagination(pg *pagination.Pagination, organizationId string) (out *[]domain.User, err error) - Get(accountId string, organizationId string) (domain.User, error) - GetByUuid(userId uuid.UUID) (domain.User, error) + department string, description string, organizationId string, roleId string) (model.User, error) + List(filters ...FilterFunc) (out *[]model.User, err error) + ListWithPagination(pg *pagination.Pagination, organizationId string) (out *[]model.User, err error) + Get(accountId string, organizationId string) (model.User, error) + GetByUuid(userId uuid.UUID) (model.User, error) UpdateWithUuid(uuid uuid.UUID, accountId string, name string, roleId string, email string, - department string, description string) (domain.User, error) + department string, description string) (model.User, error) UpdatePasswordAt(userId uuid.UUID, organizationId string, isTemporary bool) error DeleteWithUuid(uuid uuid.UUID) error Flush(organizationId string) error @@ -36,7 +36,7 @@ type UserRepository struct { } func (r *UserRepository) Flush(organizationId string) error { - res := r.db.Where("organization_id = ?", organizationId).Delete(&domain.User{}) + res := r.db.Where("organization_id = ?", organizationId).Delete(&model.User{}) if res.Error != nil { log.Errorf("error is :%s(%T)", res.Error.Error(), res.Error) return res.Error @@ -77,9 +77,9 @@ func NewUserRepository(db *gorm.DB) IUserRepository { //} func (r *UserRepository) CreateWithUuid(uuid uuid.UUID, accountId string, name string, email string, - department string, description string, organizationId string, roleId string) (domain.User, error) { + department string, description string, organizationId string, roleId string) (model.User, error) { - newUser := domain.User{ + newUser := model.User{ ID: uuid, AccountId: accountId, Name: name, @@ -92,11 +92,11 @@ func (r *UserRepository) CreateWithUuid(uuid uuid.UUID, accountId string, name s res := r.db.Create(&newUser) if res.Error != nil { log.Error(res.Error.Error()) - return domain.User{}, res.Error + return model.User{}, res.Error } user, err := r.getUserByAccountId(accountId, organizationId) if err != nil { - return domain.User{}, err + return model.User{}, err } return user, nil @@ -122,12 +122,12 @@ func (r *UserRepository) NameFilter(name string) FilterFunc { } } -func (r *UserRepository) List(filters ...FilterFunc) (*[]domain.User, error) { - var users []domain.User +func (r *UserRepository) List(filters ...FilterFunc) (*[]model.User, error) { + var users []model.User var res *gorm.DB if filters == nil { - res = r.db.Model(&domain.User{}).Preload("Organization").Preload("Role").Find(&users) + res = r.db.Model(&model.User{}).Preload("Organization").Preload("Role").Find(&users) } else { combinedFilter := func(filters ...FilterFunc) FilterFunc { return func(user *gorm.DB) *gorm.DB { @@ -138,7 +138,7 @@ func (r *UserRepository) List(filters ...FilterFunc) (*[]domain.User, error) { } } cFunc := combinedFilter(filters...) - res = cFunc(r.db.Model(&domain.User{}).Preload("Organization").Preload("Role")).Find(&users) + res = cFunc(r.db.Model(&model.User{}).Preload("Organization").Preload("Role")).Find(&users) } if res.Error != nil { @@ -149,7 +149,7 @@ func (r *UserRepository) List(filters ...FilterFunc) (*[]domain.User, error) { return nil, httpErrors.NewNotFoundError(httpErrors.NotFound, "", "") } - var out []domain.User + var out []model.User for _, user := range users { out = append(out, user) } @@ -157,20 +157,20 @@ func (r *UserRepository) List(filters ...FilterFunc) (*[]domain.User, error) { return &out, nil } -func (r *UserRepository) ListWithPagination(pg *pagination.Pagination, organizationId string) (*[]domain.User, error) { - var users []domain.User +func (r *UserRepository) ListWithPagination(pg *pagination.Pagination, organizationId string) (*[]model.User, error) { + var users []model.User if pg == nil { pg = pagination.NewPagination(nil) } - _, res := pg.Fetch(r.db.Preload("Organization").Preload("Role").Model(&domain.User{}).Where("organization_id = ?", organizationId), &users) + _, res := pg.Fetch(r.db.Preload("Organization").Preload("Role").Model(&model.User{}).Where("organization_id = ?", organizationId), &users) if res.Error != nil { log.Errorf("error is :%s(%T)", res.Error.Error(), res.Error) return nil, res.Error } - var out []domain.User + var out []model.User for _, user := range users { out = append(out, user) } @@ -178,32 +178,32 @@ func (r *UserRepository) ListWithPagination(pg *pagination.Pagination, organizat return &out, nil } -func (r *UserRepository) Get(accountId string, organizationId string) (domain.User, error) { +func (r *UserRepository) Get(accountId string, organizationId string) (model.User, error) { user, err := r.getUserByAccountId(accountId, organizationId) if err != nil { - return domain.User{}, err + return model.User{}, err } return user, nil } -func (r *UserRepository) GetByUuid(userId uuid.UUID) (respUser domain.User, err error) { - user := domain.User{} - res := r.db.Model(&domain.User{}).Preload("Organization").Preload("Role").Find(&user, "id = ?", userId) +func (r *UserRepository) GetByUuid(userId uuid.UUID) (respUser model.User, err error) { + user := model.User{} + res := r.db.Model(&model.User{}).Preload("Organization").Preload("Role").Find(&user, "id = ?", userId) if res.Error != nil { log.Errorf("error is :%s(%T)", res.Error.Error(), res.Error) - return domain.User{}, res.Error + return model.User{}, res.Error } if res.RowsAffected == 0 { - return domain.User{}, httpErrors.NewNotFoundError(httpErrors.NotFound, "", "") + return model.User{}, httpErrors.NewNotFoundError(httpErrors.NotFound, "", "") } return user, nil } func (r *UserRepository) UpdateWithUuid(uuid uuid.UUID, accountId string, name string, roleId string, - email string, department string, description string) (domain.User, error) { - var user domain.User - res := r.db.Model(&domain.User{}).Where("id = ?", uuid).Updates(domain.User{ + email string, department string, description string) (model.User, error) { + var user model.User + res := r.db.Model(&model.User{}).Where("id = ?", uuid).Updates(model.User{ AccountId: accountId, Name: name, Email: email, @@ -212,26 +212,26 @@ func (r *UserRepository) UpdateWithUuid(uuid uuid.UUID, accountId string, name s RoleId: roleId, }) if res.RowsAffected == 0 || res.Error != nil { - return domain.User{}, httpErrors.NewNotFoundError(httpErrors.NotFound, "", "") + return model.User{}, httpErrors.NewNotFoundError(httpErrors.NotFound, "", "") } if res.Error != nil { log.Errorf("error is :%s(%T)", res.Error.Error(), res.Error) - return domain.User{}, res.Error + return model.User{}, res.Error } - res = r.db.Model(&domain.User{}).Preload("Organization").Preload("Role").Where("id = ?", uuid).Find(&user) + res = r.db.Model(&model.User{}).Preload("Organization").Preload("Role").Where("id = ?", uuid).Find(&user) if res.Error != nil { - return domain.User{}, res.Error + return model.User{}, res.Error } return user, nil } func (r *UserRepository) UpdatePasswordAt(userId uuid.UUID, organizationId string, isTemporary bool) error { - var updateUser = domain.User{} + var updateUser = model.User{} if isTemporary { updateUser.PasswordUpdatedAt = time.Time{} } else { updateUser.PasswordUpdatedAt = time.Now() } - res := r.db.Model(&domain.User{}).Where("id = ? AND organization_id = ?", userId, organizationId). + res := r.db.Model(&model.User{}).Where("id = ? AND organization_id = ?", userId, organizationId). Select("password_updated_at").Updates(updateUser) if res.RowsAffected == 0 || res.Error != nil { @@ -245,7 +245,7 @@ func (r *UserRepository) UpdatePasswordAt(userId uuid.UUID, organizationId strin return nil } func (r *UserRepository) DeleteWithUuid(uuid uuid.UUID) error { - res := r.db.Unscoped().Delete(&domain.User{}, "id = ?", uuid) + res := r.db.Unscoped().Delete(&model.User{}, "id = ?", uuid) if res.Error != nil { log.Errorf("error is :%s(%T)", res.Error.Error(), res.Error) return res.Error @@ -273,17 +273,17 @@ func (r *UserRepository) DeleteWithUuid(uuid uuid.UUID) error { // Creator uuid.UUID //} -func (r *UserRepository) GetRoleByName(roleName string) (domain.Role, error) { +func (r *UserRepository) GetRoleByName(roleName string) (model.Role, error) { role, err := r.getRoleByName(roleName) if err != nil { - return domain.Role{}, err + return model.Role{}, err } return role, nil } -//func (r *UserRepository) FetchRoles() (*[]domain.Role, error) { -// var roles []domain.Role +//func (r *UserRepository) FetchRoles() (*[]model.Role, error) { +// var roles []model.Role // res := r.db.Find(&roles) // // if res.Error != nil { @@ -295,7 +295,7 @@ func (r *UserRepository) GetRoleByName(roleName string) (domain.Role, error) { // return nil, httpErrors.NewNotFoundError(httpErrors.NotFound, "", "") // } // -// var out []domain.Role +// var out []model.Role // for _, role := range roles { // outRole := r.reflectRole(role) // out = append(out, outRole) @@ -305,30 +305,30 @@ func (r *UserRepository) GetRoleByName(roleName string) (domain.Role, error) { //} // private members -func (r *UserRepository) getUserByAccountId(accountId string, organizationId string) (domain.User, error) { - user := domain.User{} - res := r.db.Model(&domain.User{}).Preload("Organization").Preload("Role"). +func (r *UserRepository) getUserByAccountId(accountId string, organizationId string) (model.User, error) { + user := model.User{} + res := r.db.Model(&model.User{}).Preload("Organization").Preload("Role"). Find(&user, "account_id = ? AND organization_id = ?", accountId, organizationId) if res.Error != nil { log.Errorf("error is :%s(%T)", res.Error.Error(), res.Error) - return domain.User{}, res.Error + return model.User{}, res.Error } if res.RowsAffected == 0 { - return domain.User{}, httpErrors.NewNotFoundError(httpErrors.NotFound, "", "") + return model.User{}, httpErrors.NewNotFoundError(httpErrors.NotFound, "", "") } return user, nil } -func (r *UserRepository) getRoleByName(roleName string) (domain.Role, error) { - role := domain.Role{} +func (r *UserRepository) getRoleByName(roleName string) (model.Role, error) { + role := model.Role{} res := r.db.First(&role, "name = ?", roleName) if res.Error != nil { log.Errorf("error is :%s(%T)", res.Error.Error(), res.Error) - return domain.Role{}, res.Error + return model.Role{}, res.Error } if res.RowsAffected == 0 { - return domain.Role{}, httpErrors.NewNotFoundError(httpErrors.NotFound, "", "") + return model.Role{}, httpErrors.NewNotFoundError(httpErrors.NotFound, "", "") } //if res.RowsAffected == 0 { diff --git a/internal/route/route.go b/internal/route/route.go index c28e1da8..0346e233 100644 --- a/internal/route/route.go +++ b/internal/route/route.go @@ -181,12 +181,14 @@ func SetupRouter(db *gorm.DB, argoClient argowf.ArgoClient, kc keycloak.IKeycloa stackTemplateHandler := delivery.NewStackTemplateHandler(usecaseFactory) r.Handle(API_PREFIX+API_VERSION+ADMINAPI_PREFIX+"/stack-templates", customMiddleware.Handle(internalApi.Admin_GetStackTemplates, http.HandlerFunc(stackTemplateHandler.GetStackTemplates))).Methods(http.MethodGet) + r.Handle(API_PREFIX+API_VERSION+ADMINAPI_PREFIX+"/stack-templates/services", customMiddleware.Handle(internalApi.Admin_GetStackTemplateServices, http.HandlerFunc(stackTemplateHandler.GetStackTemplateServices))).Methods(http.MethodGet) r.Handle(API_PREFIX+API_VERSION+ADMINAPI_PREFIX+"/stack-templates/{stackTemplateId}", customMiddleware.Handle(internalApi.Admin_GetStackTemplates, http.HandlerFunc(stackTemplateHandler.GetStackTemplate))).Methods(http.MethodGet) r.Handle(API_PREFIX+API_VERSION+ADMINAPI_PREFIX+"/stack-templates", customMiddleware.Handle(internalApi.Admin_CreateStackTemplate, http.HandlerFunc(stackTemplateHandler.CreateStackTemplate))).Methods(http.MethodPost) - r.Handle(API_PREFIX+API_VERSION+ADMINAPI_PREFIX+"/stack-templates/services", customMiddleware.Handle(internalApi.Admin_GetStackTemplateServices, http.HandlerFunc(stackTemplateHandler.GetStackTemplateServices))).Methods(http.MethodGet) r.Handle(API_PREFIX+API_VERSION+ADMINAPI_PREFIX+"/stack-templates/{stackTemplateId}/organizations", customMiddleware.Handle(internalApi.Admin_UpdateStackTemplateOrganizations, http.HandlerFunc(stackTemplateHandler.UpdateStackTemplateOrganizations))).Methods(http.MethodPut) r.Handle(API_PREFIX+API_VERSION+ADMINAPI_PREFIX+"/stack-templates/{stackTemplateId}", customMiddleware.Handle(internalApi.Admin_UpdateStackTemplate, http.HandlerFunc(stackTemplateHandler.UpdateStackTemplate))).Methods(http.MethodPut) r.Handle(API_PREFIX+API_VERSION+ADMINAPI_PREFIX+"/stack-templates/{stackTemplateId}", customMiddleware.Handle(internalApi.Admin_DeleteStackTemplate, http.HandlerFunc(stackTemplateHandler.DeleteStackTemplate))).Methods(http.MethodDelete) + r.Handle(API_PREFIX+API_VERSION+"/organizations/{organizationId}/stack-templates", customMiddleware.Handle(internalApi.GetOrganizationStackTemplates, http.HandlerFunc(stackTemplateHandler.GetOrganizationStackTemplates))).Methods(http.MethodGet) + r.Handle(API_PREFIX+API_VERSION+"/organizations/{organizationId}/stack-templates/{stackTemplateId}", customMiddleware.Handle(internalApi.GetOrganizationStackTemplate, http.HandlerFunc(stackTemplateHandler.GetOrganizationStackTemplate))).Methods(http.MethodGet) dashboardHandler := delivery.NewDashboardHandler(usecaseFactory) r.Handle(API_PREFIX+API_VERSION+"/organizations/{organizationId}/dashboard/charts", customMiddleware.Handle(internalApi.GetChartsDashboard, http.HandlerFunc(dashboardHandler.GetCharts))).Methods(http.MethodGet) @@ -244,9 +246,9 @@ func SetupRouter(db *gorm.DB, argoClient argowf.ArgoClient, kc keycloak.IKeycloa r.Handle(API_PREFIX+API_VERSION+"/organizations/{organizationId}/projects/{projectId}/kubeconfig", customMiddleware.Handle(internalApi.GetProjectKubeconfig, http.HandlerFunc(projectHandler.GetProjectKubeconfig))).Methods(http.MethodGet) auditHandler := delivery.NewAuditHandler(usecaseFactory) - r.Handle(API_PREFIX+API_VERSION+"/organizations/{organizationId}/audits", customMiddleware.Handle(internalApi.GetAudits, http.HandlerFunc(auditHandler.GetAudits))).Methods(http.MethodGet) - r.Handle(API_PREFIX+API_VERSION+"/organizations/{organizationId}/audits/{auditId}", customMiddleware.Handle(internalApi.GetAudit, http.HandlerFunc(auditHandler.GetAudit))).Methods(http.MethodGet) - r.Handle(API_PREFIX+API_VERSION+"/organizations/{organizationId}/audits/{auditId}", customMiddleware.Handle(internalApi.DeleteAudit, http.HandlerFunc(auditHandler.DeleteAudit))).Methods(http.MethodDelete) + r.Handle(API_PREFIX+API_VERSION+"/admin/audits", customMiddleware.Handle(internalApi.GetAudits, http.HandlerFunc(auditHandler.GetAudits))).Methods(http.MethodGet) + r.Handle(API_PREFIX+API_VERSION+"/admin/audits/{auditId}", customMiddleware.Handle(internalApi.GetAudit, http.HandlerFunc(auditHandler.GetAudit))).Methods(http.MethodGet) + r.Handle(API_PREFIX+API_VERSION+"/admin/audits/{auditId}", customMiddleware.Handle(internalApi.DeleteAudit, http.HandlerFunc(auditHandler.DeleteAudit))).Methods(http.MethodDelete) roleHandler := delivery.NewRoleHandler(usecaseFactory) r.Handle(API_PREFIX+API_VERSION+"/organizations/{organizationId}/roles", customMiddleware.Handle(internalApi.CreateTksRole, http.HandlerFunc(roleHandler.CreateTksRole))).Methods(http.MethodPost) diff --git a/internal/serializer/serializer.go b/internal/serializer/serializer.go index 70e96552..043a9ba4 100644 --- a/internal/serializer/serializer.go +++ b/internal/serializer/serializer.go @@ -5,7 +5,7 @@ import ( "reflect" "github.com/google/uuid" - "github.com/openinfradev/tks-api/pkg/domain" + "github.com/openinfradev/tks-api/internal/model" "github.com/openinfradev/tks-api/pkg/log" ) @@ -85,8 +85,14 @@ func recursiveMap(src interface{}, dst interface{}, converterMap ConverterMap) e } } */ - + } else { + if fieldName == "Model" { + if err := recursiveMap(srcField.Interface(), dst, converterMap); err != nil { + return err + } + } } + } return nil @@ -100,11 +106,11 @@ func Map(src interface{}, dst interface{}) error { val, _ := uuid.Parse(i.(string)) return val, nil }, - {srcType: reflect.TypeOf((*domain.Role)(nil)).Elem(), dstType: reflect.TypeOf("")}: func(i interface{}) (interface{}, error) { - return i.(domain.Role).Name, nil + {srcType: reflect.TypeOf((*model.Role)(nil)).Elem(), dstType: reflect.TypeOf("")}: func(i interface{}) (interface{}, error) { + return i.(model.Role).Name, nil }, - {srcType: reflect.TypeOf(""), dstType: reflect.TypeOf((*domain.Role)(nil)).Elem()}: func(i interface{}) (interface{}, error) { - return domain.Role{Name: i.(string)}, nil + {srcType: reflect.TypeOf(""), dstType: reflect.TypeOf((*model.Role)(nil)).Elem()}: func(i interface{}) (interface{}, error) { + return model.Role{Name: i.(string)}, nil }, }) } diff --git a/internal/usecase/alert.go b/internal/usecase/alert.go index 99fafa9c..de77595a 100644 --- a/internal/usecase/alert.go +++ b/internal/usecase/alert.go @@ -7,9 +7,9 @@ import ( "strings" "time" - "github.com/openinfradev/tks-api/internal/middleware/auth/request" - "github.com/google/uuid" + "github.com/openinfradev/tks-api/internal/middleware/auth/request" + "github.com/openinfradev/tks-api/internal/model" "github.com/openinfradev/tks-api/internal/pagination" "github.com/openinfradev/tks-api/internal/repository" "github.com/openinfradev/tks-api/pkg/domain" @@ -20,14 +20,14 @@ import ( ) type IAlertUsecase interface { - Get(ctx context.Context, alertId uuid.UUID) (domain.Alert, error) - GetByName(ctx context.Context, organizationId string, name string) (domain.Alert, error) - Fetch(ctx context.Context, organizationId string, pg *pagination.Pagination) ([]domain.Alert, error) + Get(ctx context.Context, alertId uuid.UUID) (model.Alert, error) + GetByName(ctx context.Context, organizationId string, name string) (model.Alert, error) + Fetch(ctx context.Context, organizationId string, pg *pagination.Pagination) ([]model.Alert, error) Create(ctx context.Context, dto domain.CreateAlertRequest) (err error) - Update(ctx context.Context, dto domain.Alert) error - Delete(ctx context.Context, dto domain.Alert) error + Update(ctx context.Context, dto model.Alert) error + Delete(ctx context.Context, dto model.Alert) error - CreateAlertAction(ctx context.Context, dto domain.AlertAction) (alertActionId uuid.UUID, err error) + CreateAlertAction(ctx context.Context, dto model.AlertAction) (alertActionId uuid.UUID, err error) } type AlertUsecase struct { @@ -101,7 +101,7 @@ func (u *AlertUsecase) Create(ctx context.Context, input domain.CreateAlertReque node = alert.Labels.Instance } - dto := domain.Alert{ + dto := model.Alert{ OrganizationId: organizationId, Name: alert.Labels.AlertName, Code: alert.Labels.AlertName, @@ -125,11 +125,11 @@ func (u *AlertUsecase) Create(ctx context.Context, input domain.CreateAlertReque return nil } -func (u *AlertUsecase) Update(ctx context.Context, dto domain.Alert) error { +func (u *AlertUsecase) Update(ctx context.Context, dto model.Alert) error { return nil } -func (u *AlertUsecase) Get(ctx context.Context, alertId uuid.UUID) (alert domain.Alert, err error) { +func (u *AlertUsecase) Get(ctx context.Context, alertId uuid.UUID) (alert model.Alert, err error) { alert, err = u.repo.Get(alertId) if err != nil { return alert, err @@ -139,7 +139,7 @@ func (u *AlertUsecase) Get(ctx context.Context, alertId uuid.UUID) (alert domain return } -func (u *AlertUsecase) GetByName(ctx context.Context, organizationId string, name string) (out domain.Alert, err error) { +func (u *AlertUsecase) GetByName(ctx context.Context, organizationId string, name string) (out model.Alert, err error) { out, err = u.repo.GetByName(organizationId, name) if err != nil { if errors.Is(err, gorm.ErrRecordNotFound) { @@ -150,7 +150,7 @@ func (u *AlertUsecase) GetByName(ctx context.Context, organizationId string, nam return } -func (u *AlertUsecase) Fetch(ctx context.Context, organizationId string, pg *pagination.Pagination) (alerts []domain.Alert, err error) { +func (u *AlertUsecase) Fetch(ctx context.Context, organizationId string, pg *pagination.Pagination) (alerts []model.Alert, err error) { alerts, err = u.repo.Fetch(organizationId, pg) if err != nil { return nil, err @@ -163,8 +163,8 @@ func (u *AlertUsecase) Fetch(ctx context.Context, organizationId string, pg *pag return alerts, nil } -func (u *AlertUsecase) Delete(ctx context.Context, dto domain.Alert) (err error) { - user, ok := request.UserFrom(ctx) +func (u *AlertUsecase) Delete(ctx context.Context, dto model.Alert) (err error) { + _, ok := request.UserFrom(ctx) if !ok { return httpErrors.NewUnauthorizedError(fmt.Errorf("Invalid token"), "A_INVALID_TOKEN", "") } @@ -174,8 +174,6 @@ func (u *AlertUsecase) Delete(ctx context.Context, dto domain.Alert) (err error) return httpErrors.NewNotFoundError(err, "AL_NOT_FOUND_ALERT", "") } - *dto.UpdatorId = user.GetUserId() - err = u.repo.Delete(dto) if err != nil { return err @@ -184,7 +182,7 @@ func (u *AlertUsecase) Delete(ctx context.Context, dto domain.Alert) (err error) return nil } -func (u *AlertUsecase) CreateAlertAction(ctx context.Context, dto domain.AlertAction) (alertActionId uuid.UUID, err error) { +func (u *AlertUsecase) CreateAlertAction(ctx context.Context, dto model.AlertAction) (alertActionId uuid.UUID, err error) { user, ok := request.UserFrom(ctx) if !ok { return uuid.Nil, httpErrors.NewUnauthorizedError(fmt.Errorf("Invalid token"), "A_INVALID_TOKEN", "") @@ -208,7 +206,7 @@ func (u *AlertUsecase) CreateAlertAction(ctx context.Context, dto domain.AlertAc return } -func (u *AlertUsecase) getOrganizationFromCluster(clusters *[]domain.Cluster, strId string) (organizationId string, err error) { +func (u *AlertUsecase) getOrganizationFromCluster(clusters *[]model.Cluster, strId string) (organizationId string, err error) { clusterId := domain.ClusterId(strId) if !clusterId.Validate() { return "", fmt.Errorf("Invalid clusterId %s", strId) @@ -223,9 +221,9 @@ func (u *AlertUsecase) getOrganizationFromCluster(clusters *[]domain.Cluster, st return "", fmt.Errorf("No martched organization %s", strId) } -func (u *AlertUsecase) makeAdditionalInfo(alert *domain.Alert) { +func (u *AlertUsecase) makeAdditionalInfo(alert *model.Alert) { alert.FiredAt = &alert.CreatedAt - //alert.Status = domain.AlertActionStatus_CREATED + //alert.Status = model.AlertActionStatus_CREATED if len(alert.AlertActions) > 0 { alert.TakedAt = &alert.AlertActions[0].CreatedAt @@ -242,7 +240,7 @@ func (u *AlertUsecase) makeAdditionalInfo(alert *domain.Alert) { } } -func (u *AlertUsecase) makeGrafanaUrl(ctx context.Context, primaryCluster domain.Cluster, alert domain.CreateAlertRequestAlert, clusterId domain.ClusterId) (url string) { +func (u *AlertUsecase) makeGrafanaUrl(ctx context.Context, primaryCluster model.Cluster, alert domain.CreateAlertRequestAlert, clusterId domain.ClusterId) (url string) { primaryGrafanaEndpoint := "" appGroups, err := u.appGroupRepo.Fetch(primaryCluster.ID, nil) if err == nil { diff --git a/internal/usecase/app-group.go b/internal/usecase/app-group.go index f6a2d7b4..a73c0e6b 100644 --- a/internal/usecase/app-group.go +++ b/internal/usecase/app-group.go @@ -6,6 +6,7 @@ import ( "strings" "github.com/openinfradev/tks-api/internal/middleware/auth/request" + "github.com/openinfradev/tks-api/internal/model" "github.com/openinfradev/tks-api/internal/pagination" "github.com/openinfradev/tks-api/internal/repository" argowf "github.com/openinfradev/tks-api/pkg/argo-client" @@ -17,12 +18,12 @@ import ( ) type IAppGroupUsecase interface { - Fetch(ctx context.Context, clusterId domain.ClusterId, pg *pagination.Pagination) ([]domain.AppGroup, error) - Create(ctx context.Context, dto domain.AppGroup) (id domain.AppGroupId, err error) - Get(ctx context.Context, id domain.AppGroupId) (out domain.AppGroup, err error) + Fetch(ctx context.Context, clusterId domain.ClusterId, pg *pagination.Pagination) ([]model.AppGroup, error) + Create(ctx context.Context, dto model.AppGroup) (id domain.AppGroupId, err error) + Get(ctx context.Context, id domain.AppGroupId) (out model.AppGroup, err error) Delete(ctx context.Context, id domain.AppGroupId) (err error) - GetApplications(ctx context.Context, id domain.AppGroupId, applicationType domain.ApplicationType) (out []domain.Application, err error) - UpdateApplication(ctx context.Context, dto domain.Application) (err error) + GetApplications(ctx context.Context, id domain.AppGroupId, applicationType domain.ApplicationType) (out []model.Application, err error) + UpdateApplication(ctx context.Context, dto model.Application) (err error) } type AppGroupUsecase struct { @@ -41,7 +42,7 @@ func NewAppGroupUsecase(r repository.Repository, argoClient argowf.ArgoClient) I } } -func (u *AppGroupUsecase) Fetch(ctx context.Context, clusterId domain.ClusterId, pg *pagination.Pagination) (out []domain.AppGroup, err error) { +func (u *AppGroupUsecase) Fetch(ctx context.Context, clusterId domain.ClusterId, pg *pagination.Pagination) (out []model.AppGroup, err error) { out, err = u.repo.Fetch(clusterId, pg) if err != nil { return nil, err @@ -49,7 +50,7 @@ func (u *AppGroupUsecase) Fetch(ctx context.Context, clusterId domain.ClusterId, return } -func (u *AppGroupUsecase) Create(ctx context.Context, dto domain.AppGroup) (id domain.AppGroupId, err error) { +func (u *AppGroupUsecase) Create(ctx context.Context, dto model.AppGroup) (id domain.AppGroupId, err error) { user, ok := request.UserFrom(ctx) if !ok { return "", httpErrors.NewUnauthorizedError(fmt.Errorf("Invalid token"), "A_INVALID_TOKEN", "") @@ -158,10 +159,10 @@ func (u *AppGroupUsecase) Create(ctx context.Context, dto domain.AppGroup) (id d return dto.ID, nil } -func (u *AppGroupUsecase) Get(ctx context.Context, id domain.AppGroupId) (out domain.AppGroup, err error) { +func (u *AppGroupUsecase) Get(ctx context.Context, id domain.AppGroupId) (out model.AppGroup, err error) { appGroup, err := u.repo.Get(id) if err != nil { - return domain.AppGroup{}, err + return model.AppGroup{}, err } return appGroup, nil } @@ -255,7 +256,7 @@ func (u *AppGroupUsecase) Delete(ctx context.Context, id domain.AppGroupId) (err return nil } -func (u *AppGroupUsecase) GetApplications(ctx context.Context, id domain.AppGroupId, applicationType domain.ApplicationType) (out []domain.Application, err error) { +func (u *AppGroupUsecase) GetApplications(ctx context.Context, id domain.AppGroupId, applicationType domain.ApplicationType) (out []model.Application, err error) { out, err = u.repo.GetApplications(id, applicationType) if err != nil { return nil, err @@ -263,7 +264,7 @@ func (u *AppGroupUsecase) GetApplications(ctx context.Context, id domain.AppGrou return } -func (u *AppGroupUsecase) UpdateApplication(ctx context.Context, dto domain.Application) (err error) { +func (u *AppGroupUsecase) UpdateApplication(ctx context.Context, dto model.Application) (err error) { err = u.repo.UpsertApplication(dto) if err != nil { return err diff --git a/internal/usecase/app-serve-app.go b/internal/usecase/app-serve-app.go index b16163f1..198b31a3 100644 --- a/internal/usecase/app-serve-app.go +++ b/internal/usecase/app-serve-app.go @@ -14,6 +14,7 @@ import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "github.com/openinfradev/tks-api/internal/kubernetes" + "github.com/openinfradev/tks-api/internal/model" "github.com/openinfradev/tks-api/internal/pagination" "github.com/openinfradev/tks-api/internal/repository" argowf "github.com/openinfradev/tks-api/pkg/argo-client" @@ -23,19 +24,19 @@ import ( ) type IAppServeAppUsecase interface { - CreateAppServeApp(app *domain.AppServeApp) (appId string, taskId string, err error) - GetAppServeApps(organizationId string, showAll bool, pg *pagination.Pagination) ([]domain.AppServeApp, error) - GetAppServeAppById(appId string) (*domain.AppServeApp, error) - GetAppServeAppTasks(appId string, pg *pagination.Pagination) ([]domain.AppServeAppTask, error) - GetAppServeAppTaskById(taskId string) (*domain.AppServeAppTask, *domain.AppServeApp, error) - GetAppServeAppLatestTask(appId string) (*domain.AppServeAppTask, error) + CreateAppServeApp(app *model.AppServeApp) (appId string, taskId string, err error) + GetAppServeApps(organizationId string, showAll bool, pg *pagination.Pagination) ([]model.AppServeApp, error) + GetAppServeAppById(appId string) (*model.AppServeApp, error) + GetAppServeAppTasks(appId string, pg *pagination.Pagination) ([]model.AppServeAppTask, error) + GetAppServeAppTaskById(taskId string) (*model.AppServeAppTask, *model.AppServeApp, error) + GetAppServeAppLatestTask(appId string) (*model.AppServeAppTask, error) GetNumOfAppsOnStack(organizationId string, clusterId string) (int64, error) IsAppServeAppExist(appId string) (bool, error) IsAppServeAppNameExist(orgId string, appName string) (bool, error) IsAppServeAppNamespaceExist(clusterId string, namespace string) (bool, error) UpdateAppServeAppStatus(appId string, taskId string, status string, output string) (ret string, err error) DeleteAppServeApp(appId string) (res string, err error) - UpdateAppServeApp(app *domain.AppServeApp, appTask *domain.AppServeAppTask) (ret string, err error) + UpdateAppServeApp(app *model.AppServeApp, appTask *model.AppServeAppTask) (ret string, err error) UpdateAppServeAppEndpoint(appId string, taskId string, endpoint string, previewEndpoint string, helmRevision int32) (string, error) PromoteAppServeApp(appId string) (ret string, err error) AbortAppServeApp(appId string) (ret string, err error) @@ -58,7 +59,7 @@ func NewAppServeAppUsecase(r repository.Repository, argoClient argowf.ArgoClient } } -func (u *AppServeAppUsecase) CreateAppServeApp(app *domain.AppServeApp) (string, string, error) { +func (u *AppServeAppUsecase) CreateAppServeApp(app *model.AppServeApp) (string, string, error) { if app == nil { return "", "", fmt.Errorf("invalid app obj") } @@ -179,7 +180,7 @@ func (u *AppServeAppUsecase) CreateAppServeApp(app *domain.AppServeApp) (string, return appId, app.Name, nil } -func (u *AppServeAppUsecase) GetAppServeApps(organizationId string, showAll bool, pg *pagination.Pagination) ([]domain.AppServeApp, error) { +func (u *AppServeAppUsecase) GetAppServeApps(organizationId string, showAll bool, pg *pagination.Pagination) ([]model.AppServeApp, error) { apps, err := u.repo.GetAppServeApps(organizationId, showAll, pg) if err != nil { fmt.Println(apps) @@ -188,7 +189,7 @@ func (u *AppServeAppUsecase) GetAppServeApps(organizationId string, showAll bool return apps, nil } -func (u *AppServeAppUsecase) GetAppServeAppById(appId string) (*domain.AppServeApp, error) { +func (u *AppServeAppUsecase) GetAppServeAppById(appId string) (*model.AppServeApp, error) { asa, err := u.repo.GetAppServeAppById(appId) if err != nil { return nil, err @@ -222,7 +223,7 @@ func (u *AppServeAppUsecase) GetAppServeAppById(appId string) (*domain.AppServeA return asa, nil } -func (u *AppServeAppUsecase) GetAppServeAppTasks(appId string, pg *pagination.Pagination) ([]domain.AppServeAppTask, error) { +func (u *AppServeAppUsecase) GetAppServeAppTasks(appId string, pg *pagination.Pagination) ([]model.AppServeAppTask, error) { tasks, err := u.repo.GetAppServeAppTasksByAppId(appId, pg) if err != nil { log.Debugf("Tasks: %v", tasks) @@ -231,7 +232,7 @@ func (u *AppServeAppUsecase) GetAppServeAppTasks(appId string, pg *pagination.Pa return tasks, nil } -func (u *AppServeAppUsecase) GetAppServeAppTaskById(taskId string) (*domain.AppServeAppTask, *domain.AppServeApp, error) { +func (u *AppServeAppUsecase) GetAppServeAppTaskById(taskId string) (*model.AppServeAppTask, *model.AppServeApp, error) { task, app, err := u.repo.GetAppServeAppTaskById(taskId) if err != nil { return nil, nil, err @@ -240,7 +241,7 @@ func (u *AppServeAppUsecase) GetAppServeAppTaskById(taskId string) (*domain.AppS return task, app, nil } -func (u *AppServeAppUsecase) GetAppServeAppLatestTask(appId string) (*domain.AppServeAppTask, error) { +func (u *AppServeAppUsecase) GetAppServeAppLatestTask(appId string) (*model.AppServeAppTask, error) { task, err := u.repo.GetAppServeAppLatestTask(appId) if err != nil { return nil, err @@ -361,7 +362,7 @@ func (u *AppServeAppUsecase) DeleteAppServeApp(appId string) (res string, err er * Start delete task * ********************/ - appTask := &domain.AppServeAppTask{ + appTask := &model.AppServeAppTask{ AppServeAppId: app.ID, Version: strconv.Itoa(len(app.AppServeAppTasks) + 1), ArtifactUrl: "", @@ -412,7 +413,7 @@ func (u *AppServeAppUsecase) DeleteAppServeApp(appId string) (res string, err er "Confirm result by checking the app status after a while.", app.Name), nil } -func (u *AppServeAppUsecase) UpdateAppServeApp(app *domain.AppServeApp, appTask *domain.AppServeAppTask) (ret string, err error) { +func (u *AppServeAppUsecase) UpdateAppServeApp(app *model.AppServeApp, appTask *model.AppServeAppTask) (ret string, err error) { if appTask == nil { return "", errors.New("invalid parameters. appTask is nil") } @@ -659,7 +660,7 @@ func (u *AppServeAppUsecase) RollbackAppServeApp(appId string, taskId string) (r } // Find target(dest) task - var task domain.AppServeAppTask + var task model.AppServeAppTask for _, t := range app.AppServeAppTasks { if t.ID == taskId { task = t diff --git a/internal/usecase/audit.go b/internal/usecase/audit.go index 7461cf05..0e3e5165 100644 --- a/internal/usecase/audit.go +++ b/internal/usecase/audit.go @@ -5,17 +5,17 @@ import ( "github.com/google/uuid" "github.com/openinfradev/tks-api/internal/middleware/auth/request" + "github.com/openinfradev/tks-api/internal/model" "github.com/openinfradev/tks-api/internal/pagination" "github.com/openinfradev/tks-api/internal/repository" - "github.com/openinfradev/tks-api/pkg/domain" "github.com/openinfradev/tks-api/pkg/httpErrors" ) type IAuditUsecase interface { - Get(ctx context.Context, auditId uuid.UUID) (domain.Audit, error) - Fetch(ctx context.Context, organizationId string, pg *pagination.Pagination) ([]domain.Audit, error) - Create(ctx context.Context, dto domain.Audit) (auditId uuid.UUID, err error) - Delete(ctx context.Context, dto domain.Audit) error + Get(ctx context.Context, auditId uuid.UUID) (model.Audit, error) + Fetch(ctx context.Context, pg *pagination.Pagination) ([]model.Audit, error) + Create(ctx context.Context, dto model.Audit) (auditId uuid.UUID, err error) + Delete(ctx context.Context, dto model.Audit) error } type AuditUsecase struct { @@ -28,7 +28,7 @@ func NewAuditUsecase(r repository.Repository) IAuditUsecase { } } -func (u *AuditUsecase) Create(ctx context.Context, dto domain.Audit) (auditId uuid.UUID, err error) { +func (u *AuditUsecase) Create(ctx context.Context, dto model.Audit) (auditId uuid.UUID, err error) { if dto.UserId == nil { user, ok := request.UserFrom(ctx) if ok { @@ -43,23 +43,23 @@ func (u *AuditUsecase) Create(ctx context.Context, dto domain.Audit) (auditId uu return auditId, nil } -func (u *AuditUsecase) Get(ctx context.Context, auditId uuid.UUID) (res domain.Audit, err error) { +func (u *AuditUsecase) Get(ctx context.Context, auditId uuid.UUID) (res model.Audit, err error) { res, err = u.repo.Get(auditId) if err != nil { - return domain.Audit{}, err + return model.Audit{}, err } return } -func (u *AuditUsecase) Fetch(ctx context.Context, organizationId string, pg *pagination.Pagination) (audits []domain.Audit, err error) { - audits, err = u.repo.Fetch(organizationId, pg) +func (u *AuditUsecase) Fetch(ctx context.Context, pg *pagination.Pagination) (audits []model.Audit, err error) { + audits, err = u.repo.Fetch(pg) if err != nil { return nil, err } return } -func (u *AuditUsecase) Delete(ctx context.Context, dto domain.Audit) (err error) { +func (u *AuditUsecase) Delete(ctx context.Context, dto model.Audit) (err error) { err = u.repo.Delete(dto.ID) if err != nil { return httpErrors.NewNotFoundError(err, "", "") diff --git a/internal/usecase/auth.go b/internal/usecase/auth.go index 4fe4fd15..7213d1f2 100644 --- a/internal/usecase/auth.go +++ b/internal/usecase/auth.go @@ -24,13 +24,14 @@ import ( "github.com/openinfradev/tks-api/internal/helper" "github.com/openinfradev/tks-api/internal/keycloak" "github.com/openinfradev/tks-api/internal/mail" + "github.com/openinfradev/tks-api/internal/model" "github.com/openinfradev/tks-api/internal/repository" "github.com/openinfradev/tks-api/pkg/domain" "github.com/openinfradev/tks-api/pkg/httpErrors" ) type IAuthUsecase interface { - Login(accountId string, password string, organizationId string) (domain.User, error) + Login(accountId string, password string, organizationId string) (model.User, error) Logout(accessToken string, organizationId string) error PingToken(accessToken string, organizationId string) error FindId(code string, email string, userName string, organizationId string) (string, error) @@ -67,28 +68,28 @@ func NewAuthUsecase(r repository.Repository, kc keycloak.IKeycloak) IAuthUsecase } } -func (u *AuthUsecase) Login(accountId string, password string, organizationId string) (domain.User, error) { +func (u *AuthUsecase) Login(accountId string, password string, organizationId string) (model.User, error) { // Authentication with DB user, err := u.userRepository.Get(accountId, organizationId) if err != nil { - return domain.User{}, httpErrors.NewBadRequestError(err, "A_INVALID_ID", "") + return model.User{}, httpErrors.NewBadRequestError(err, "A_INVALID_ID", "") } - var accountToken *domain.User + var accountToken *model.User accountToken, err = u.kc.Login(accountId, password, organizationId) if err != nil { apiErr, ok := err.(*gocloak.APIError) if ok { if apiErr.Code == 401 { - return domain.User{}, httpErrors.NewBadRequestError(fmt.Errorf("Mismatch password"), "A_INVALID_PASSWORD", "") + return model.User{}, httpErrors.NewBadRequestError(fmt.Errorf("Mismatch password"), "A_INVALID_PASSWORD", "") } } - return domain.User{}, httpErrors.NewInternalServerError(err, "", "") + return model.User{}, httpErrors.NewInternalServerError(err, "", "") } log.Errorf("err: %v", err) if err != nil { //TODO: implement not found handling - return domain.User{}, err + return model.User{}, err } // Insert token @@ -254,7 +255,7 @@ func (u *AuthUsecase) FindPassword(code string, accountId string, email string, } func (u *AuthUsecase) VerifyIdentity(accountId string, email string, userName string, organizationId string) error { - var users *[]domain.User + var users *[]model.User var err error if accountId == "" { diff --git a/internal/usecase/cloud-account.go b/internal/usecase/cloud-account.go index a938066f..b6719bbb 100644 --- a/internal/usecase/cloud-account.go +++ b/internal/usecase/cloud-account.go @@ -15,10 +15,10 @@ import ( "github.com/aws/aws-sdk-go-v2/service/elasticloadbalancingv2" "github.com/aws/aws-sdk-go-v2/service/servicequotas" "github.com/aws/aws-sdk-go-v2/service/sts" + "github.com/google/uuid" "github.com/openinfradev/tks-api/internal/kubernetes" "github.com/openinfradev/tks-api/internal/middleware/auth/request" - - "github.com/google/uuid" + "github.com/openinfradev/tks-api/internal/model" "github.com/openinfradev/tks-api/internal/pagination" "github.com/openinfradev/tks-api/internal/repository" argowf "github.com/openinfradev/tks-api/pkg/argo-client" @@ -32,14 +32,14 @@ import ( const MAX_WORKFLOW_TIME = 30 type ICloudAccountUsecase interface { - Get(ctx context.Context, cloudAccountId uuid.UUID) (domain.CloudAccount, error) - GetByName(ctx context.Context, organizationId string, name string) (domain.CloudAccount, error) - GetByAwsAccountId(ctx context.Context, awsAccountId string) (domain.CloudAccount, error) + Get(ctx context.Context, cloudAccountId uuid.UUID) (model.CloudAccount, error) + GetByName(ctx context.Context, organizationId string, name string) (model.CloudAccount, error) + GetByAwsAccountId(ctx context.Context, awsAccountId string) (model.CloudAccount, error) GetResourceQuota(ctx context.Context, cloudAccountId uuid.UUID) (available bool, out domain.ResourceQuota, err error) - Fetch(ctx context.Context, organizationId string, pg *pagination.Pagination) ([]domain.CloudAccount, error) - Create(ctx context.Context, dto domain.CloudAccount) (cloudAccountId uuid.UUID, err error) - Update(ctx context.Context, dto domain.CloudAccount) error - Delete(ctx context.Context, dto domain.CloudAccount) error + Fetch(ctx context.Context, organizationId string, pg *pagination.Pagination) ([]model.CloudAccount, error) + Create(ctx context.Context, dto model.CloudAccount) (cloudAccountId uuid.UUID, err error) + Update(ctx context.Context, dto model.CloudAccount) error + Delete(ctx context.Context, dto model.CloudAccount) error DeleteForce(ctx context.Context, cloudAccountId uuid.UUID) error } @@ -57,14 +57,15 @@ func NewCloudAccountUsecase(r repository.Repository, argoClient argowf.ArgoClien } } -func (u *CloudAccountUsecase) Create(ctx context.Context, dto domain.CloudAccount) (cloudAccountId uuid.UUID, err error) { +func (u *CloudAccountUsecase) Create(ctx context.Context, dto model.CloudAccount) (cloudAccountId uuid.UUID, err error) { user, ok := request.UserFrom(ctx) if !ok { return uuid.Nil, httpErrors.NewBadRequestError(fmt.Errorf("Invalid token"), "", "") } + userId := user.GetUserId() dto.Resource = "TODO server result or additional information" - dto.CreatorId = user.GetUserId() + dto.CreatorId = &userId _, err = u.GetByName(ctx, dto.OrganizationId, dto.Name) if err == nil { @@ -114,14 +115,15 @@ func (u *CloudAccountUsecase) Create(ctx context.Context, dto domain.CloudAccoun return cloudAccountId, nil } -func (u *CloudAccountUsecase) Update(ctx context.Context, dto domain.CloudAccount) error { +func (u *CloudAccountUsecase) Update(ctx context.Context, dto model.CloudAccount) error { user, ok := request.UserFrom(ctx) if !ok { return httpErrors.NewBadRequestError(fmt.Errorf("Invalid token"), "", "") } + userId := user.GetUserId() dto.Resource = "TODO server result or additional information" - dto.UpdatorId = user.GetUserId() + dto.UpdatorId = &userId err := u.repo.Update(dto) if err != nil { return httpErrors.NewInternalServerError(err, "", "") @@ -129,10 +131,10 @@ func (u *CloudAccountUsecase) Update(ctx context.Context, dto domain.CloudAccoun return nil } -func (u *CloudAccountUsecase) Get(ctx context.Context, cloudAccountId uuid.UUID) (res domain.CloudAccount, err error) { +func (u *CloudAccountUsecase) Get(ctx context.Context, cloudAccountId uuid.UUID) (res model.CloudAccount, err error) { res, err = u.repo.Get(cloudAccountId) if err != nil { - return domain.CloudAccount{}, err + return model.CloudAccount{}, err } res.Clusters = u.getClusterCnt(cloudAccountId) @@ -140,31 +142,31 @@ func (u *CloudAccountUsecase) Get(ctx context.Context, cloudAccountId uuid.UUID) return } -func (u *CloudAccountUsecase) GetByName(ctx context.Context, organizationId string, name string) (res domain.CloudAccount, err error) { +func (u *CloudAccountUsecase) GetByName(ctx context.Context, organizationId string, name string) (res model.CloudAccount, err error) { res, err = u.repo.GetByName(organizationId, name) if err != nil { if errors.Is(err, gorm.ErrRecordNotFound) { - return domain.CloudAccount{}, httpErrors.NewNotFoundError(err, "", "") + return model.CloudAccount{}, httpErrors.NewNotFoundError(err, "", "") } - return domain.CloudAccount{}, err + return model.CloudAccount{}, err } res.Clusters = u.getClusterCnt(res.ID) return } -func (u *CloudAccountUsecase) GetByAwsAccountId(ctx context.Context, awsAccountId string) (res domain.CloudAccount, err error) { +func (u *CloudAccountUsecase) GetByAwsAccountId(ctx context.Context, awsAccountId string) (res model.CloudAccount, err error) { res, err = u.repo.GetByAwsAccountId(awsAccountId) if err != nil { if errors.Is(err, gorm.ErrRecordNotFound) { - return domain.CloudAccount{}, httpErrors.NewNotFoundError(err, "", "") + return model.CloudAccount{}, httpErrors.NewNotFoundError(err, "", "") } - return domain.CloudAccount{}, err + return model.CloudAccount{}, err } res.Clusters = u.getClusterCnt(res.ID) return } -func (u *CloudAccountUsecase) Fetch(ctx context.Context, organizationId string, pg *pagination.Pagination) (cloudAccounts []domain.CloudAccount, err error) { +func (u *CloudAccountUsecase) Fetch(ctx context.Context, organizationId string, pg *pagination.Pagination) (cloudAccounts []model.CloudAccount, err error) { cloudAccounts, err = u.repo.Fetch(organizationId, pg) if err != nil { return nil, err @@ -176,17 +178,18 @@ func (u *CloudAccountUsecase) Fetch(ctx context.Context, organizationId string, return } -func (u *CloudAccountUsecase) Delete(ctx context.Context, dto domain.CloudAccount) (err error) { +func (u *CloudAccountUsecase) Delete(ctx context.Context, dto model.CloudAccount) (err error) { user, ok := request.UserFrom(ctx) if !ok { return httpErrors.NewBadRequestError(fmt.Errorf("Invalid token"), "", "") } + userId := user.GetUserId() cloudAccount, err := u.Get(ctx, dto.ID) if err != nil { return httpErrors.NewNotFoundError(err, "", "") } - dto.UpdatorId = user.GetUserId() + dto.UpdatorId = &userId if u.getClusterCnt(dto.ID) > 0 { return fmt.Errorf("사용 중인 클러스터가 있어 삭제할 수 없습니다.") diff --git a/internal/usecase/cluster.go b/internal/usecase/cluster.go index f298fff7..e22233f3 100644 --- a/internal/usecase/cluster.go +++ b/internal/usecase/cluster.go @@ -8,13 +8,11 @@ import ( "strings" "time" + "github.com/google/uuid" "github.com/openinfradev/tks-api/internal/helper" "github.com/openinfradev/tks-api/internal/kubernetes" "github.com/openinfradev/tks-api/internal/middleware/auth/request" - byoh "github.com/vmware-tanzu/cluster-api-provider-bringyourownhost/apis/infrastructure/v1beta1" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - - "github.com/google/uuid" + "github.com/openinfradev/tks-api/internal/model" "github.com/openinfradev/tks-api/internal/pagination" "github.com/openinfradev/tks-api/internal/repository" "github.com/openinfradev/tks-api/internal/serializer" @@ -25,19 +23,21 @@ import ( gcache "github.com/patrickmn/go-cache" "github.com/pkg/errors" "github.com/spf13/viper" + byoh "github.com/vmware-tanzu/cluster-api-provider-bringyourownhost/apis/infrastructure/v1beta1" "gopkg.in/yaml.v3" "gorm.io/gorm" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" ) type IClusterUsecase interface { WithTrx(*gorm.DB) IClusterUsecase - Fetch(ctx context.Context, organizationId string, pg *pagination.Pagination) ([]domain.Cluster, error) - FetchByCloudAccountId(ctx context.Context, cloudAccountId uuid.UUID, pg *pagination.Pagination) (out []domain.Cluster, err error) - Create(ctx context.Context, dto domain.Cluster) (clusterId domain.ClusterId, err error) - Import(ctx context.Context, dto domain.Cluster) (clusterId domain.ClusterId, err error) - Bootstrap(ctx context.Context, dto domain.Cluster) (clusterId domain.ClusterId, err error) + Fetch(ctx context.Context, organizationId string, pg *pagination.Pagination) ([]model.Cluster, error) + FetchByCloudAccountId(ctx context.Context, cloudAccountId uuid.UUID, pg *pagination.Pagination) (out []model.Cluster, err error) + Create(ctx context.Context, dto model.Cluster) (clusterId domain.ClusterId, err error) + Import(ctx context.Context, dto model.Cluster) (clusterId domain.ClusterId, err error) + Bootstrap(ctx context.Context, dto model.Cluster) (clusterId domain.ClusterId, err error) Install(ctx context.Context, clusterId domain.ClusterId) (err error) - Get(ctx context.Context, clusterId domain.ClusterId) (out domain.Cluster, err error) + Get(ctx context.Context, clusterId domain.ClusterId) (out model.Cluster, err error) GetClusterSiteValues(ctx context.Context, clusterId domain.ClusterId) (out domain.ClusterSiteValuesResponse, err error) Delete(ctx context.Context, clusterId domain.ClusterId) (err error) CreateBootstrapKubeconfig(ctx context.Context, clusterId domain.ClusterId) (out domain.BootstrapKubeconfig, err error) @@ -101,7 +101,7 @@ func (u *ClusterUsecase) WithTrx(trxHandle *gorm.DB) IClusterUsecase { return u } -func (u *ClusterUsecase) Fetch(ctx context.Context, organizationId string, pg *pagination.Pagination) (out []domain.Cluster, err error) { +func (u *ClusterUsecase) Fetch(ctx context.Context, organizationId string, pg *pagination.Pagination) (out []model.Cluster, err error) { user, ok := request.UserFrom(ctx) if !ok { return out, httpErrors.NewBadRequestError(fmt.Errorf("Invalid token"), "", "") @@ -120,7 +120,7 @@ func (u *ClusterUsecase) Fetch(ctx context.Context, organizationId string, pg *p return out, nil } -func (u *ClusterUsecase) FetchByCloudAccountId(ctx context.Context, cloudAccountId uuid.UUID, pg *pagination.Pagination) (out []domain.Cluster, err error) { +func (u *ClusterUsecase) FetchByCloudAccountId(ctx context.Context, cloudAccountId uuid.UUID, pg *pagination.Pagination) (out []model.Cluster, err error) { if cloudAccountId == uuid.Nil { return nil, fmt.Errorf("Invalid cloudAccountId") } @@ -133,7 +133,7 @@ func (u *ClusterUsecase) FetchByCloudAccountId(ctx context.Context, cloudAccount return out, nil } -func (u *ClusterUsecase) Create(ctx context.Context, dto domain.Cluster) (clusterId domain.ClusterId, err error) { +func (u *ClusterUsecase) Create(ctx context.Context, dto model.Cluster) (clusterId domain.ClusterId, err error) { user, ok := request.UserFrom(ctx) if !ok { return "", httpErrors.NewBadRequestError(fmt.Errorf("Invalid token"), "", "") @@ -153,7 +153,7 @@ func (u *ClusterUsecase) Create(ctx context.Context, dto domain.Cluster) (cluste tksCloudAccountId := dto.CloudAccountId.String() isExist := false for _, ca := range cloudAccounts { - if ca.ID == dto.CloudAccountId { + if ca.ID == *dto.CloudAccountId { // FOR TEST. ADD MAGIC KEYWORD if strings.Contains(ca.Name, domain.CLOUD_ACCOUNT_INCLUSTER) { @@ -213,7 +213,7 @@ func (u *ClusterUsecase) Create(ctx context.Context, dto domain.Cluster) (cluste return clusterId, nil } -func (u *ClusterUsecase) Import(ctx context.Context, dto domain.Cluster) (clusterId domain.ClusterId, err error) { +func (u *ClusterUsecase) Import(ctx context.Context, dto model.Cluster) (clusterId domain.ClusterId, err error) { user, ok := request.UserFrom(ctx) if !ok { return "", httpErrors.NewBadRequestError(fmt.Errorf("Invalid token"), "", "") @@ -275,7 +275,7 @@ func (u *ClusterUsecase) Import(ctx context.Context, dto domain.Cluster) (cluste return clusterId, nil } -func (u *ClusterUsecase) Bootstrap(ctx context.Context, dto domain.Cluster) (clusterId domain.ClusterId, err error) { +func (u *ClusterUsecase) Bootstrap(ctx context.Context, dto model.Cluster) (clusterId domain.ClusterId, err error) { user, ok := request.UserFrom(ctx) if !ok { return "", httpErrors.NewBadRequestError(fmt.Errorf("Invalid token"), "", "") @@ -374,10 +374,10 @@ func (u *ClusterUsecase) Install(ctx context.Context, clusterId domain.ClusterId return nil } -func (u *ClusterUsecase) Get(ctx context.Context, clusterId domain.ClusterId) (out domain.Cluster, err error) { +func (u *ClusterUsecase) Get(ctx context.Context, clusterId domain.ClusterId) (out model.Cluster, err error) { cluster, err := u.repo.Get(clusterId) if err != nil { - return domain.Cluster{}, err + return model.Cluster{}, err } return cluster, nil @@ -453,13 +453,13 @@ func (u *ClusterUsecase) GetClusterSiteValues(ctx context.Context, clusterId dom out.SshKeyName = "tks-seoul" out.ClusterRegion = "ap-northeast-2" - if err := serializer.Map(cluster.Conf, &out); err != nil { + if err := serializer.Map(cluster, &out); err != nil { log.ErrorWithContext(ctx, err) } if cluster.StackTemplate.CloudService == "AWS" && cluster.StackTemplate.KubeType == "AWS" { - out.TksUserNode = cluster.Conf.TksUserNode / domain.MAX_AZ_NUM - out.TksUserNodeMax = cluster.Conf.TksUserNodeMax / domain.MAX_AZ_NUM + out.TksUserNode = cluster.TksUserNode / domain.MAX_AZ_NUM + out.TksUserNodeMax = cluster.TksUserNodeMax / domain.MAX_AZ_NUM } if err := serializer.Map(cluster, &out); err != nil { @@ -712,30 +712,30 @@ func (u *ClusterUsecase) GetNodes(ctx context.Context, clusterId domain.ClusterI out = []domain.ClusterNode{ { Type: "TKS_CP_NODE", - Targeted: cluster.Conf.TksCpNode, + Targeted: cluster.TksCpNode, Registered: tksCpNodeRegistered, Registering: tksCpNodeRegistering, - Status: clusterNodeStatus(cluster.Conf.TksCpNode, tksCpNodeRegistered), + Status: clusterNodeStatus(cluster.TksCpNode, tksCpNodeRegistered), Command: command + "control-plane", Validity: bootstrapKubeconfig.Expiration, Hosts: tksCpHosts, }, { Type: "TKS_INFRA_NODE", - Targeted: cluster.Conf.TksInfraNode, + Targeted: cluster.TksInfraNode, Registered: tksInfraNodeRegistered, Registering: tksInfraNodeRegistering, - Status: clusterNodeStatus(cluster.Conf.TksInfraNode, tksInfraNodeRegistered), + Status: clusterNodeStatus(cluster.TksInfraNode, tksInfraNodeRegistered), Command: command + "tks", Validity: bootstrapKubeconfig.Expiration, Hosts: tksInfraHosts, }, { Type: "TKS_USER_NODE", - Targeted: cluster.Conf.TksUserNode, + Targeted: cluster.TksUserNode, Registered: tksUserNodeRegistered, Registering: tksUserNodeRegistering, - Status: clusterNodeStatus(cluster.Conf.TksUserNode, tksUserNodeRegistered), + Status: clusterNodeStatus(cluster.TksUserNode, tksUserNodeRegistered), Command: command + "worker", Validity: bootstrapKubeconfig.Expiration, Hosts: tksUserHosts, @@ -779,7 +779,7 @@ func (u *ClusterUsecase) GetNodes(ctx context.Context, clusterId domain.ClusterI } /* -func (u *ClusterUsecase) constructClusterConf(rawConf *domain.ClusterConf) (clusterConf *domain.ClusterConf, err error) { +func (u *ClusterUsecase) constructClusterConf(rawConf *model.ClusterConf) (clusterConf *model.ClusterConf, err error) { region := "ap-northeast-2" if rawConf != nil && rawConf.Region != "" { region = rawConf.Region @@ -857,7 +857,7 @@ func (u *ClusterUsecase) constructClusterConf(rawConf *domain.ClusterConf) (clus } // Construct cluster conf - tempConf := domain.ClusterConf{ + tempConf := model.ClusterConf{ SshKeyName: sshKeyName, Region: region, NumOfAz: int(numOfAz), diff --git a/internal/usecase/dashboard.go b/internal/usecase/dashboard.go index 18ceda50..a4f271a8 100644 --- a/internal/usecase/dashboard.go +++ b/internal/usecase/dashboard.go @@ -11,6 +11,7 @@ import ( "github.com/google/uuid" "github.com/openinfradev/tks-api/internal/helper" "github.com/openinfradev/tks-api/internal/kubernetes" + "github.com/openinfradev/tks-api/internal/model" "github.com/openinfradev/tks-api/internal/repository" "github.com/openinfradev/tks-api/internal/serializer" "github.com/openinfradev/tks-api/pkg/domain" @@ -153,11 +154,11 @@ func (u *DashboardUsecase) GetResources(ctx context.Context, organizationId stri return out, err } - filteredClusters := funk.Filter(clusters, func(x domain.Cluster) bool { + filteredClusters := funk.Filter(clusters, func(x model.Cluster) bool { return x.Status != domain.ClusterStatus_DELETED }) if filteredClusters != nil { - out.Stack = fmt.Sprintf("%d 개", len(filteredClusters.([]domain.Cluster))) + out.Stack = fmt.Sprintf("%d 개", len(filteredClusters.([]model.Cluster))) } else { out.Stack = "0 개" } diff --git a/internal/usecase/organization.go b/internal/usecase/organization.go index 832430a1..dcc7bb60 100644 --- a/internal/usecase/organization.go +++ b/internal/usecase/organization.go @@ -8,6 +8,7 @@ import ( "github.com/google/uuid" "github.com/openinfradev/tks-api/internal/helper" "github.com/openinfradev/tks-api/internal/keycloak" + "github.com/openinfradev/tks-api/internal/model" "github.com/openinfradev/tks-api/internal/pagination" "github.com/openinfradev/tks-api/internal/repository" argowf "github.com/openinfradev/tks-api/pkg/argo-client" @@ -19,10 +20,10 @@ import ( ) type IOrganizationUsecase interface { - Create(context.Context, *domain.Organization) (organizationId string, err error) - Fetch(pg *pagination.Pagination) (*[]domain.Organization, error) - Get(organizationId string) (domain.Organization, error) - Update(organizationId string, in domain.UpdateOrganizationRequest) (domain.Organization, error) + Create(context.Context, *model.Organization) (organizationId string, err error) + Fetch(pg *pagination.Pagination) (*[]model.Organization, error) + Get(organizationId string) (model.Organization, error) + Update(organizationId string, in domain.UpdateOrganizationRequest) (model.Organization, error) UpdatePrimaryClusterId(organizationId string, clusterId string) (err error) Delete(organizationId string, accessToken string) error } @@ -43,7 +44,7 @@ func NewOrganizationUsecase(r repository.Repository, argoClient argowf.ArgoClien } } -func (u *OrganizationUsecase) Create(ctx context.Context, in *domain.Organization) (organizationId string, err error) { +func (u *OrganizationUsecase) Create(ctx context.Context, in *model.Organization) (organizationId string, err error) { creator := uuid.Nil if in.Creator != "" { creator, err = uuid.Parse(in.Creator) @@ -84,17 +85,17 @@ func (u *OrganizationUsecase) Create(ctx context.Context, in *domain.Organizatio return organizationId, nil } -func (u *OrganizationUsecase) Fetch(pg *pagination.Pagination) (out *[]domain.Organization, err error) { +func (u *OrganizationUsecase) Fetch(pg *pagination.Pagination) (out *[]model.Organization, err error) { organizations, err := u.repo.Fetch(pg) if err != nil { return nil, err } return organizations, nil } -func (u *OrganizationUsecase) Get(organizationId string) (res domain.Organization, err error) { +func (u *OrganizationUsecase) Get(organizationId string) (res model.Organization, err error) { res, err = u.repo.Get(organizationId) if err != nil { - return domain.Organization{}, httpErrors.NewNotFoundError(err, "", "") + return model.Organization{}, httpErrors.NewNotFoundError(err, "", "") } return res, nil } @@ -130,15 +131,15 @@ func (u *OrganizationUsecase) Delete(organizationId string, accessToken string) return nil } -func (u *OrganizationUsecase) Update(organizationId string, in domain.UpdateOrganizationRequest) (domain.Organization, error) { +func (u *OrganizationUsecase) Update(organizationId string, in domain.UpdateOrganizationRequest) (model.Organization, error) { _, err := u.Get(organizationId) if err != nil { - return domain.Organization{}, httpErrors.NewNotFoundError(err, "", "") + return model.Organization{}, httpErrors.NewNotFoundError(err, "", "") } res, err := u.repo.Update(organizationId, in) if err != nil { - return domain.Organization{}, err + return model.Organization{}, err } return res, nil diff --git a/internal/usecase/permission.go b/internal/usecase/permission.go index 4d38cca3..bcce7e95 100644 --- a/internal/usecase/permission.go +++ b/internal/usecase/permission.go @@ -2,21 +2,21 @@ package usecase import ( "github.com/google/uuid" + "github.com/openinfradev/tks-api/internal/model" "github.com/openinfradev/tks-api/internal/repository" - "github.com/openinfradev/tks-api/pkg/domain" ) type IPermissionUsecase interface { - CreatePermissionSet(permissionSet *domain.PermissionSet) error - GetPermissionSetByRoleId(roleId string) (*domain.PermissionSet, error) - ListPermissions(roleId string) ([]*domain.Permission, error) - //GetPermission(id uuid.UUID) (*domain.Permission, error) + CreatePermissionSet(permissionSet *model.PermissionSet) error + GetPermissionSetByRoleId(roleId string) (*model.PermissionSet, error) + ListPermissions(roleId string) ([]*model.Permission, error) + //GetPermission(id uuid.UUID) (*model.Permission, error) //DeletePermission(id uuid.UUID) error - //UpdatePermission(permission *domain.Permission) error - SetRoleIdToPermissionSet(roleId string, permissionSet *domain.PermissionSet) - GetAllowedPermissionSet() *domain.PermissionSet - GetUserPermissionSet() *domain.PermissionSet - UpdatePermission(permission *domain.Permission) error + //UpdatePermission(permission *model.Permission) error + SetRoleIdToPermissionSet(roleId string, permissionSet *model.PermissionSet) + GetAllowedPermissionSet() *model.PermissionSet + GetUserPermissionSet() *model.PermissionSet + UpdatePermission(permission *model.Permission) error } type PermissionUsecase struct { @@ -29,7 +29,7 @@ func NewPermissionUsecase(repo repository.Repository) *PermissionUsecase { } } -func (p PermissionUsecase) CreatePermissionSet(permissionSet *domain.PermissionSet) error { +func (p PermissionUsecase) CreatePermissionSet(permissionSet *model.PermissionSet) error { var err error if err = p.repo.Create(permissionSet.Dashboard); err != nil { return err @@ -52,8 +52,8 @@ func (p PermissionUsecase) CreatePermissionSet(permissionSet *domain.PermissionS return nil } -func (p PermissionUsecase) GetPermissionSetByRoleId(roleId string) (*domain.PermissionSet, error) { - permissionSet := &domain.PermissionSet{ +func (p PermissionUsecase) GetPermissionSetByRoleId(roleId string) (*model.PermissionSet, error) { + permissionSet := &model.PermissionSet{ Dashboard: nil, Stack: nil, SecurityPolicy: nil, @@ -68,17 +68,17 @@ func (p PermissionUsecase) GetPermissionSetByRoleId(roleId string) (*domain.Perm } for _, permission := range permissionList { switch permission.Name { - case string(domain.DashBoardPermission): + case string(model.DashBoardPermission): permissionSet.Dashboard = permission - case string(domain.StackPermission): + case string(model.StackPermission): permissionSet.Stack = permission - case string(domain.SecurityPolicyPermission): + case string(model.SecurityPolicyPermission): permissionSet.SecurityPolicy = permission - case string(domain.ProjectManagementPermission): + case string(model.ProjectManagementPermission): permissionSet.ProjectManagement = permission - case string(domain.NotificationPermission): + case string(model.NotificationPermission): permissionSet.Notification = permission - case string(domain.ConfigurationPermission): + case string(model.ConfigurationPermission): permissionSet.Configuration = permission } } @@ -86,11 +86,11 @@ func (p PermissionUsecase) GetPermissionSetByRoleId(roleId string) (*domain.Perm return permissionSet, nil } -func (p PermissionUsecase) ListPermissions(roleId string) ([]*domain.Permission, error) { +func (p PermissionUsecase) ListPermissions(roleId string) ([]*model.Permission, error) { return p.repo.List(roleId) } -func (p PermissionUsecase) GetPermission(id uuid.UUID) (*domain.Permission, error) { +func (p PermissionUsecase) GetPermission(id uuid.UUID) (*model.Permission, error) { return p.repo.Get(id) } @@ -98,22 +98,22 @@ func (p PermissionUsecase) DeletePermission(id uuid.UUID) error { return p.repo.Delete(id) } -func (p PermissionUsecase) UpdatePermission(permission *domain.Permission) error { +func (p PermissionUsecase) UpdatePermission(permission *model.Permission) error { return p.repo.Update(permission) } -func (p PermissionUsecase) SetRoleIdToPermissionSet(roleId string, permissionSet *domain.PermissionSet) { +func (p PermissionUsecase) SetRoleIdToPermissionSet(roleId string, permissionSet *model.PermissionSet) { permissionSet.SetRoleId(roleId) } -func (p PermissionUsecase) GetAllowedPermissionSet() *domain.PermissionSet { - permissionSet := domain.NewDefaultPermissionSet() +func (p PermissionUsecase) GetAllowedPermissionSet() *model.PermissionSet { + permissionSet := model.NewDefaultPermissionSet() permissionSet.SetAllowedPermissionSet() return permissionSet } -func (p PermissionUsecase) GetUserPermissionSet() *domain.PermissionSet { - permissionSet := domain.NewDefaultPermissionSet() +func (p PermissionUsecase) GetUserPermissionSet() *model.PermissionSet { + permissionSet := model.NewDefaultPermissionSet() permissionSet.SetUserPermissionSet() return permissionSet } diff --git a/internal/usecase/policy-template.go b/internal/usecase/policy-template.go index 9f1b8263..7c76a846 100644 --- a/internal/usecase/policy-template.go +++ b/internal/usecase/policy-template.go @@ -9,21 +9,23 @@ import ( "github.com/google/uuid" "github.com/open-policy-agent/opa/ast" "github.com/openinfradev/tks-api/internal/middleware/auth/request" + "github.com/openinfradev/tks-api/internal/model" "github.com/openinfradev/tks-api/internal/pagination" "github.com/openinfradev/tks-api/internal/repository" "github.com/openinfradev/tks-api/pkg/domain" "github.com/openinfradev/tks-api/pkg/httpErrors" + "github.com/openinfradev/tks-api/pkg/log" ) type IPolicyTemplateUsecase interface { - Create(ctx context.Context, policyTemplate domain.PolicyTemplate) (policyTemplateId string, err error) - Fetch(ctx context.Context, pg *pagination.Pagination) (policyTemplates []domain.PolicyTemplate, err error) + Create(ctx context.Context, policyTemplate model.PolicyTemplate) (policyTemplateId string, err error) + Fetch(ctx context.Context, pg *pagination.Pagination) (policyTemplates []model.PolicyTemplate, err error) Update(ctx context.Context, policyTemplateId uuid.UUID, update domain.UpdatePolicyTemplateRequest) (err error) - Get(ctx context.Context, policyTemplateId uuid.UUID) (policyTemplates *domain.PolicyTemplate, err error) + Get(ctx context.Context, policyTemplateId uuid.UUID) (policyTemplates *model.PolicyTemplate, err error) Delete(ctx context.Context, policyTemplateId uuid.UUID) (err error) IsPolicyTemplateNameExist(ctx context.Context, policyTemplateName string) (bool, error) IsPolicyTemplateKindExist(ctx context.Context, policyTemplateKind string) (bool, error) - GetPolicyTemplateVersion(ctx context.Context, policyTemplateId uuid.UUID, version string) (policyTemplateVersionsReponse *domain.PolicyTemplate, err error) + GetPolicyTemplateVersion(ctx context.Context, policyTemplateId uuid.UUID, version string) (policyTemplateVersionsReponse *model.PolicyTemplate, err error) ListPolicyTemplateVersions(ctx context.Context, policyTemplateId uuid.UUID) (policyTemplateVersionsReponse *domain.ListPolicyTemplateVersionsResponse, err error) DeletePolicyTemplateVersion(ctx context.Context, policyTemplateId uuid.UUID, version string) (err error) CreatePolicyTemplateVersion(ctx context.Context, policyTemplateId uuid.UUID, newVersion string, schema []domain.ParameterDef, rego string, libs []string) (version string, err error) @@ -45,7 +47,7 @@ func NewPolicyTemplateUsecase(r repository.Repository) IPolicyTemplateUsecase { } } -func (u *PolicyTemplateUsecase) Create(ctx context.Context, dto domain.PolicyTemplate) (policyTemplateId string, err error) { +func (u *PolicyTemplateUsecase) Create(ctx context.Context, dto model.PolicyTemplate) (policyTemplateId string, err error) { user, ok := request.UserFrom(ctx) if !ok { return "", httpErrors.NewUnauthorizedError(fmt.Errorf("invalid token"), "A_INVALID_TOKEN", "") @@ -79,7 +81,7 @@ func (u *PolicyTemplateUsecase) Create(ctx context.Context, dto domain.PolicyTem return id.String(), nil } -func (u *PolicyTemplateUsecase) Fetch(ctx context.Context, pg *pagination.Pagination) (policyTemplates []domain.PolicyTemplate, err error) { +func (u *PolicyTemplateUsecase) Fetch(ctx context.Context, pg *pagination.Pagination) (policyTemplates []model.PolicyTemplate, err error) { policyTemplates, err = u.repo.Fetch(pg) if err != nil { @@ -99,7 +101,7 @@ func (u *PolicyTemplateUsecase) Fetch(ctx context.Context, pg *pagination.Pagina } -func (u *PolicyTemplateUsecase) Get(ctx context.Context, policyTemplateID uuid.UUID) (policyTemplates *domain.PolicyTemplate, err error) { +func (u *PolicyTemplateUsecase) Get(ctx context.Context, policyTemplateID uuid.UUID) (policyTemplates *model.PolicyTemplate, err error) { policyTemplate, err := u.repo.GetByID(policyTemplateID) if err != nil { @@ -173,7 +175,7 @@ func (u *PolicyTemplateUsecase) IsPolicyTemplateKindExist(ctx context.Context, p return u.repo.ExistByKind(policyTemplateKind) } -func (u *PolicyTemplateUsecase) GetPolicyTemplateVersion(ctx context.Context, policyTemplateId uuid.UUID, version string) (policyTemplateVersionsReponse *domain.PolicyTemplate, err error) { +func (u *PolicyTemplateUsecase) GetPolicyTemplateVersion(ctx context.Context, policyTemplateId uuid.UUID, version string) (policyTemplateVersionsReponse *model.PolicyTemplate, err error) { policyTemplate, err := u.repo.GetPolicyTemplateVersion(policyTemplateId, version) if err != nil { @@ -190,10 +192,12 @@ func (u *PolicyTemplateUsecase) GetPolicyTemplateVersion(ctx context.Context, po return policyTemplate, nil } -func (*PolicyTemplateUsecase) updatePermittedOrganizations(organizations *[]domain.Organization, permittedOrgIdSet map[string]string, policyTemplate *domain.PolicyTemplate) { +func (*PolicyTemplateUsecase) updatePermittedOrganizations(organizations *[]model.Organization, permittedOrgIdSet map[string]string, policyTemplate *model.PolicyTemplate) { // 허용리스트가 비어있으면 모든 Org에 대해서 허용 permitted := len(permittedOrgIdSet) == 0 + log.Info("CHECK HERE ", permitted) + for _, organization := range *organizations { _, ok := permittedOrgIdSet[organization.ID] @@ -201,21 +205,30 @@ func (*PolicyTemplateUsecase) updatePermittedOrganizations(organizations *[]doma if !ok { policyTemplate.PermittedOrganizations = append( policyTemplate.PermittedOrganizations, - domain.PermittedOrganization{ - OrganizationId: organization.ID, - OrganizationName: organization.Name, - Permitted: permitted, - }) + + // ktkfree : 역시 이부분 확인 부탁 드립니다. + /* + domain.PermittedOrganization{ + OrganizationId: organization.ID, + OrganizationName: organization.Name, + Permitted: permitted, + } + */ + ) } } } -func (*PolicyTemplateUsecase) getPermittedOrganiationIdSet(policyTemplate *domain.PolicyTemplate) map[string]string { +func (*PolicyTemplateUsecase) getPermittedOrganiationIdSet(policyTemplate *model.PolicyTemplate) map[string]string { permittedOrgIdSet := make(map[string]string) for _, permittedOrg := range policyTemplate.PermittedOrganizations { // Set 처리를 위해서 키만 사용, 값은 아무거나 - permittedOrgIdSet[permittedOrg.OrganizationId] = "1" + + // ktkfree : 이부분 확인 부탁 드립니다. + // + //permittedOrgIdSet[permittedOrg.OrganizationId] = "1" + log.Info("CHECK HERE ", permittedOrg) } return permittedOrgIdSet } diff --git a/internal/usecase/role.go b/internal/usecase/role.go index 70d51081..bc5d3734 100644 --- a/internal/usecase/role.go +++ b/internal/usecase/role.go @@ -1,18 +1,18 @@ package usecase import ( + "github.com/openinfradev/tks-api/internal/model" "github.com/openinfradev/tks-api/internal/pagination" "github.com/openinfradev/tks-api/internal/repository" - "github.com/openinfradev/tks-api/pkg/domain" ) type IRoleUsecase interface { - CreateTksRole(role *domain.Role) (string, error) - ListRoles(pg *pagination.Pagination) ([]*domain.Role, error) - ListTksRoles(organizationId string, pg *pagination.Pagination) ([]*domain.Role, error) - GetTksRole(id string) (*domain.Role, error) + CreateTksRole(role *model.Role) (string, error) + ListRoles(pg *pagination.Pagination) ([]*model.Role, error) + ListTksRoles(organizationId string, pg *pagination.Pagination) ([]*model.Role, error) + GetTksRole(id string) (*model.Role, error) DeleteTksRole(id string) error - UpdateTksRole(role *domain.Role) error + UpdateTksRole(role *model.Role) error } type RoleUsecase struct { @@ -25,11 +25,11 @@ func NewRoleUsecase(repo repository.Repository) *RoleUsecase { } } -func (r RoleUsecase) CreateTksRole(role *domain.Role) (string, error) { +func (r RoleUsecase) CreateTksRole(role *model.Role) (string, error) { return r.repo.Create(role) } -func (r RoleUsecase) ListTksRoles(organizationId string, pg *pagination.Pagination) ([]*domain.Role, error) { +func (r RoleUsecase) ListTksRoles(organizationId string, pg *pagination.Pagination) ([]*model.Role, error) { roles, err := r.repo.ListTksRoles(organizationId, pg) if err != nil { return nil, err @@ -38,11 +38,11 @@ func (r RoleUsecase) ListTksRoles(organizationId string, pg *pagination.Paginati return roles, nil } -func (r RoleUsecase) ListRoles(pg *pagination.Pagination) ([]*domain.Role, error) { +func (r RoleUsecase) ListRoles(pg *pagination.Pagination) ([]*model.Role, error) { return r.repo.List(nil) } -func (r RoleUsecase) GetTksRole(id string) (*domain.Role, error) { +func (r RoleUsecase) GetTksRole(id string) (*model.Role, error) { role, err := r.repo.GetTksRole(id) if err != nil { return nil, err @@ -55,7 +55,7 @@ func (r RoleUsecase) DeleteTksRole(id string) error { return r.repo.Delete(id) } -func (r RoleUsecase) UpdateTksRole(role *domain.Role) error { +func (r RoleUsecase) UpdateTksRole(role *model.Role) error { err := r.repo.Update(role) if err != nil { return err diff --git a/internal/usecase/stack-template.go b/internal/usecase/stack-template.go index 2a258d16..4c672e7a 100644 --- a/internal/usecase/stack-template.go +++ b/internal/usecase/stack-template.go @@ -7,20 +7,21 @@ import ( "github.com/google/uuid" "github.com/openinfradev/tks-api/internal" "github.com/openinfradev/tks-api/internal/middleware/auth/request" + "github.com/openinfradev/tks-api/internal/model" "github.com/openinfradev/tks-api/internal/pagination" "github.com/openinfradev/tks-api/internal/repository" - "github.com/openinfradev/tks-api/pkg/domain" "github.com/openinfradev/tks-api/pkg/httpErrors" "github.com/openinfradev/tks-api/pkg/log" ) type IStackTemplateUsecase interface { - Get(ctx context.Context, stackTemplateId uuid.UUID) (domain.StackTemplate, error) - Fetch(ctx context.Context, pg *pagination.Pagination) ([]domain.StackTemplate, error) - Create(ctx context.Context, dto domain.StackTemplate) (stackTemplate uuid.UUID, err error) - Update(ctx context.Context, dto domain.StackTemplate) error - Delete(ctx context.Context, dto domain.StackTemplate) error - UpdateOrganizations(ctx context.Context, dto domain.StackTemplate) error + Get(ctx context.Context, stackTemplateId uuid.UUID) (model.StackTemplate, error) + Fetch(ctx context.Context, pg *pagination.Pagination) ([]model.StackTemplate, error) + FetchWithOrganization(ctx context.Context, organizationId string, pg *pagination.Pagination) ([]model.StackTemplate, error) + Create(ctx context.Context, dto model.StackTemplate) (stackTemplate uuid.UUID, err error) + Update(ctx context.Context, dto model.StackTemplate) error + Delete(ctx context.Context, dto model.StackTemplate) error + UpdateOrganizations(ctx context.Context, dto model.StackTemplate) error } type StackTemplateUsecase struct { @@ -35,13 +36,14 @@ func NewStackTemplateUsecase(r repository.Repository) IStackTemplateUsecase { } } -func (u *StackTemplateUsecase) Create(ctx context.Context, dto domain.StackTemplate) (stackTemplateId uuid.UUID, err error) { +func (u *StackTemplateUsecase) Create(ctx context.Context, dto model.StackTemplate) (stackTemplateId uuid.UUID, err error) { user, ok := request.UserFrom(ctx) if !ok { return uuid.Nil, httpErrors.NewBadRequestError(fmt.Errorf("Invalid token"), "", "") } - dto.CreatorId = user.GetUserId() - dto.UpdatorId = user.GetUserId() + userId := user.GetUserId() + dto.CreatorId = &userId + dto.UpdatorId = &userId pg := pagination.NewPaginationWithFilter("name", "", "$eq", []string{dto.Name}) stackTemplates, _ := u.Fetch(ctx, pg) @@ -76,7 +78,7 @@ func (u *StackTemplateUsecase) Create(ctx context.Context, dto domain.StackTempl return stackTemplateId, nil } -func (u *StackTemplateUsecase) Update(ctx context.Context, dto domain.StackTemplate) error { +func (u *StackTemplateUsecase) Update(ctx context.Context, dto model.StackTemplate) error { _, err := u.repo.Get(dto.ID) if err != nil { return httpErrors.NewBadRequestError(err, "ST_NOT_EXISTED_STACK_TEMPLATE", "") @@ -89,15 +91,15 @@ func (u *StackTemplateUsecase) Update(ctx context.Context, dto domain.StackTempl return nil } -func (u *StackTemplateUsecase) Get(ctx context.Context, stackTemplateId uuid.UUID) (res domain.StackTemplate, err error) { +func (u *StackTemplateUsecase) Get(ctx context.Context, stackTemplateId uuid.UUID) (res model.StackTemplate, err error) { res, err = u.repo.Get(stackTemplateId) if err != nil { - return domain.StackTemplate{}, err + return model.StackTemplate{}, err } return } -func (u *StackTemplateUsecase) Fetch(ctx context.Context, pg *pagination.Pagination) (res []domain.StackTemplate, err error) { +func (u *StackTemplateUsecase) Fetch(ctx context.Context, pg *pagination.Pagination) (res []model.StackTemplate, err error) { res, err = u.repo.Fetch(pg) if err != nil { return nil, err @@ -105,17 +107,25 @@ func (u *StackTemplateUsecase) Fetch(ctx context.Context, pg *pagination.Paginat return res, nil } -func (u *StackTemplateUsecase) Delete(ctx context.Context, dto domain.StackTemplate) (err error) { +func (u *StackTemplateUsecase) FetchWithOrganization(ctx context.Context, organizationId string, pg *pagination.Pagination) (res []model.StackTemplate, err error) { + res, err = u.repo.FetchWithOrganization(organizationId, pg) + if err != nil { + return nil, err + } + return res, nil +} + +func (u *StackTemplateUsecase) Delete(ctx context.Context, dto model.StackTemplate) (err error) { return nil } -func (u *StackTemplateUsecase) UpdateOrganizations(ctx context.Context, dto domain.StackTemplate) error { +func (u *StackTemplateUsecase) UpdateOrganizations(ctx context.Context, dto model.StackTemplate) error { _, err := u.repo.Get(dto.ID) if err != nil { return httpErrors.NewBadRequestError(err, "ST_NOT_EXISTED_STACK_TEMPLATE", "") } - organizations := make([]domain.Organization, 0) + organizations := make([]model.Organization, 0) for _, organizationId := range dto.OrganizationIds { organization, err := u.organizationRepo.Get(organizationId) if err == nil { diff --git a/internal/usecase/stack.go b/internal/usecase/stack.go index 3bb6f907..9daeea2a 100644 --- a/internal/usecase/stack.go +++ b/internal/usecase/stack.go @@ -11,6 +11,7 @@ import ( "github.com/openinfradev/tks-api/internal/helper" "github.com/openinfradev/tks-api/internal/kubernetes" "github.com/openinfradev/tks-api/internal/middleware/auth/request" + "github.com/openinfradev/tks-api/internal/model" "github.com/openinfradev/tks-api/internal/pagination" "github.com/openinfradev/tks-api/internal/repository" "github.com/openinfradev/tks-api/internal/serializer" @@ -24,13 +25,13 @@ import ( ) type IStackUsecase interface { - Get(ctx context.Context, stackId domain.StackId) (domain.Stack, error) - GetByName(ctx context.Context, organizationId string, name string) (domain.Stack, error) - Fetch(ctx context.Context, organizationId string, pg *pagination.Pagination) ([]domain.Stack, error) - Create(ctx context.Context, dto domain.Stack) (stackId domain.StackId, err error) + Get(ctx context.Context, stackId domain.StackId) (model.Stack, error) + GetByName(ctx context.Context, organizationId string, name string) (model.Stack, error) + Fetch(ctx context.Context, organizationId string, pg *pagination.Pagination) ([]model.Stack, error) + Create(ctx context.Context, dto model.Stack) (stackId domain.StackId, err error) Install(ctx context.Context, stackId domain.StackId) (err error) - Update(ctx context.Context, dto domain.Stack) error - Delete(ctx context.Context, dto domain.Stack) error + Update(ctx context.Context, dto model.Stack) error + Delete(ctx context.Context, dto model.Stack) error GetKubeConfig(ctx context.Context, stackId domain.StackId) (kubeConfig string, err error) GetStepStatus(ctx context.Context, stackId domain.StackId) (out []domain.StackStepStatus, stackStatus string, err error) SetFavorite(ctx context.Context, stackId domain.StackId) error @@ -61,7 +62,7 @@ func NewStackUsecase(r repository.Repository, argoClient argowf.ArgoClient, dash } } -func (u *StackUsecase) Create(ctx context.Context, dto domain.Stack) (stackId domain.StackId, err error) { +func (u *StackUsecase) Create(ctx context.Context, dto model.Stack) (stackId domain.StackId, err error) { user, ok := request.UserFrom(ctx) if !ok { return "", httpErrors.NewUnauthorizedError(fmt.Errorf("Invalid token"), "A_INVALID_TOKEN", "") @@ -103,7 +104,7 @@ func (u *StackUsecase) Create(ctx context.Context, dto domain.Stack) (stackId do // Make stack nodes var stackConf domain.StackConfResponse - if err = domain.Map(dto.Conf, &stackConf); err != nil { + if err = serializer.Map(dto, &stackConf); err != nil { log.InfoWithContext(ctx, err) } if stackTemplate.CloudService == "AWS" && stackTemplate.KubeType == "AWS" { @@ -196,7 +197,7 @@ func (u *StackUsecase) Install(ctx context.Context, stackId domain.StackId) (err // Make stack nodes var stackConf domain.StackConfResponse - if err = domain.Map(cluster.Conf, &stackConf); err != nil { + if err = serializer.Map(cluster, &stackConf); err != nil { log.InfoWithContext(ctx, err) } @@ -221,7 +222,7 @@ func (u *StackUsecase) Install(ctx context.Context, stackId domain.StackId) (err return nil } -func (u *StackUsecase) Get(ctx context.Context, stackId domain.StackId) (out domain.Stack, err error) { +func (u *StackUsecase) Get(ctx context.Context, stackId domain.StackId) (out model.Stack, err error) { cluster, err := u.clusterRepo.Get(domain.ClusterId(stackId)) if err != nil { if errors.Is(err, gorm.ErrRecordNotFound) { @@ -275,7 +276,7 @@ func (u *StackUsecase) Get(ctx context.Context, stackId domain.StackId) (out dom return } -func (u *StackUsecase) GetByName(ctx context.Context, organizationId string, name string) (out domain.Stack, err error) { +func (u *StackUsecase) GetByName(ctx context.Context, organizationId string, name string) (out model.Stack, err error) { cluster, err := u.clusterRepo.GetByName(organizationId, name) if err != nil { if errors.Is(err, gorm.ErrRecordNotFound) { @@ -293,7 +294,7 @@ func (u *StackUsecase) GetByName(ctx context.Context, organizationId string, nam return } -func (u *StackUsecase) Fetch(ctx context.Context, organizationId string, pg *pagination.Pagination) (out []domain.Stack, err error) { +func (u *StackUsecase) Fetch(ctx context.Context, organizationId string, pg *pagination.Pagination) (out []model.Stack, err error) { user, ok := request.UserFrom(ctx) if !ok { return out, httpErrors.NewUnauthorizedError(fmt.Errorf("Invalid token"), "A_INVALID_TOKEN", "") @@ -352,7 +353,7 @@ func (u *StackUsecase) Fetch(ctx context.Context, organizationId string, pg *pag return } -func (u *StackUsecase) Update(ctx context.Context, dto domain.Stack) (err error) { +func (u *StackUsecase) Update(ctx context.Context, dto model.Stack) (err error) { user, ok := request.UserFrom(ctx) if !ok { return httpErrors.NewBadRequestError(fmt.Errorf("Invalid token"), "", "") @@ -364,7 +365,7 @@ func (u *StackUsecase) Update(ctx context.Context, dto domain.Stack) (err error) } updatorId := user.GetUserId() - dtoCluster := domain.Cluster{ + dtoCluster := model.Cluster{ ID: domain.ClusterId(dto.ID), Description: dto.Description, UpdatorId: &updatorId, @@ -378,7 +379,7 @@ func (u *StackUsecase) Update(ctx context.Context, dto domain.Stack) (err error) return nil } -func (u *StackUsecase) Delete(ctx context.Context, dto domain.Stack) (err error) { +func (u *StackUsecase) Delete(ctx context.Context, dto model.Stack) (err error) { user, ok := request.UserFrom(ctx) if !ok { return httpErrors.NewBadRequestError(fmt.Errorf("Invalid token"), "", "") @@ -617,7 +618,7 @@ func (u *StackUsecase) DeleteFavorite(ctx context.Context, stackId domain.StackI return nil } -func reflectClusterToStack(cluster domain.Cluster, appGroups []domain.AppGroup) (out domain.Stack) { +func reflectClusterToStack(cluster model.Cluster, appGroups []model.AppGroup) (out model.Stack) { if err := serializer.Map(cluster, &out); err != nil { log.Error(err) } @@ -629,7 +630,7 @@ func reflectClusterToStack(cluster domain.Cluster, appGroups []domain.AppGroup) out.StatusDesc = statusDesc /* - return domain.Stack{ + return model.Stack{ ID: domain.StackId(cluster.ID), OrganizationId: cluster.OrganizationId, Name: cluster.Name, @@ -663,7 +664,7 @@ func reflectClusterToStack(cluster domain.Cluster, appGroups []domain.AppGroup) } // [TODO] more pretty -func getStackStatus(cluster domain.Cluster, appGroups []domain.AppGroup) (domain.StackStatus, string) { +func getStackStatus(cluster model.Cluster, appGroups []model.AppGroup) (domain.StackStatus, string) { for _, appGroup := range appGroups { if appGroup.Status == domain.AppGroupStatus_PENDING && cluster.Status == domain.ClusterStatus_RUNNING { return domain.StackStatus_APPGROUP_INSTALLING, appGroup.StatusDesc diff --git a/internal/usecase/user.go b/internal/usecase/user.go index b851d2f5..0d3bd907 100644 --- a/internal/usecase/user.go +++ b/internal/usecase/user.go @@ -10,32 +10,32 @@ import ( "github.com/openinfradev/tks-api/internal/helper" "github.com/openinfradev/tks-api/internal/keycloak" "github.com/openinfradev/tks-api/internal/mail" + "github.com/openinfradev/tks-api/internal/model" "github.com/openinfradev/tks-api/internal/pagination" "github.com/openinfradev/tks-api/internal/repository" - "github.com/openinfradev/tks-api/pkg/domain" "github.com/openinfradev/tks-api/pkg/httpErrors" "github.com/openinfradev/tks-api/pkg/log" "github.com/pkg/errors" ) type IUserUsecase interface { - CreateAdmin(organizationId string, email string) (*domain.User, error) + CreateAdmin(organizationId string, email string) (*model.User, error) DeleteAdmin(organizationId string) error DeleteAll(ctx context.Context, organizationId string) error - Create(ctx context.Context, user *domain.User) (*domain.User, error) - List(ctx context.Context, organizationId string) (*[]domain.User, error) - ListWithPagination(ctx context.Context, organizationId string, pg *pagination.Pagination) (*[]domain.User, error) - Get(userId uuid.UUID) (*domain.User, error) - Update(ctx context.Context, userId uuid.UUID, user *domain.User) (*domain.User, error) + Create(ctx context.Context, user *model.User) (*model.User, error) + List(ctx context.Context, organizationId string) (*[]model.User, error) + ListWithPagination(ctx context.Context, organizationId string, pg *pagination.Pagination) (*[]model.User, error) + Get(userId uuid.UUID) (*model.User, error) + Update(ctx context.Context, userId uuid.UUID, user *model.User) (*model.User, error) ResetPassword(userId uuid.UUID) error ResetPasswordByAccountId(accountId string, organizationId string) error GenerateRandomPassword() string Delete(userId uuid.UUID, organizationId string) error - GetByAccountId(ctx context.Context, accountId string, organizationId string) (*domain.User, error) - GetByEmail(ctx context.Context, email string, organizationId string) (*domain.User, error) + GetByAccountId(ctx context.Context, accountId string, organizationId string) (*model.User, error) + GetByEmail(ctx context.Context, email string, organizationId string) (*model.User, error) SendEmailForTemporaryPassword(ctx context.Context, accountId string, organizationId string, password string) error - UpdateByAccountId(ctx context.Context, accountId string, user *domain.User) (*domain.User, error) + UpdateByAccountId(ctx context.Context, accountId string, user *model.User) (*model.User, error) UpdatePasswordByAccountId(ctx context.Context, accountId string, originPassword string, newPassword string, organizationId string) error RenewalPasswordExpiredTime(ctx context.Context, userId uuid.UUID) error RenewalPasswordExpiredTimeByAccountId(ctx context.Context, accountId string, organizationId string) error @@ -43,7 +43,7 @@ type IUserUsecase interface { ValidateAccount(userId uuid.UUID, password string, organizationId string) error ValidateAccountByAccountId(accountId string, password string, organizationId string) error - UpdateByAccountIdByAdmin(ctx context.Context, accountId string, user *domain.User) (*domain.User, error) + UpdateByAccountIdByAdmin(ctx context.Context, accountId string, user *model.User) (*model.User, error) } type UserUsecase struct { @@ -196,17 +196,17 @@ func (u *UserUsecase) DeleteAdmin(organizationId string) error { return nil } -func (u *UserUsecase) CreateAdmin(orgainzationId string, email string) (*domain.User, error) { +func (u *UserUsecase) CreateAdmin(orgainzationId string, email string) (*model.User, error) { // Generate Admin user object randomPassword := helper.GenerateRandomString(passwordLength) - user := domain.User{ + user := model.User{ AccountId: "admin", Password: randomPassword, Email: email, - Role: domain.Role{ + Role: model.Role{ Name: "admin", }, - Organization: domain.Organization{ + Organization: model.Organization{ ID: orgainzationId, }, Name: "admin", @@ -295,7 +295,7 @@ func (u *UserUsecase) UpdatePasswordByAccountId(ctx context.Context, accountId s return nil } -func (u *UserUsecase) List(ctx context.Context, organizationId string) (users *[]domain.User, err error) { +func (u *UserUsecase) List(ctx context.Context, organizationId string) (users *[]model.User, err error) { users, err = u.userRepository.List(u.userRepository.OrganizationFilter(organizationId)) if err != nil { return nil, err @@ -304,7 +304,7 @@ func (u *UserUsecase) List(ctx context.Context, organizationId string) (users *[ return } -func (u *UserUsecase) ListWithPagination(ctx context.Context, organizationId string, pg *pagination.Pagination) (users *[]domain.User, err error) { +func (u *UserUsecase) ListWithPagination(ctx context.Context, organizationId string, pg *pagination.Pagination) (users *[]model.User, err error) { users, err = u.userRepository.ListWithPagination(pg, organizationId) if err != nil { return nil, err @@ -313,7 +313,7 @@ func (u *UserUsecase) ListWithPagination(ctx context.Context, organizationId str return } -func (u *UserUsecase) Get(userId uuid.UUID) (*domain.User, error) { +func (u *UserUsecase) Get(userId uuid.UUID) (*model.User, error) { user, err := u.userRepository.GetByUuid(userId) if err != nil { if _, status := httpErrors.ErrorResponse(err); status == http.StatusNotFound { @@ -325,7 +325,7 @@ func (u *UserUsecase) Get(userId uuid.UUID) (*domain.User, error) { return &user, nil } -func (u *UserUsecase) GetByAccountId(ctx context.Context, accountId string, organizationId string) (*domain.User, error) { +func (u *UserUsecase) GetByAccountId(ctx context.Context, accountId string, organizationId string) (*model.User, error) { users, err := u.userRepository.List(u.userRepository.OrganizationFilter(organizationId), u.userRepository.AccountIdFilter(accountId)) if err != nil { @@ -335,7 +335,7 @@ func (u *UserUsecase) GetByAccountId(ctx context.Context, accountId string, orga return &(*users)[0], nil } -func (u *UserUsecase) GetByEmail(ctx context.Context, email string, organizationId string) (*domain.User, error) { +func (u *UserUsecase) GetByEmail(ctx context.Context, email string, organizationId string) (*model.User, error) { users, err := u.userRepository.List(u.userRepository.OrganizationFilter(organizationId), u.userRepository.EmailFilter(email)) if err != nil { @@ -345,7 +345,7 @@ func (u *UserUsecase) GetByEmail(ctx context.Context, email string, organization return &(*users)[0], nil } -func (u *UserUsecase) Update(ctx context.Context, userId uuid.UUID, user *domain.User) (*domain.User, error) { +func (u *UserUsecase) Update(ctx context.Context, userId uuid.UUID, user *model.User) (*model.User, error) { storedUser, err := u.Get(userId) if err != nil { return nil, err @@ -355,8 +355,8 @@ func (u *UserUsecase) Update(ctx context.Context, userId uuid.UUID, user *domain return u.UpdateByAccountId(ctx, storedUser.AccountId, user) } -func (u *UserUsecase) UpdateByAccountId(ctx context.Context, accountId string, user *domain.User) (*domain.User, error) { - var out domain.User +func (u *UserUsecase) UpdateByAccountId(ctx context.Context, accountId string, user *model.User) (*model.User, error) { + var out model.User originUser, err := u.kc.GetUser(user.Organization.ID, accountId) if err != nil { @@ -438,7 +438,7 @@ func (u *UserUsecase) DeleteByAccountId(ctx context.Context, accountId string, o return nil } -func (u *UserUsecase) Create(ctx context.Context, user *domain.User) (*domain.User, error) { +func (u *UserUsecase) Create(ctx context.Context, user *model.User) (*model.User, error) { // Create user in keycloak groups := []string{fmt.Sprintf("%s@%s", user.Role.Name, user.Organization.ID)} userUuidStr, err := u.kc.CreateUser(user.Organization.ID, &gocloak.User{ @@ -492,7 +492,7 @@ func (u *UserUsecase) Create(ctx context.Context, user *domain.User) (*domain.Us return &resUser, nil } -func (u *UserUsecase) UpdateByAccountIdByAdmin(ctx context.Context, accountId string, newUser *domain.User) (*domain.User, error) { +func (u *UserUsecase) UpdateByAccountIdByAdmin(ctx context.Context, accountId string, newUser *model.User) (*model.User, error) { deepCopyUser := *newUser user, err := u.UpdateByAccountId(ctx, accountId, &deepCopyUser) if err != nil { diff --git a/pkg/domain/admin/user.go b/pkg/domain/admin/user.go index 7d53a51e..0a9e6820 100644 --- a/pkg/domain/admin/user.go +++ b/pkg/domain/admin/user.go @@ -1,8 +1,9 @@ package admin import ( - "github.com/openinfradev/tks-api/pkg/domain" "time" + + "github.com/openinfradev/tks-api/pkg/domain" ) type CreateUserRequest struct { @@ -26,17 +27,17 @@ type ListUserResponse struct { type GetUserResponse struct { User struct { - ID string `json:"id"` - AccountId string `json:"accountId"` - Name string `json:"name"` - Role domain.Role `json:"role"` - Organization domain.Organization `json:"organization"` - Email string `json:"email"` - Department string `json:"department"` - Description string `json:"description"` - Creator string `json:"creator"` - CreatedAt time.Time `json:"createdAt"` - UpdatedAt time.Time `json:"updatedAt"` + ID string `json:"id"` + AccountId string `json:"accountId"` + Name string `json:"name"` + Role domain.RoleResponse `json:"role"` + Organization domain.OrganizationResponse `json:"organization"` + Email string `json:"email"` + Department string `json:"department"` + Description string `json:"description"` + Creator string `json:"creator"` + CreatedAt time.Time `json:"createdAt"` + UpdatedAt time.Time `json:"updatedAt"` } `json:"user"` } @@ -51,16 +52,16 @@ type UpdateUserRequest struct { type UpdateUserResponse struct { User struct { - ID string `json:"id"` - AccountId string `json:"accountId"` - Name string `json:"name"` - Role domain.Role `json:"role"` - Organization domain.Organization `json:"organization"` - Email string `json:"email"` - Department string `json:"department"` - Description string `json:"description"` - CreatedAt time.Time `json:"createdAt"` - UpdatedAt time.Time `json:"updatedAt"` + ID string `json:"id"` + AccountId string `json:"accountId"` + Name string `json:"name"` + Role domain.RoleResponse `json:"role"` + Organization domain.OrganizationResponse `json:"organization"` + Email string `json:"email"` + Department string `json:"department"` + Description string `json:"description"` + CreatedAt time.Time `json:"createdAt"` + UpdatedAt time.Time `json:"updatedAt"` } `json:"user"` } diff --git a/pkg/domain/alert.go b/pkg/domain/alert.go index 7201ef24..a60073bf 100644 --- a/pkg/domain/alert.go +++ b/pkg/domain/alert.go @@ -33,50 +33,6 @@ func (m AlertActionStatus) FromString(s string) AlertActionStatus { return AlertActionStatus_ERROR } -// 내부 -type Alert struct { - ID uuid.UUID - OrganizationId string - Organization Organization - Name string - Description string - Code string - Grade string - Message string - ClusterId ClusterId - Cluster Cluster - Node string - CheckPoint string - Summary string - GrafanaUrl string - FiredAt *time.Time - TakedAt *time.Time - ClosedAt *time.Time - TakedSec int - ProcessingSec int - Status AlertActionStatus - AlertActions []AlertAction - LastTaker User - RawData []byte - CreatorId *uuid.UUID - Creator User - UpdatorId *uuid.UUID - Updator User - CreatedAt time.Time - UpdatedAt time.Time -} - -type AlertAction struct { - ID uuid.UUID - AlertId uuid.UUID - Content string - Status AlertActionStatus - TakerId *uuid.UUID - Taker User - CreatedAt time.Time - UpdatedAt time.Time -} - type CreateAlertRequestAlert struct { Status string `json:"status"` GeneratorURL string `json:"generatorURL"` diff --git a/pkg/domain/app-group.go b/pkg/domain/app-group.go index d4e3211d..36dff144 100644 --- a/pkg/domain/app-group.go +++ b/pkg/domain/app-group.go @@ -114,33 +114,6 @@ func (m AppGroupType) FromString(s string) AppGroupType { return AppGroupType_UNSPECIFIED } -type AppGroup = struct { - ID AppGroupId - Name string - ClusterId ClusterId - AppGroupType AppGroupType - Description string - WorkflowId string - Status AppGroupStatus - StatusDesc string - CreatorId *uuid.UUID - Creator User - UpdatorId *uuid.UUID - Updator User - CreatedAt time.Time - UpdatedAt time.Time -} - -type Application = struct { - ID uuid.UUID - AppGroupId AppGroupId - Endpoint string - Metadata string - ApplicationType ApplicationType - CreatedAt time.Time - UpdatedAt time.Time -} - type AppGroupResponse = struct { ID AppGroupId `json:"id"` Name string `json:"name"` diff --git a/pkg/domain/app-serve-app.go b/pkg/domain/app-serve-app.go index 45239154..b1db60af 100644 --- a/pkg/domain/app-serve-app.go +++ b/pkg/domain/app-serve-app.go @@ -1,71 +1,56 @@ package domain -import ( - "time" - - "github.com/google/uuid" - "gorm.io/gorm" -) - -type AppServeApp struct { - ID string `gorm:"primarykey" json:"id,omitempty"` - Name string `gorm:"index" json:"name,omitempty"` // application name - Namespace string `json:"namespace,omitempty"` // application namespace - OrganizationId string `json:"organizationId,omitempty"` // contractId is a contract ID which this app belongs to - ProjectId string `json:"projectId,omitempty"` // project ID which this app belongs to - Type string `json:"type,omitempty"` // type (build/deploy/all) - AppType string `json:"appType,omitempty"` // appType (spring/springboot) - EndpointUrl string `json:"endpointUrl,omitempty"` // endpoint URL of deployed app - PreviewEndpointUrl string `json:"previewEndpointUrl,omitempty"` // preview svc endpoint URL in B/G deployment - TargetClusterId string `json:"targetClusterId,omitempty"` // target cluster to which the app is deployed - TargetClusterName string `gorm:"-:all" json:"targetClusterName,omitempty"` // target cluster name - Status string `gorm:"index" json:"status,omitempty"` // status is status of deployed app - GrafanaUrl string `json:"grafanaUrl,omitempty"` // grafana dashboard URL for deployed app - CreatedAt time.Time `gorm:"autoCreateTime:false" json:"createdAt" ` - UpdatedAt *time.Time `gorm:"autoUpdateTime:false" json:"updatedAt"` - DeletedAt *time.Time `json:"deletedAt"` - AppServeAppTasks []AppServeAppTask `gorm:"foreignKey:AppServeAppId" json:"appServeAppTasks"` -} - -type AppServeAppTask struct { - ID string `gorm:"primarykey" json:"id,omitempty"` - AppServeAppId string `gorm:"not null" json:"appServeAppId,omitempty"` // ID for appServeApp that this task belongs to - Version string `json:"version,omitempty"` // application version - Status string `json:"status,omitempty"` // status is app status - Output string `json:"output,omitempty"` // output for task result - ArtifactUrl string `json:"artifactUrl,omitempty"` // URL of java app artifact (Eg, Jar) - ImageUrl string `json:"imageUrl,omitempty"` // URL of built image for app - ExecutablePath string `json:"executablePath,omitempty"` // Executable path of app image - Profile string `json:"profile,omitempty"` // java app profile - AppConfig string `json:"appConfig,omitempty"` // java app config - AppSecret string `json:"appSecret,omitempty"` // java app secret - ExtraEnv string `json:"extraEnv,omitempty"` // env variable list for java app - Port string `json:"port,omitempty"` // java app port - ResourceSpec string `json:"resourceSpec,omitempty"` // resource spec of app pod - HelmRevision int32 `gorm:"default:0" json:"helmRevision,omitempty"` // revision of deployed helm release - Strategy string `json:"strategy,omitempty"` // deployment strategy (eg, rolling-update) - RollbackVersion string `json:"rollbackVersion,omitempty"` // rollback target version +import "time" + +type AppServeAppResponse struct { + ID string `json:"id,omitempty"` + Name string `json:"name,omitempty"` // application name + Namespace string `json:"namespace,omitempty"` // application namespace + OrganizationId string `json:"organizationId,omitempty"` // contractId is a contract ID which this app belongs to + ProjectId string `json:"projectId,omitempty"` // project ID which this app belongs to + Type string `json:"type,omitempty"` // type (build/deploy/all) + AppType string `json:"appType,omitempty"` // appType (spring/springboot) + EndpointUrl string `json:"endpointUrl,omitempty"` // endpoint URL of deployed app + PreviewEndpointUrl string `json:"previewEndpointUrl,omitempty"` // preview svc endpoint URL in B/G deployment + TargetClusterId string `json:"targetClusterId,omitempty"` // target cluster to which the app is deployed + TargetClusterName string `json:"targetClusterName,omitempty"` // target cluster name + Status string `json:"status,omitempty"` // status is status of deployed app + GrafanaUrl string `json:"grafanaUrl,omitempty"` // grafana dashboard URL for deployed app + CreatedAt time.Time `json:"createdAt" ` + UpdatedAt *time.Time `json:"updatedAt"` + DeletedAt *time.Time `json:"deletedAt"` + AppServeAppTasks []AppServeAppTaskResponse `json:"appServeAppTasks"` +} + +type AppServeAppTaskResponse struct { + ID string `json:"id,omitempty"` + AppServeAppId string `json:"appServeAppId,omitempty"` // ID for appServeApp that this task belongs to + Version string `json:"version,omitempty"` // application version + Status string `json:"status,omitempty"` // status is app status + Output string `json:"output,omitempty"` // output for task result + ArtifactUrl string `json:"artifactUrl,omitempty"` // URL of java app artifact (Eg, Jar) + ImageUrl string `json:"imageUrl,omitempty"` // URL of built image for app + ExecutablePath string `json:"executablePath,omitempty"` // Executable path of app image + Profile string `json:"profile,omitempty"` // java app profile + AppConfig string `json:"appConfig,omitempty"` // java app config + AppSecret string `json:"appSecret,omitempty"` // java app secret + ExtraEnv string `json:"extraEnv,omitempty"` // env variable list for java app + Port string `json:"port,omitempty"` // java app port + ResourceSpec string `json:"resourceSpec,omitempty"` // resource spec of app pod + HelmRevision int32 `json:"helmRevision,omitempty"` // revision of deployed helm release + Strategy string `json:"strategy,omitempty"` // deployment strategy (eg, rolling-update) + RollbackVersion string `json:"rollbackVersion,omitempty"` // rollback target version PvEnabled bool `json:"pvEnabled"` PvStorageClass string `json:"pvStorageClass"` PvAccessMode string `json:"pvAccessMode"` PvSize string `json:"pvSize"` PvMountPath string `json:"pvMountPath"` - AvailableRollback bool `gorm:"-:all" json:"availableRollback"` - CreatedAt time.Time `gorm:"autoCreateTime:false" json:"createdAt"` // createdAt is a creation timestamp for the application - UpdatedAt *time.Time `gorm:"autoUpdateTime:false" json:"updatedAt"` + AvailableRollback bool `json:"availableRollback"` + CreatedAt time.Time `json:"createdAt"` // createdAt is a creation timestamp for the application + UpdatedAt *time.Time `json:"updatedAt"` DeletedAt *time.Time `json:"deletedAt"` } -func (a *AppServeApp) BeforeCreate(tx *gorm.DB) (err error) { - a.ID = uuid.New().String() - return nil -} - -func (t *AppServeAppTask) BeforeCreate(tx *gorm.DB) (err error) { - t.ID = uuid.New().String() - return nil -} - type CreateAppServeAppRequest struct { // App Name string `json:"name" validate:"required,rfc1123,name"` @@ -158,25 +143,25 @@ type RollbackAppServeAppRequest struct { } type GetAppServeAppsResponse struct { - AppServeApps []AppServeApp `json:"appServeApps"` - Pagination PaginationResponse `json:"pagination"` + AppServeApps []AppServeAppResponse `json:"appServeApps"` + Pagination PaginationResponse `json:"pagination"` } // TODO: This will be deprecated later type GetAppServeAppResponse struct { - AppServeApp AppServeApp `json:"appServeApp"` - Stages []StageResponse `json:"stages"` + AppServeApp AppServeAppResponse `json:"appServeApp"` + Stages []StageResponse `json:"stages"` } type GetAppServeAppTasksResponse struct { - AppServeAppTasks []AppServeAppTask `json:"appServeAppTasks"` - Pagination PaginationResponse `json:"pagination"` + AppServeAppTasks []AppServeAppTaskResponse `json:"appServeAppTasks"` + Pagination PaginationResponse `json:"pagination"` } type GetAppServeAppTaskResponse struct { - AppServeApp AppServeApp `json:"appServeApp"` - AppServeAppTask AppServeAppTask `json:"appServeAppTask"` - Stages []StageResponse `json:"stages"` + AppServeApp AppServeAppResponse `json:"appServeApp"` + AppServeAppTask AppServeAppTaskResponse `json:"appServeAppTask"` + Stages []StageResponse `json:"stages"` } type StageResponse struct { diff --git a/pkg/domain/audit.go b/pkg/domain/audit.go index 9599ccae..6622aa40 100644 --- a/pkg/domain/audit.go +++ b/pkg/domain/audit.go @@ -2,25 +2,8 @@ package domain import ( "time" - - "github.com/google/uuid" ) -// 내부 -type Audit struct { - ID uuid.UUID - OrganizationId string - Organization Organization - Group string - Message string - Description string - ClientIP string - UserId *uuid.UUID - User User - CreatedAt time.Time - UpdatedAt time.Time -} - type AuditResponse struct { ID string `json:"id"` OrganizationId string `json:"organizationId"` @@ -29,7 +12,6 @@ type AuditResponse struct { Group string `json:"group"` Message string `json:"message"` ClientIP string `json:"clientIP"` - UserId string `json:"userId"` User SimpleUserResponse `json:"user"` CreatedAt time.Time `json:"createdAt"` UpdatedAt time.Time `json:"updatedAt"` diff --git a/pkg/domain/auth.go b/pkg/domain/auth.go index abab6f97..4dbaeeef 100644 --- a/pkg/domain/auth.go +++ b/pkg/domain/auth.go @@ -13,13 +13,13 @@ type PingTokenRequest struct { type LoginResponse struct { User struct { - AccountId string `json:"accountId"` - Name string `json:"name"` - Token string `json:"token"` - Role Role `json:"role"` - Department string `json:"department"` - Organization Organization `json:"organization"` - PasswordExpired bool `json:"passwordExpired"` + AccountId string `json:"accountId"` + Name string `json:"name"` + Token string `json:"token"` + Role RoleResponse `json:"role"` + Department string `json:"department"` + Organization OrganizationResponse `json:"organization"` + PasswordExpired bool `json:"passwordExpired"` } `json:"user"` } diff --git a/pkg/domain/cloud-account.go b/pkg/domain/cloud-account.go index 5e4720c8..591356ac 100644 --- a/pkg/domain/cloud-account.go +++ b/pkg/domain/cloud-account.go @@ -2,8 +2,6 @@ package domain import ( "time" - - "github.com/google/uuid" ) const CLOUD_ACCOUNT_INCLUSTER = "INCLUSTER" @@ -49,30 +47,6 @@ func (m CloudAccountStatus) FromString(s string) CloudAccountStatus { return CloudAccountStatus_PENDING } -// 내부 -type CloudAccount struct { - ID uuid.UUID - OrganizationId string - Name string - Description string - CloudService string - Resource string - Clusters int - AwsAccountId string - AccessKeyId string - SecretAccessKey string - SessionToken string - Status CloudAccountStatus - StatusDesc string - CreatedIAM bool - CreatorId uuid.UUID - Creator User - UpdatorId uuid.UUID - Updator User - CreatedAt time.Time - UpdatedAt time.Time -} - type ResourceQuotaAttr struct { Type string `json:"type"` Usage int `json:"usage"` @@ -157,3 +131,7 @@ type GetCloudAccountResourceQuotaResponse struct { Available bool `json:"available"` ResourceQuota ResourceQuota `json:"resourceQuota"` } + +type DeleteCloudAccountResponse struct { + ID string `json:"id"` +} diff --git a/pkg/domain/cluster.go b/pkg/domain/cluster.go index 6c2ea884..0d7c854b 100644 --- a/pkg/domain/cluster.go +++ b/pkg/domain/cluster.go @@ -3,7 +3,6 @@ package domain import ( "time" - "github.com/google/uuid" "github.com/openinfradev/tks-api/internal/helper" ) @@ -83,34 +82,6 @@ func (m ClusterType) FromString(s string) ClusterType { return ClusterType_USER } -// model -type Cluster struct { - ID ClusterId - CloudService string - OrganizationId string - Name string - Description string - CloudAccountId uuid.UUID - CloudAccount CloudAccount - StackTemplateId uuid.UUID - StackTemplate StackTemplate - Status ClusterStatus - StatusDesc string - Conf ClusterConf - Favorited bool - CreatorId *uuid.UUID - Creator User - ClusterType ClusterType - UpdatorId *uuid.UUID - Updator User - CreatedAt time.Time - UpdatedAt time.Time - ByoClusterEndpointHost string - ByoClusterEndpointPort int - IsStack bool - Kubeconfig []byte -} - type ClusterConf struct { TksCpNode int TksCpNodeMax int @@ -239,6 +210,7 @@ type ClusterResponse struct { ByoClusterEndpointHost string `json:"byoClusterEndpointHost,omitempty"` ByoClusterEndpointInt int `json:"byoClusterEndpointPort,omitempty"` IsStack bool `json:"isStack,omitempty"` + Favorited bool `json:"favorited,omitempty"` } type SimpleClusterResponse struct { diff --git a/pkg/domain/dashboard.go b/pkg/domain/dashboard.go index c7699fb7..6f3e18e2 100644 --- a/pkg/domain/dashboard.go +++ b/pkg/domain/dashboard.go @@ -37,14 +37,6 @@ func (m ChartType) FromString(s string) ChartType { return ChartType_ERROR } -// [TODO] -func (m ChartType) All() (out []string) { - for _, v := range chartType { - out = append(out, v) - } - return -} - // 내부 type DashboardChart struct { ChartType ChartType @@ -72,6 +64,14 @@ type DashboardStack struct { UpdatedAt time.Time } +// [TODO] +func (m ChartType) All() (out []string) { + for _, v := range chartType { + out = append(out, v) + } + return +} + type Unit struct { Name string `json:"name"` Data []string `json:"data"` diff --git a/pkg/domain/endpoint.go b/pkg/domain/endpoint.go index c34a45ae..e2a2127d 100644 --- a/pkg/domain/endpoint.go +++ b/pkg/domain/endpoint.go @@ -1,11 +1,10 @@ package domain -import ( - "time" -) +import "time" -type Endpoint struct { - Name string `gorm:"primary_key;type:text;not null;unique" json:"name"` - Group string `gorm:"type:text;" json:"group"` - CreatedAt time.Time +type EndpointResponse struct { + Name string `json:"name"` + Group string `json:"group"` + CreatedAt time.Time `json:"createdAt"` + UpdatedAt time.Time `json:"updatedAt"` } diff --git a/pkg/domain/mapper.go b/pkg/domain/mapper.go deleted file mode 100644 index e3fa80ac..00000000 --- a/pkg/domain/mapper.go +++ /dev/null @@ -1,140 +0,0 @@ -package domain - -import ( - "fmt" - "reflect" - - "github.com/google/uuid" - "github.com/openinfradev/tks-api/pkg/log" -) - -type ConverterMap map[compositeKey]func(interface{}) (interface{}, error) - -type compositeKey struct { - srcType reflect.Type - dstType reflect.Type -} - -func recursiveMap(src interface{}, dst interface{}, converterMap ConverterMap) error { - srcVal := reflect.ValueOf(src) - srcType := srcVal.Type() - - dstVal := reflect.ValueOf(dst) - if dstVal.Kind() != reflect.Ptr || dstVal.IsNil() { - return fmt.Errorf("dst must be a non-nil pointer") - } - dstElem := dstVal.Elem() - - for i := 0; i < srcVal.NumField(); i++ { - fieldName := srcType.Field(i).Name - srcField := srcVal.Field(i) - dstField := dstElem.FieldByName(fieldName) - - if dstField.IsValid() && dstField.CanSet() { - if dstField.Type() == srcField.Type() { - dstField.Set(srcField) - continue - } else if srcField.Type().Kind() == reflect.Struct && dstField.Type().Kind() == reflect.Struct { - if err := recursiveMap(srcField.Interface(), dstField.Addr().Interface(), converterMap); err != nil { - return err - } - } else { - converterKey := compositeKey{srcType: srcField.Type(), dstType: dstField.Type()} - if converter, ok := converterMap[converterKey]; ok { - if converted, err := converter(srcField.Interface()); err != nil { - return err - } else { - dstField.Set(reflect.ValueOf(converted)) - } - } else { - log.Debugf("no converter found for %s -> %s", srcField.Type(), dstField.Type()) - continue - } - } - - /* - else if srcField.Type().Kind() == reflect.Ptr && dstField.Type().Kind() == reflect.Ptr { - log.Info("AAA ", dstField.Type()) - ptr := reflect.New(dstField.Elem().Type()) - if err := recursiveMap(srcField.Elem().Interface(), ptr.Elem().Interface(), converterMap); err != nil { - return err - } - } - */ - - } - } - - return nil -} -func Map(src interface{}, dst interface{}) error { - return recursiveMap(src, dst, ConverterMap{ - {srcType: reflect.TypeOf((*uuid.UUID)(nil)).Elem(), dstType: reflect.TypeOf("")}: func(i interface{}) (interface{}, error) { - return i.(uuid.UUID).String(), nil - }, - {srcType: reflect.TypeOf(""), dstType: reflect.TypeOf((*uuid.UUID)(nil)).Elem()}: func(i interface{}) (interface{}, error) { - val, _ := uuid.Parse(i.(string)) - return val, nil - }, - {srcType: reflect.TypeOf((*OrganizationStatus)(nil)).Elem(), dstType: reflect.TypeOf("")}: func(i interface{}) (interface{}, error) { - return i.(OrganizationStatus).String(), nil - }, - {srcType: reflect.TypeOf(""), dstType: reflect.TypeOf((*OrganizationStatus)(nil)).Elem()}: func(i interface{}) (interface{}, error) { - return organizationStatusMap[i.(string)], nil - }, - {srcType: reflect.TypeOf((*Role)(nil)).Elem(), dstType: reflect.TypeOf("")}: func(i interface{}) (interface{}, error) { - return i.(Role).Name, nil - }, - {srcType: reflect.TypeOf(""), dstType: reflect.TypeOf((*Role)(nil)).Elem()}: func(i interface{}) (interface{}, error) { - return Role{Name: i.(string)}, nil - }, - {srcType: reflect.TypeOf((*ClusterStatus)(nil)).Elem(), dstType: reflect.TypeOf("")}: func(i interface{}) (interface{}, error) { - return i.(ClusterStatus).String(), nil - }, - {srcType: reflect.TypeOf(""), dstType: reflect.TypeOf((*ClusterStatus)(nil)).Elem()}: func(i interface{}) (interface{}, error) { - return new(ClusterStatus).FromString(i.(string)), nil - }, - {srcType: reflect.TypeOf((*AppGroupStatus)(nil)).Elem(), dstType: reflect.TypeOf("")}: func(i interface{}) (interface{}, error) { - return i.(AppGroupStatus).String(), nil - }, - {srcType: reflect.TypeOf(""), dstType: reflect.TypeOf((*AppGroupStatus)(nil)).Elem()}: func(i interface{}) (interface{}, error) { - return new(AppGroupStatus).FromString(i.(string)), nil - }, - {srcType: reflect.TypeOf((*AppGroupType)(nil)).Elem(), dstType: reflect.TypeOf("")}: func(i interface{}) (interface{}, error) { - return i.(AppGroupType).String(), nil - }, - {srcType: reflect.TypeOf(""), dstType: reflect.TypeOf((*AppGroupType)(nil)).Elem()}: func(i interface{}) (interface{}, error) { - return new(AppGroupType).FromString(i.(string)), nil - }, - {srcType: reflect.TypeOf((*StackStatus)(nil)).Elem(), dstType: reflect.TypeOf("")}: func(i interface{}) (interface{}, error) { - return i.(StackStatus).String(), nil - }, - {srcType: reflect.TypeOf(""), dstType: reflect.TypeOf((*StackStatus)(nil)).Elem()}: func(i interface{}) (interface{}, error) { - return new(StackStatus).FromString(i.(string)), nil - }, - {srcType: reflect.TypeOf((*ChartType)(nil)).Elem(), dstType: reflect.TypeOf("")}: func(i interface{}) (interface{}, error) { - return i.(ChartType).String(), nil - }, - {srcType: reflect.TypeOf(""), dstType: reflect.TypeOf((*ChartType)(nil)).Elem()}: func(i interface{}) (interface{}, error) { - return new(ChartType).FromString(i.(string)), nil - }, - {srcType: reflect.TypeOf((*AlertActionStatus)(nil)).Elem(), dstType: reflect.TypeOf("")}: func(i interface{}) (interface{}, error) { - return i.(AlertActionStatus).String(), nil - }, - {srcType: reflect.TypeOf(""), dstType: reflect.TypeOf((*AlertActionStatus)(nil)).Elem()}: func(i interface{}) (interface{}, error) { - return new(AlertActionStatus).FromString(i.(string)), nil - }, - {srcType: reflect.TypeOf((*ApplicationType)(nil)).Elem(), dstType: reflect.TypeOf("")}: func(i interface{}) (interface{}, error) { - return i.(ApplicationType).String(), nil - }, - {srcType: reflect.TypeOf(""), dstType: reflect.TypeOf((*ApplicationType)(nil)).Elem()}: func(i interface{}) (interface{}, error) { - return new(ApplicationType).FromString(i.(string)), nil - }, - {srcType: reflect.TypeOf((*CloudAccountStatus)(nil)).Elem(), dstType: reflect.TypeOf("")}: func(i interface{}) (interface{}, error) { - return i.(CloudAccountStatus).String(), nil - }, - {srcType: reflect.TypeOf(""), dstType: reflect.TypeOf((*CloudAccountStatus)(nil)).Elem()}: func(i interface{}) (interface{}, error) { - return new(CloudAccountStatus).FromString(i.(string)), nil - }, - }) -} diff --git a/pkg/domain/mapper_test.go b/pkg/domain/mapper_test.go deleted file mode 100644 index c235e360..00000000 --- a/pkg/domain/mapper_test.go +++ /dev/null @@ -1,117 +0,0 @@ -package domain - -import ( - "fmt" - "github.com/google/uuid" - "testing" - "time" -) - -// test case -func TestConvert(t *testing.T) { - type args struct { - src interface{} - dst interface{} - } - tests := []struct { - name string - args args - wantErr bool - }{ - { - name: "test case: CreateOrganizationRequest->Organization", - args: args{ - src: CreateOrganizationRequest{ - Name: "test", - Description: "test", - Phone: "test", - }, - dst: &Organization{}, - }, - wantErr: false, - }, - { - name: "test case Organization->CreateOrganizationResponse", - args: args{ - src: Organization{ - ID: "", - Name: "test", - Description: "test", - Phone: "test", - StatusDesc: "good", - Creator: "", - CreatedAt: time.Time{}, - UpdatedAt: time.Time{}, - }, - dst: &CreateOrganizationResponse{}, - }, - wantErr: false, - }, - { - name: "test case Organization->GetOrganizationResponse", - args: args{ - src: Organization{ - ID: "", - Name: "test", - Description: "test", - Phone: "test", - Status: OrganizationStatus_CREATE, - StatusDesc: "good", - Creator: "", - CreatedAt: time.Time{}, - UpdatedAt: time.Time{}, - }, - dst: &(&GetOrganizationResponse{}).Organization, - }, - wantErr: false, - }, - { - name: "test case CreateUserRequest->User", - args: args{ - src: CreateUserRequest{ - AccountId: "testAccount", - Password: "testPassword", - Name: "testName", - Email: "testEmail", - Department: "testDepartment", - Role: "testRole", - Description: "testDescription", - }, - dst: &User{}, - }, - wantErr: false, - }, - { - name: "test case User->GetUserResponse", - args: args{ - src: User{ - ID: uuid.New(), - AccountId: "testAccount", - Password: "testPassword", - Name: "testName", - Token: "testToken", - Role: Role{}, - Organization: Organization{}, - Creator: "", - CreatedAt: time.Time{}, - UpdatedAt: time.Time{}, - Email: "", - Department: "", - Description: "", - }, - dst: &GetUserResponse{}, - }, - wantErr: false, - }, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - if err := Map(tt.args.src, tt.args.dst); (err != nil) != tt.wantErr { - t.Errorf("Map() error = %v, wantErr %v", err, tt.wantErr) - } else { - fmt.Printf("Input: %+v\n", tt.args.src) - fmt.Printf("Output: %+v\n\n", tt.args.dst) - } - }) - } -} diff --git a/pkg/domain/organization.go b/pkg/domain/organization.go index fed0cfe9..efe7e5e3 100644 --- a/pkg/domain/organization.go +++ b/pkg/domain/organization.go @@ -2,8 +2,6 @@ package domain import ( "time" - - "gorm.io/gorm" ) // enum @@ -50,18 +48,14 @@ func (m OrganizationStatus) FromString(s string) OrganizationStatus { return OrganizationStatus_ERROR } -type Organization struct { - gorm.Model - - ID string `gorm:"primarykey;type:varchar(36);not null" json:"id"` +type OrganizationResponse struct { + ID string `json:"id"` Name string `json:"name"` Description string `json:"description"` Phone string `json:"phone"` PrimaryClusterId string `json:"primaryClusterId"` - WorkflowId string `json:"-"` Status OrganizationStatus `json:"status"` StatusDesc string `json:"statusDesc"` - Creator string `json:"creator"` CreatedAt time.Time `json:"createdAt"` UpdatedAt time.Time `json:"updatedAt"` } @@ -129,3 +123,7 @@ type UpdateOrganizationResponse struct { type UpdatePrimaryClusterRequest struct { PrimaryClusterId string `json:"primaryClusterId"` } + +type DeleteOrganizationResponse struct { + ID string `json:"id"` +} diff --git a/pkg/domain/permission.go b/pkg/domain/permission.go index ad95656e..f7b69f40 100644 --- a/pkg/domain/permission.go +++ b/pkg/domain/permission.go @@ -2,626 +2,37 @@ package domain import ( "github.com/google/uuid" - "github.com/openinfradev/tks-api/internal/delivery/api" - "github.com/openinfradev/tks-api/internal/helper" - "gorm.io/gorm" ) -type PermissionKind string - -const ( - DashBoardPermission PermissionKind = "대시보드" - StackPermission PermissionKind = "스택 관리" - SecurityPolicyPermission PermissionKind = "보안/정책 관리" - ProjectManagementPermission PermissionKind = "프로젝트 관리" - NotificationPermission PermissionKind = "알림" - ConfigurationPermission PermissionKind = "설정" -) - -type Permission struct { - gorm.Model - - ID uuid.UUID `gorm:"primarykey;type:uuid;" json:"ID"` - Name string `json:"name"` - - IsAllowed *bool `gorm:"type:boolean;" json:"is_allowed,omitempty"` - RoleID *string `json:"role_id,omitempty"` - Role *Role `gorm:"foreignKey:RoleID;references:ID;" json:"role,omitempty"` - Endpoints []*Endpoint `gorm:"many2many:permission_endpoints;" json:"endpoints,omitempty"` - // omit empty - - ParentID *uuid.UUID `json:"parent_id,omitempty"` - Parent *Permission `gorm:"foreignKey:ParentID;references:ID;" json:"parent,omitempty"` - Children []*Permission `gorm:"foreignKey:ParentID;references:ID;" json:"children,omitempty"` +type PermissionResponse struct { + ID uuid.UUID `json:"ID"` + Name string `json:"name"` + IsAllowed *bool `json:"is_allowed,omitempty"` + RoleID *string `json:"role_id,omitempty"` + Role *RoleResponse `json:"role,omitempty"` + Endpoints []*EndpointResponse `json:"endpoints,omitempty"` + ParentID *uuid.UUID `json:"parent_id,omitempty"` + Parent *PermissionResponse `json:"parent,omitempty"` + Children []*PermissionResponse `json:"children,omitempty"` } -func (p *Permission) BeforeCreate(tx *gorm.DB) (err error) { - if p.ID == uuid.Nil { - p.ID = uuid.New() - } - return nil -} - -type PermissionSet struct { - Dashboard *Permission `gorm:"-:all" json:"dashboard,omitempty"` - Stack *Permission `gorm:"-:all" json:"stack,omitempty"` - SecurityPolicy *Permission `gorm:"-:all" json:"security_policy,omitempty"` - ProjectManagement *Permission `gorm:"-:all" json:"project_management,omitempty"` - Notification *Permission `gorm:"-:all" json:"notification,omitempty"` - Configuration *Permission `gorm:"-:all" json:"configuration,omitempty"` -} - -func NewDefaultPermissionSet() *PermissionSet { - return &PermissionSet{ - Dashboard: newDashboard(), - Stack: newStack(), - SecurityPolicy: newSecurityPolicy(), - ProjectManagement: newProjectManagement(), - Notification: newNotification(), - Configuration: newConfiguration(), - } +type PermissionSetResponse struct { + Dashboard *PermissionResponse `json:"dashboard,omitempty"` + Stack *PermissionResponse `json:"stack,omitempty"` + SecurityPolicy *PermissionResponse `json:"security_policy,omitempty"` + ProjectManagement *PermissionResponse `json:"project_management,omitempty"` + Notification *PermissionResponse `json:"notification,omitempty"` + Configuration *PermissionResponse `json:"configuration,omitempty"` } type GetPermissionTemplatesResponse struct { - Permissions []*Permission `json:"permissions"` + Permissions []*PermissionResponse `json:"permissions"` } type GetPermissionsByRoleIdResponse struct { - Permissions []*Permission `json:"permissions"` + Permissions []*PermissionResponse `json:"permissions"` } type UpdatePermissionsByRoleIdRequest struct { - Permissions []*Permission `json:"permissions"` -} - -func GetEdgePermission(root *Permission, edgePermissions []*Permission, f *func(permission Permission) bool) []*Permission { - if root.Children == nil { - return append(edgePermissions, root) - } - - for _, child := range root.Children { - if f != nil && !(*f)(*child) { - continue - } - edgePermissions = GetEdgePermission(child, edgePermissions, f) - } - - return edgePermissions -} - -func SetRoleIDToPermission(roleID string, permission *Permission) { - permission.RoleID = helper.StringP(roleID) -} - -func endpointObjects(eps ...api.Endpoint) []*Endpoint { - var result []*Endpoint - for _, ep := range eps { - result = append(result, &Endpoint{ - Name: api.ApiMap[ep].Name, - Group: api.ApiMap[ep].Group, - }) - } - return result -} - -func newDashboard() *Permission { - dashboard := &Permission{ - Name: string(DashBoardPermission), - Children: []*Permission{ - { - Name: "대시보드", - Children: []*Permission{ - { - Name: "조회", - IsAllowed: helper.BoolP(false), - Endpoints: endpointObjects( - api.GetChartsDashboard, - api.GetChartDashboard, - api.GetStacksDashboard, - api.GetResourcesDashboard, - ), - }, - }, - }, - { - Name: "대시보드 설정", - Children: []*Permission{ - { - Name: "조회", - IsAllowed: helper.BoolP(false), - }, - { - Name: "생성", - IsAllowed: helper.BoolP(false), - }, - { - Name: "수정", - IsAllowed: helper.BoolP(false), - }, - { - Name: "삭제", - IsAllowed: helper.BoolP(false), - }, - }, - }, - }, - } - - return dashboard -} - -func newStack() *Permission { - stack := &Permission{ - Name: string(StackPermission), - Children: []*Permission{ - { - Name: "조회", - IsAllowed: helper.BoolP(false), - Endpoints: endpointObjects( - api.GetStacks, - api.GetStack, - api.CheckStackName, - api.GetStackStatus, - api.GetStackKubeConfig, - - api.SetFavoriteStack, - api.DeleteFavoriteStack, - ), - }, - { - Name: "생성", - IsAllowed: helper.BoolP(false), - Endpoints: endpointObjects( - api.CreateStack, - api.InstallStack, - ), - }, - { - Name: "수정", - IsAllowed: helper.BoolP(false), - Endpoints: endpointObjects( - api.UpdateStack, - ), - }, - { - Name: "삭제", - IsAllowed: helper.BoolP(false), - Endpoints: endpointObjects( - api.DeleteStack, - ), - }, - }, - } - - return stack -} - -func newSecurityPolicy() *Permission { - security_policy := &Permission{ - Name: string(SecurityPolicyPermission), - Children: []*Permission{ - { - Name: "보안/정책", - Children: []*Permission{ - { - Name: "조회", - IsAllowed: helper.BoolP(false), - }, - { - Name: "생성", - IsAllowed: helper.BoolP(false), - }, - { - Name: "수정", - IsAllowed: helper.BoolP(false), - }, - { - Name: "삭제", - IsAllowed: helper.BoolP(false), - }, - }, - }, - }, - } - - return security_policy -} - -func newProjectManagement() *Permission { - projectManagement := &Permission{ - Name: string(ProjectManagementPermission), - Children: []*Permission{ - { - Name: "프로젝트", - Children: []*Permission{ - { - Name: "조회", - IsAllowed: helper.BoolP(false), - Endpoints: endpointObjects( - api.GetProjects, - api.GetProject, - ), - }, - { - Name: "생성", - IsAllowed: helper.BoolP(false), - Endpoints: endpointObjects( - api.CreateProject, - ), - }, - }, - }, - { - Name: "앱 서빙", - Children: []*Permission{ - { - Name: "조회", - IsAllowed: helper.BoolP(false), - Endpoints: endpointObjects( - api.GetAppServeApps, - api.GetAppServeApp, - api.GetNumOfAppsOnStack, - api.GetAppServeAppLatestTask, - api.IsAppServeAppExist, - api.IsAppServeAppNameExist, - ), - }, - { - Name: "빌드", - IsAllowed: helper.BoolP(false), - Endpoints: endpointObjects( - api.CreateAppServeApp, - api.IsAppServeAppExist, - api.IsAppServeAppNameExist, - api.UpdateAppServeApp, - api.UpdateAppServeAppEndpoint, - api.UpdateAppServeAppStatus, - api.RollbackAppServeApp, - ), - }, - { - Name: "배포", - IsAllowed: helper.BoolP(false), - Endpoints: endpointObjects( - api.CreateAppServeApp, - api.IsAppServeAppExist, - api.IsAppServeAppNameExist, - api.UpdateAppServeApp, - api.UpdateAppServeAppEndpoint, - api.UpdateAppServeAppStatus, - api.RollbackAppServeApp, - ), - }, - { - Name: "삭제", - IsAllowed: helper.BoolP(false), - Endpoints: endpointObjects( - api.DeleteAppServeApp, - ), - }, - }, - }, - { - Name: "설정-일반", - Children: []*Permission{ - { - Name: "조회", - IsAllowed: helper.BoolP(false), - Endpoints: endpointObjects( - api.GetProjects, - api.GetProject, - - api.GetProjectRoles, - api.GetProjectRole, - ), - }, - { - Name: "수정", - IsAllowed: helper.BoolP(false), - Endpoints: endpointObjects( - api.UpdateProject, - ), - }, - { - Name: "삭제", - IsAllowed: helper.BoolP(false), - Endpoints: endpointObjects( - api.DeleteProject, - ), - }, - }, - }, - { - Name: "설정-멤버", - Children: []*Permission{ - { - Name: "조회", - IsAllowed: helper.BoolP(false), - Endpoints: endpointObjects( - api.GetProjectMembers, - api.GetProjectMember, - api.GetProjectRoles, - api.GetProjectRole, - ), - }, - { - Name: "생성", - IsAllowed: helper.BoolP(false), - Endpoints: endpointObjects( - api.AddProjectMember, - ), - }, - { - Name: "수정", - IsAllowed: helper.BoolP(false), - Endpoints: endpointObjects( - api.UpdateProjectMemberRole, - ), - }, - { - Name: "삭제", - IsAllowed: helper.BoolP(false), - Endpoints: endpointObjects( - api.RemoveProjectMember, - ), - }, - }, - }, - { - Name: "설정-네임스페이스", - Children: []*Permission{ - { - Name: "조회", - IsAllowed: helper.BoolP(false), - Endpoints: endpointObjects( - api.GetProjectNamespaces, - api.GetProjectNamespace, - ), - }, - { - Name: "생성", - IsAllowed: helper.BoolP(false), - Endpoints: endpointObjects( - api.CreateProjectNamespace, - ), - }, - { - Name: "수정", - IsAllowed: helper.BoolP(false), - Endpoints: endpointObjects(), - }, - { - Name: "삭제", - IsAllowed: helper.BoolP(false), - Endpoints: endpointObjects( - api.DeleteProjectNamespace, - ), - }, - }, - }, - }, - } - - return projectManagement -} - -func newNotification() *Permission { - notification := &Permission{ - Name: string(NotificationPermission), - Children: []*Permission{ - { - Name: "시스템 경고", - Children: []*Permission{ - { - Name: "조회", - IsAllowed: helper.BoolP(false), - }, - }, - }, - { - Name: "보안/정책 감사로그", - Children: []*Permission{ - { - Name: "조회", - IsAllowed: helper.BoolP(false), - }, - }, - }, - }, - } - - return notification -} - -func newConfiguration() *Permission { - configuration := &Permission{ - Name: string(ConfigurationPermission), - Children: []*Permission{ - { - Name: "일반", - Children: []*Permission{ - { - Name: "조회", - IsAllowed: helper.BoolP(false), - }, - { - Name: "수정", - IsAllowed: helper.BoolP(false), - }, - }, - }, - { - Name: "클라우드 계정", - Children: []*Permission{ - { - Name: "조회", - IsAllowed: helper.BoolP(false), - }, - { - Name: "생성", - IsAllowed: helper.BoolP(false), - }, - { - Name: "수정", - IsAllowed: helper.BoolP(false), - }, - { - Name: "삭제", - IsAllowed: helper.BoolP(false), - }, - }, - }, - { - Name: "스택 템플릿", - Children: []*Permission{ - { - Name: "조회", - IsAllowed: helper.BoolP(false), - }, - }, - }, - { - Name: "프로젝트 관리", - Children: []*Permission{ - { - Name: "조회", - IsAllowed: helper.BoolP(false), - }, - { - Name: "생성", - IsAllowed: helper.BoolP(false), - }, - { - Name: "수정", - IsAllowed: helper.BoolP(false), - }, - { - Name: "삭제", - IsAllowed: helper.BoolP(false), - }, - }, - }, - { - Name: "사용자", - Children: []*Permission{ - { - Name: "조회", - IsAllowed: helper.BoolP(false), - }, - { - Name: "생성", - IsAllowed: helper.BoolP(false), - }, - { - Name: "수정", - IsAllowed: helper.BoolP(false), - }, - { - Name: "삭제", - IsAllowed: helper.BoolP(false), - }, - }, - }, - { - Name: "사용자 권한 관리", - Children: []*Permission{ - { - Name: "조회", - IsAllowed: helper.BoolP(false), - }, - { - Name: "생성", - IsAllowed: helper.BoolP(false), - }, - { - Name: "수정", - IsAllowed: helper.BoolP(false), - }, - { - Name: "삭제", - IsAllowed: helper.BoolP(false), - }, - }, - }, - { - Name: "알림 설정", - Children: []*Permission{ - { - Name: "조회", - IsAllowed: helper.BoolP(false), - }, - { - Name: "생성", - IsAllowed: helper.BoolP(false), - }, - { - Name: "수정", - IsAllowed: helper.BoolP(false), - }, - { - Name: "삭제", - IsAllowed: helper.BoolP(false), - }, - }, - }, - }, - } - - return configuration -} - -func (p *PermissionSet) SetAllowedPermissionSet() { - edgePermissions := make([]*Permission, 0) - edgePermissions = append(edgePermissions, GetEdgePermission(p.Dashboard, edgePermissions, nil)...) - edgePermissions = append(edgePermissions, GetEdgePermission(p.Stack, edgePermissions, nil)...) - edgePermissions = append(edgePermissions, GetEdgePermission(p.SecurityPolicy, edgePermissions, nil)...) - edgePermissions = append(edgePermissions, GetEdgePermission(p.ProjectManagement, edgePermissions, nil)...) - edgePermissions = append(edgePermissions, GetEdgePermission(p.Notification, edgePermissions, nil)...) - edgePermissions = append(edgePermissions, GetEdgePermission(p.Configuration, edgePermissions, nil)...) - - for _, permission := range edgePermissions { - permission.IsAllowed = helper.BoolP(true) - } - - return -} - -func (p *PermissionSet) SetUserPermissionSet() { - f := func(permission Permission) bool { - return permission.Name == "조회" - } - edgePermissions := make([]*Permission, 0) - edgePermissions = append(edgePermissions, GetEdgePermission(p.Dashboard, edgePermissions, nil)...) - edgePermissions = append(edgePermissions, GetEdgePermission(p.Stack, edgePermissions, &f)...) - edgePermissions = append(edgePermissions, GetEdgePermission(p.SecurityPolicy, edgePermissions, &f)...) - edgePermissions = append(edgePermissions, GetEdgePermission(p.ProjectManagement, edgePermissions, &f)...) - edgePermissions = append(edgePermissions, GetEdgePermission(p.Notification, edgePermissions, &f)...) - //edgePermissions = append(edgePermissions, GetEdgePermission(p.Configuration, edgePermissions, &f)...) - - for _, permission := range edgePermissions { - permission.IsAllowed = helper.BoolP(true) - } - - return -} - -func (p *PermissionSet) SetRoleId(roleId string) { - setRoleIdToPermission(p.Dashboard, roleId) - setRoleIdToPermission(p.Stack, roleId) - setRoleIdToPermission(p.SecurityPolicy, roleId) - setRoleIdToPermission(p.ProjectManagement, roleId) - setRoleIdToPermission(p.Notification, roleId) - setRoleIdToPermission(p.Configuration, roleId) -} - -func setRoleIdToPermission(root *Permission, roleId string) { - root.RoleID = helper.StringP(roleId) - - if root.Children == nil { - return - } - - for _, child := range root.Children { - setRoleIdToPermission(child, roleId) - } + Permissions []*PermissionResponse `json:"permissions"` } diff --git a/pkg/domain/policy-template.go b/pkg/domain/policy-template.go index baf8990f..e2dd0810 100644 --- a/pkg/domain/policy-template.go +++ b/pkg/domain/policy-template.go @@ -73,6 +73,7 @@ type PolicyTemplateResponse struct { PermittedOrganizations []PermittedOrganization `json:"permittedOrganizations"` } +/* type PolicyTemplate struct { ID PolicyTemplateId Type string @@ -97,6 +98,7 @@ type PolicyTemplate struct { PermittedOrganizationIds []string // 생성 시에만 사용 PermittedOrganizations []PermittedOrganization } +*/ type CreateCommonPolicyTemplateRequest struct { TemplateName string `json:"templateName" example:"필수 Label 검사" validate:"name"` diff --git a/pkg/domain/project.go b/pkg/domain/project.go index 1007dd27..b63d6036 100644 --- a/pkg/domain/project.go +++ b/pkg/domain/project.go @@ -3,17 +3,18 @@ package domain import "time" type ProjectResponse struct { - ID string `json:"id"` - OrganizationId string `json:"organizationId"` - Name string `json:"name"` - Description string `json:"description"` - IsMyProject string `json:"isMyProject"` - ProjectRoleId string `json:"projectRoleId"` - ProjectRoleName string `json:"projectRoleName"` - NamespaceCount int `json:"namespaceCount"` - AppCount int `json:"appCount"` - MemberCount int `json:"memberCount"` - CreatedAt time.Time `json:"createdAt"` + ID string `json:"id"` + OrganizationId string `json:"organizationId"` + Name string `json:"name"` + Description string `json:"description"` + IsMyProject string `json:"isMyProject"` + ProjectRoleId string `json:"projectRoleId"` + ProjectRoleName string `json:"projectRoleName"` + NamespaceCount int `json:"namespaceCount"` + AppCount int `json:"appCount"` + MemberCount int `json:"memberCount"` + CreatedAt time.Time `json:"createdAt"` + UpdatedAt *time.Time `json:"updatedAt"` } type GetProjectsResponse struct { diff --git a/pkg/domain/role.go b/pkg/domain/role.go index e177a76a..ab961b26 100644 --- a/pkg/domain/role.go +++ b/pkg/domain/role.go @@ -4,7 +4,6 @@ import ( "time" "github.com/google/uuid" - "gorm.io/gorm" ) type RoleType string @@ -15,23 +14,23 @@ const ( RoleTypeProject RoleType = "project" ) -func (r *Role) BeforeCreate(tx *gorm.DB) (err error) { - r.ID = uuid.New().String() - return nil +type RoleResponse struct { + ID string `json:"id"` + Name string `json:"name"` + OrganizationID string `json:"organizationId"` + Organization OrganizationResponse `json:"organization"` + Type string `json:"type"` + Description string `json:"description"` + Creator uuid.UUID `json:"creator"` + CreatedAt time.Time `json:"createdAt"` + UpdatedAt time.Time `json:"updatedAt"` } -type Role struct { - gorm.Model - - ID string `gorm:"primarykey;" json:"id"` - Name string `json:"name"` - OrganizationID string `json:"organizationId"` - Organization Organization `gorm:"foreignKey:OrganizationID;references:ID;" json:"organization"` - Type string `json:"type"` - Description string `json:"description"` - Creator uuid.UUID `json:"creator"` - CreatedAt time.Time `json:"createdAt"` - UpdatedAt time.Time `json:"updatedAt"` +type SimpleRoleResponse = struct { + ID string `json:"id"` + Name string `json:"name"` + Description string `json:"description"` + OrganizationID string `json:"organizationId"` } type CreateTksRoleRequest struct { diff --git a/pkg/domain/stack-template.go b/pkg/domain/stack-template.go index 13b6e9da..122410d1 100644 --- a/pkg/domain/stack-template.go +++ b/pkg/domain/stack-template.go @@ -2,38 +2,11 @@ package domain import ( "time" - - "github.com/google/uuid" ) const STACK_TEMPLATE_TYPE_STANDARD = "STANDARD" const STACK_TEMPLATE_TYPE_MSA = "MSA" -// 내부 -type StackTemplate struct { - ID uuid.UUID - OrganizationId string - Name string - Description string - Template string - TemplateType string - CloudService string - Version string - Platform string - KubeVersion string - KubeType string - OrganizationIds []string - Organizations []Organization - ServiceIds []string - Services []byte - CreatorId uuid.UUID - Creator User - UpdatorId uuid.UUID - Updator User - CreatedAt time.Time - UpdatedAt time.Time -} - type StackTemplateServiceApplicationResponse struct { Name string `json:"name"` Description string `json:"description"` diff --git a/pkg/domain/stack.go b/pkg/domain/stack.go index b4935bcb..c56abc48 100644 --- a/pkg/domain/stack.go +++ b/pkg/domain/stack.go @@ -3,7 +3,6 @@ package domain import ( "time" - "github.com/google/uuid" "github.com/openinfradev/tks-api/internal/helper" ) @@ -74,45 +73,6 @@ const MAX_STEP_LMA_REMOVE = 12 const MAX_STEP_SM_CREATE = 22 const MAX_STEP_SM_REMOVE = 4 -// model -type Stack = struct { - ID StackId - Name string - Description string - ClusterId string - OrganizationId string - CloudService string - CloudAccountId uuid.UUID - CloudAccount CloudAccount - StackTemplateId uuid.UUID - StackTemplate StackTemplate - Status StackStatus - StatusDesc string - Conf StackConf - PrimaryCluster bool - GrafanaUrl string - CreatorId *uuid.UUID - Creator User - UpdatorId *uuid.UUID - Updator User - CreatedAt time.Time - UpdatedAt time.Time - Favorited bool - ClusterEndpoint string - Resource DashboardStackResponse -} - -type StackConf struct { - TksCpNode int - TksCpNodeMax int - TksCpNodeType string - TksInfraNode int - TksInfraNodeMax int - TksInfraNodeType string - TksUserNode int - TksUserNodeMax int - TksUserNodeType string -} type StackStepStatus struct { Status string `json:"status"` Stage string `json:"stage"` @@ -176,6 +136,19 @@ type StackResponse struct { UpdatedAt time.Time `json:"updatedAt"` } +type SimpleStackResponse struct { + ID StackId `json:"id"` + Name string `json:"name"` + Description string `json:"description"` + OrganizationId string `json:"organizationId"` + StackTemplate SimpleStackTemplateResponse `json:"stackTemplate,omitempty"` + CloudAccount SimpleCloudAccountResponse `json:"cloudAccount,omitempty"` + Status string `json:"status"` + PrimaryCluster bool `json:"primaryCluster"` + CreatedAt time.Time `json:"createdAt"` + UpdatedAt time.Time `json:"updatedAt"` +} + type GetStacksResponse struct { Stacks []StackResponse `json:"stacks"` Pagination PaginationResponse `json:"pagination"` diff --git a/pkg/domain/user.go b/pkg/domain/user.go index d63b4605..a4833494 100644 --- a/pkg/domain/user.go +++ b/pkg/domain/user.go @@ -1,55 +1,49 @@ package domain import ( - "github.com/google/uuid" - "gorm.io/gorm" "time" + + "github.com/google/uuid" ) -type User struct { +// // Deprecated: Policy is deprecated, use Permission instead. +// +// type Policy = struct { +// ID string `json:"id"` +// Name string `json:"name"` +// Create bool `json:"create"` +// CreatePriviledge string `json:"createPriviledge"` +// Update bool `json:"update"` +// UpdatePriviledge string `json:"updatePriviledge"` +// Read bool `json:"read"` +// ReadPriviledge string `json:"readPriviledge"` +// Delete bool `json:"delete"` +// DeletePriviledge string `json:"deletePriviledge"` +// Creator string `json:"creator"` +// CreatedAt time.Time `json:"createdAt"` +// UpdatedAt time.Time `json:"updatedAt"` +// } +type UserResponse struct { ID uuid.UUID `gorm:"primarykey;type:uuid" json:"id"` AccountId string `json:"accountId"` Password string `gorm:"-:all" json:"password"` Name string `json:"name"` Token string `json:"token"` RoleId string - Role Role `gorm:"foreignKey:RoleId;references:ID" json:"role"` + Role RoleResponse `gorm:"foreignKey:RoleId;references:ID" json:"role"` OrganizationId string - Organization Organization `gorm:"foreignKey:OrganizationId;references:ID" json:"organization"` - Creator string `json:"creator"` - CreatedAt time.Time `json:"createdAt"` - UpdatedAt time.Time `json:"updatedAt"` - PasswordUpdatedAt time.Time `json:"passwordUpdatedAt"` - PasswordExpired bool `json:"passwordExpired"` + Organization OrganizationResponse `gorm:"foreignKey:OrganizationId;references:ID" json:"organization"` + Creator string `json:"creator"` + CreatedAt time.Time `json:"createdAt"` + UpdatedAt time.Time `json:"updatedAt"` + PasswordUpdatedAt time.Time `json:"passwordUpdatedAt"` + PasswordExpired bool `json:"passwordExpired"` Email string `json:"email"` Department string `json:"department"` Description string `json:"description"` } -func (g *User) BeforeCreate(tx *gorm.DB) (err error) { - g.PasswordUpdatedAt = time.Now() - return nil -} - -// -//// Deprecated: Policy is deprecated, use Permission instead. -//type Policy = struct { -// ID string `json:"id"` -// Name string `json:"name"` -// Create bool `json:"create"` -// CreatePriviledge string `json:"createPriviledge"` -// Update bool `json:"update"` -// UpdatePriviledge string `json:"updatePriviledge"` -// Read bool `json:"read"` -// ReadPriviledge string `json:"readPriviledge"` -// Delete bool `json:"delete"` -// DeletePriviledge string `json:"deletePriviledge"` -// Creator string `json:"creator"` -// CreatedAt time.Time `json:"createdAt"` -// UpdatedAt time.Time `json:"updatedAt"` -//} - type CreateUserRequest struct { AccountId string `json:"accountId" validate:"required"` Password string `json:"password" validate:"required"` @@ -60,45 +54,38 @@ type CreateUserRequest struct { Description string `json:"description" validate:"min=0,max=100"` } -type SimpleRoleResponse = struct { - ID string `json:"id"` - Name string `json:"name"` - Description string `json:"description"` -} - type SimpleUserResponse struct { - ID string `json:"id"` - AccountId string `json:"accountId"` - Name string `json:"name"` - Role SimpleRoleResponse `json:"role"` + ID string `json:"id"` + AccountId string `json:"accountId"` + Name string `json:"name"` } type CreateUserResponse struct { User struct { - ID string `json:"id"` - AccountId string `json:"accountId"` - Name string `json:"name"` - Role Role `json:"role"` - Organization Organization `json:"organization"` - Email string `json:"email"` - Department string `json:"department"` - Description string `json:"description"` + ID string `json:"id"` + AccountId string `json:"accountId"` + Name string `json:"name"` + Role RoleResponse `json:"role"` + Organization OrganizationResponse `json:"organization"` + Email string `json:"email"` + Department string `json:"department"` + Description string `json:"description"` } `json:"user"` } type GetUserResponse struct { User struct { - ID string `json:"id"` - AccountId string `json:"accountId"` - Name string `json:"name"` - Role Role `json:"role"` - Organization Organization `json:"organization"` - Email string `json:"email"` - Department string `json:"department"` - Description string `json:"description"` - Creator string `json:"creator"` - CreatedAt time.Time `json:"createdAt"` - UpdatedAt time.Time `json:"updatedAt"` + ID string `json:"id"` + AccountId string `json:"accountId"` + Name string `json:"name"` + Role RoleResponse `json:"role"` + Organization OrganizationResponse `json:"organization"` + Email string `json:"email"` + Department string `json:"department"` + Description string `json:"description"` + Creator string `json:"creator"` + CreatedAt time.Time `json:"createdAt"` + UpdatedAt time.Time `json:"updatedAt"` } `json:"user"` } @@ -107,17 +94,17 @@ type ListUserResponse struct { Pagination PaginationResponse `json:"pagination"` } type ListUserBody struct { - ID string `json:"id"` - AccountId string `json:"accountId"` - Name string `json:"name"` - Role Role `json:"role"` - Organization Organization `json:"organization"` - Email string `json:"email"` - Department string `json:"department"` - Description string `json:"description"` - Creator string `json:"creator"` - CreatedAt time.Time `json:"createdAt"` - UpdatedAt time.Time `json:"updatedAt"` + ID string `json:"id"` + AccountId string `json:"accountId"` + Name string `json:"name"` + Role RoleResponse `json:"role"` + Organization OrganizationResponse `json:"organization"` + Email string `json:"email"` + Department string `json:"department"` + Description string `json:"description"` + Creator string `json:"creator"` + CreatedAt time.Time `json:"createdAt"` + UpdatedAt time.Time `json:"updatedAt"` } type UpdateUserRequest struct { @@ -130,28 +117,28 @@ type UpdateUserRequest struct { type UpdateUserResponse struct { User struct { - ID string `json:"id"` - AccountId string `json:"accountId"` - Name string `json:"name"` - Role Role `json:"role"` - Organization Organization `json:"organization"` - Email string `json:"email"` - Department string `json:"department"` - Description string `json:"description"` - CreatedAt time.Time `json:"createdAt"` - UpdatedAt time.Time `json:"updatedAt"` + ID string `json:"id"` + AccountId string `json:"accountId"` + Name string `json:"name"` + Role RoleResponse `json:"role"` + Organization OrganizationResponse `json:"organization"` + Email string `json:"email"` + Department string `json:"department"` + Description string `json:"description"` + CreatedAt time.Time `json:"createdAt"` + UpdatedAt time.Time `json:"updatedAt"` } `json:"user"` } type GetMyProfileResponse struct { User struct { - ID string `json:"id"` - AccountId string `json:"accountId"` - Name string `json:"name"` - Role Role `json:"role"` - Organization Organization `json:"organization"` - Email string `json:"email"` - Department string `json:"department"` + ID string `json:"id"` + AccountId string `json:"accountId"` + Name string `json:"name"` + Role RoleResponse `json:"role"` + Organization OrganizationResponse `json:"organization"` + Email string `json:"email"` + Department string `json:"department"` } `json:"user"` } type UpdateMyProfileRequest struct { @@ -163,13 +150,13 @@ type UpdateMyProfileRequest struct { type UpdateMyProfileResponse struct { User struct { - ID string `json:"id"` - AccountId string `json:"accountId"` - Name string `json:"name"` - Role Role `json:"role"` - Organization Organization `json:"organization"` - Email string `json:"email"` - Department string `json:"department"` + ID string `json:"id"` + AccountId string `json:"accountId"` + Name string `json:"name"` + Role RoleResponse `json:"role"` + Organization OrganizationResponse `json:"organization"` + Email string `json:"email"` + Department string `json:"department"` } `json:"user"` }