From bde599db77d00b1b5fca0d8367ce24044c396579 Mon Sep 17 00:00:00 2001 From: donggyu Date: Fri, 8 Mar 2024 11:16:35 +0900 Subject: [PATCH 01/11] remove unused files --- internal/usecase/role_test.go | 217 ---------------------------------- 1 file changed, 217 deletions(-) delete mode 100644 internal/usecase/role_test.go diff --git a/internal/usecase/role_test.go b/internal/usecase/role_test.go deleted file mode 100644 index a0b47c5b..00000000 --- a/internal/usecase/role_test.go +++ /dev/null @@ -1,217 +0,0 @@ -package usecase_test - -import ( - "fmt" - "gorm_test/config" - "testing" - - "github.com/google/uuid" - myRepository "github.com/openinfradev/tks-api/internal/repository" - "github.com/openinfradev/tks-api/internal/usecase" - "gorm.io/driver/postgres" - "gorm.io/gorm" -) - -func TestNewRoleUsecase(t *testing.T) { - conf := config.NewDefaultConfig() - dsn := fmt.Sprintf( - "host=%s dbname=%s user=%s password=%s port=%d sslmode=disable TimeZone=Asia/Seoul", - conf.Address, conf.Database, conf.AdminId, conf.AdminPassword, conf.Port, - ) - - t.Logf("dsn: %s", dsn) - - db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{}) - if err != nil { - panic(err) - } - - if err = db.AutoMigrate(&myRepository.Organization{}); err != nil { - panic(err) - } - if err = db.AutoMigrate(&myRepository.Role{}); err != nil { - panic(err) - } - if err = db.AutoMigrate(&myRepository.TksRole{}); err != nil { - panic(err) - } - if err = db.AutoMigrate(&myRepository.ProjectRole{}); err != nil { - panic(err) - } - - orgaizationRepository := myRepository.NewOrganizationRepository(db) - roleDbClient := myRepository.NewRoleRepository(db) - - roleUsecase := usecase.NewRoleUsecase(roleDbClient) - - // create organization - // organizationId = "test" - if _, err := orgaizationRepository.Get("test"); err != nil { - if _, err := orgaizationRepository.Create("test", "test", uuid.New(), "test", "test"); err != nil { - panic(err) - } - } - - // create project - // projectName = "testProject" - projectRepository := myRepository.NewProjectRepository(db) - projectFound := false - if projects, err := projectRepository.List(); err != nil { - panic(err) - } else { - for _, project := range projects { - if project.Name == "testProject" { - projectFound = true - break - } - } - } - - if !projectFound { - project := &domain.Project{ - Name: "testProject", - OrganizationID: "test", - Description: "testDesc", - } - if err := projectRepository.Create(project); err != nil { - panic(err) - } - } - - // get id of project - projects, err := projectRepository.List() - if err != nil { - panic(err) - } - var projectId uuid.UUID - for _, project := range projects { - if project.Name == "testProject" { - projectId = project.ID - break - } - } - - // create tks role - tksRoles, err := roleUsecase.ListTksRoles() - if err != nil { - panic(err) - } - tksRoleFound := false - for _, role := range tksRoles { - if role.Name == "testTksRole" { - tksRoleFound = true - break - } - } - if !tksRoleFound { - role := &domain.TksRole{ - Role: domain.Role{ - Name: "testTksRole", - OrganizationID: "test", - Description: "testDesc", - }, - } - if err := roleUsecase.CreateTksRole(role); err != nil { - panic(err) - } - } - - // create project role - projectRoles, err := roleUsecase.ListProjectRoles() - if err != nil { - panic(err) - } - - projectRoleFound := false - for _, role := range projectRoles { - if role.Role.Name == "testProjectRole" { - projectRoleFound = true - break - } - } - - if !projectRoleFound { - role := &domain.ProjectRole{ - Role: domain.Role{ - Name: "testProjectRole", - OrganizationID: "test", - Description: "testDesc", - }, - ProjectID: projectId, - } - if err := roleUsecase.CreateProjectRole(role); err != nil { - panic(err) - } - } - - // list tks role - tksRoles, err = roleUsecase.ListTksRoles() - if err != nil { - panic(err) - } - for i, role := range tksRoles { - t.Logf("index: %d, tksRole: %+v", i, role) - } - - // list project role - projectRoles, err = roleUsecase.ListProjectRoles() - if err != nil { - panic(err) - } - for i, role := range projectRoles { - t.Logf("index: %d, projectRole: %+v", i, role) - } - - // list all role - roles, err := roleUsecase.ListRoles() - if err != nil { - panic(err) - } - for i, role := range roles { - t.Logf("index: %d, role: %+v", i, role) - } - - t.Logf("now delete all roles") - - // delete tks role - for _, role := range tksRoles { - if err := roleDbClient.Delete(role.RoleID); err != nil { - panic(err) - } - } - - // delete project role - for _, role := range projectRoles { - if err := roleDbClient.Delete(role.RoleID); err != nil { - panic(err) - } - } - - // print tks role - tksRoles, err = roleUsecase.ListTksRoles() - if err != nil { - panic(err) - } - for i, role := range tksRoles { - t.Logf("index: %d, tksRole: %+v", i, role) - } - - // print project role - projectRoles, err = roleUsecase.ListProjectRoles() - if err != nil { - panic(err) - } - for i, role := range projectRoles { - t.Logf("index: %d, projectRole: %+v", i, role) - } - - // print all role - roles, err = roleUsecase.ListRoles() - if err != nil { - panic(err) - } - for i, role := range roles { - t.Logf("index: %d, role: %+v", i, role) - } - -} From 7a6474853c25c93118b9ee1d92ef9105e62543aa Mon Sep 17 00:00:00 2001 From: donggyu Date: Fri, 8 Mar 2024 11:18:37 +0900 Subject: [PATCH 02/11] improvement: make for sql log to contain req IDt --- internal/database/database.go | 4 +- internal/gorm/gorm.go | 152 +++++++++++++++++++++++++++++ pkg/log/log.go | 179 ++++++++++++++++++---------------- 3 files changed, 249 insertions(+), 86 deletions(-) create mode 100644 internal/gorm/gorm.go diff --git a/internal/database/database.go b/internal/database/database.go index 4c34a427..96ffa3eb 100644 --- a/internal/database/database.go +++ b/internal/database/database.go @@ -7,6 +7,7 @@ import ( "github.com/openinfradev/tks-api/internal/delivery/api" + internal_gorm "github.com/openinfradev/tks-api/internal/gorm" "github.com/spf13/viper" "gorm.io/driver/postgres" "gorm.io/gorm" @@ -37,9 +38,10 @@ func InitDB() (*gorm.DB, error) { default: level = logger.Silent } + newLogger := internal_gorm.NewGormLogger().LogMode(level) db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{ - Logger: logger.Default.LogMode(level), + Logger: newLogger, }) if err != nil { return nil, err diff --git a/internal/gorm/gorm.go b/internal/gorm/gorm.go new file mode 100644 index 00000000..37bd2deb --- /dev/null +++ b/internal/gorm/gorm.go @@ -0,0 +1,152 @@ +// This file contains the custom Gorm logger +// Origin Source: https://github.com/go-gorm/gorm/blob/master/logger/logger.go +// Author: Jinzhu +// Changes: Modified functions related to logging +// Licensed under the MIT License +/* +The MIT License (MIT) + +Copyright (c) 2013-NOW Jinzhu + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +*/ + +package gorm + +import ( + "context" + "fmt" + internalLogger "github.com/openinfradev/tks-api/pkg/log" + "github.com/pkg/errors" + "gorm.io/gorm/logger" + "gorm.io/gorm/utils" + "time" +) + +func (l *customGormLogger) LogMode(level logger.LogLevel) logger.Interface { + newlogger := *l + newlogger.LogLevel = level + return &newlogger +} + +func (l *customGormLogger) Info(ctx context.Context, msg string, data ...interface{}) { + if l.LogLevel >= logger.Info { + internalLogger.InfofWithContext(ctx, l.infoStr+msg, append([]interface{}{utils.FileWithLineNum()}, data...)...) + } +} + +func (l *customGormLogger) Warn(ctx context.Context, msg string, data ...interface{}) { + if l.LogLevel >= logger.Warn { + internalLogger.WarnfWithContext(ctx, l.warnStr+msg, append([]interface{}{utils.FileWithLineNum()}, data...)...) + } +} + +func (l *customGormLogger) Error(ctx context.Context, msg string, data ...interface{}) { + if l.LogLevel >= logger.Error { + internalLogger.ErrorfWithContext(ctx, l.errStr+msg, append([]interface{}{utils.FileWithLineNum()}, data...)...) + } +} + +func (l *customGormLogger) Trace(ctx context.Context, begin time.Time, fc func() (sql string, rowsAffected int64), err error) { + if l.LogLevel <= logger.Silent { + return + } + + elapsed := time.Since(begin) + switch { + case err != nil && l.LogLevel >= logger.Error && (!errors.Is(err, logger.ErrRecordNotFound) || !l.IgnoreRecordNotFoundError): + sql, rows := fc() + if rows == -1 { + internalLogger.ErrorfWithContext(ctx, l.traceErrStr, utils.FileWithLineNum(), err, float64(elapsed.Nanoseconds())/1e6, "-", sql) + //l.Printf(l.traceErrStr, utils.FileWithLineNum(), err, float64(elapsed.Nanoseconds())/1e6, "-", sql) + } else { + internalLogger.ErrorfWithContext(ctx, l.traceErrStr, utils.FileWithLineNum(), err, float64(elapsed.Nanoseconds())/1e6, rows, sql) + //l.Printf(l.traceErrStr, utils.FileWithLineNum(), err, float64(elapsed.Nanoseconds())/1e6, rows, sql) + } + case elapsed > l.SlowThreshold && l.SlowThreshold != 0 && l.LogLevel >= logger.Warn: + sql, rows := fc() + slowLog := fmt.Sprintf("SLOW SQL >= %v", l.SlowThreshold) + if rows == -1 { + internalLogger.WarnfWithContext(ctx, l.traceWarnStr, utils.FileWithLineNum(), slowLog, float64(elapsed.Nanoseconds())/1e6, "-", sql) + //l.Printf(l.traceWarnStr, utils.FileWithLineNum(), slowLog, float64(elapsed.Nanoseconds())/1e6, "-", sql) + } else { + internalLogger.WarnfWithContext(ctx, l.traceWarnStr, utils.FileWithLineNum(), slowLog, float64(elapsed.Nanoseconds())/1e6, rows, sql) + //l.Printf(l.traceWarnStr, utils.FileWithLineNum(), slowLog, float64(elapsed.Nanoseconds())/1e6, rows, sql) + } + case l.LogLevel == logger.Info: + sql, rows := fc() + if rows == -1 { + internalLogger.InfofWithContext(ctx, l.traceStr, utils.FileWithLineNum(), float64(elapsed.Nanoseconds())/1e6, "-", sql) + //l.Printf(l.traceStr, utils.FileWithLineNum(), float64(elapsed.Nanoseconds())/1e6, "-", sql) + } else { + internalLogger.InfofWithContext(ctx, l.traceStr, utils.FileWithLineNum(), float64(elapsed.Nanoseconds())/1e6, rows, sql) + //l.Printf(l.traceStr, utils.FileWithLineNum(), float64(elapsed.Nanoseconds())/1e6, rows, sql) + } + default: + internalLogger.Info("Trace") + } +} + +type customGormLogger struct { + logger.Writer + logger.Config + infoStr, warnStr, errStr string + traceStr, traceErrStr, traceWarnStr string +} + +const ( + Reset = "\033[0m" + Red = "\033[31m" + Green = "\033[32m" + Yellow = "\033[33m" + Blue = "\033[34m" + Magenta = "\033[35m" + Cyan = "\033[36m" + White = "\033[37m" + BlueBold = "\033[34;1m" + MagentaBold = "\033[35;1m" + RedBold = "\033[31;1m" + YellowBold = "\033[33;1m" +) + +func NewGormLogger() logger.Interface { + infoStr := Green + "%s\n" + Reset + Green + "[info] " + Reset + warnStr := BlueBold + "%s\n" + Reset + Magenta + "[warn] " + Reset + errStr := Magenta + "%s\n" + Reset + Red + "[error] " + Reset + traceStr := Green + "%s\n" + Reset + Yellow + "[%.3fms] " + BlueBold + "[rows:%v]" + Reset + " %s" + traceWarnStr := Green + "%s " + Yellow + "%s\n" + Reset + RedBold + "[%.3fms] " + Yellow + "[rows:%v]" + Magenta + " %s" + Reset + traceErrStr := RedBold + "%s " + MagentaBold + "%s\n" + Reset + Yellow + "[%.3fms] " + BlueBold + "[rows:%v]" + Reset + " %s" + + return &customGormLogger{ + Writer: customGormLogger{}, + Config: logger.Config{ + SlowThreshold: time.Second, + LogLevel: logger.Silent, + IgnoreRecordNotFoundError: true, + ParameterizedQueries: true, + Colorful: false, + }, + infoStr: infoStr, + warnStr: warnStr, + errStr: errStr, + traceStr: traceStr, + traceErrStr: traceErrStr, + traceWarnStr: traceWarnStr, + } +} diff --git a/pkg/log/log.go b/pkg/log/log.go index 2a5bf3bc..a88eac18 100644 --- a/pkg/log/log.go +++ b/pkg/log/log.go @@ -2,6 +2,7 @@ package log import ( "context" + "fmt" "io" "os" "runtime" @@ -48,17 +49,65 @@ type CustomFormatter struct { logrus.Formatter } +var colors = map[logrus.Level]string{ + logrus.DebugLevel: "\033[36m", // Cyan + logrus.InfoLevel: "\033[32m", // Green + logrus.WarnLevel: "\033[33m", // Yellow + logrus.ErrorLevel: "\033[31m", // Red + logrus.FatalLevel: "\033[31m", // Red + logrus.PanicLevel: "\033[31m", // Red +} + +func getColor(level logrus.Level) string { + return colors[level] +} + func (f *CustomFormatter) Format(entry *logrus.Entry) ([]byte, error) { - //_, file := path.Split(entry.Caller.File) - //entry.Data["file"] = file - return f.Formatter.Format(entry) + levelColor := getColor(entry.Level) + resetColor := "\033[0m" + levelText := strings.ToUpper(entry.Level.String()) + + requestIDColorStart := "\033[34m" // 파란색 시작 + requestIDColorEnd := "\033[0m" // 색상 리셋 + + requestID := entry.Data[string(internal.ContextKeyRequestID)] + if requestID == nil { + requestID = "Unknown" + } else { + requestID = fmt.Sprintf("%s%v%s", requestIDColorStart, requestID, requestIDColorEnd) + } + file := entry.Data["file"] + if file == nil { + file = "-" + } + var logMessage string + + if file == "-" { + logMessage = fmt.Sprintf("%s%-7s%s %s %sREQUEST_ID=%v%s msg=%s\n", + levelColor, levelText, resetColor, + entry.Time.Format("2006-01-02 15:04:05"), + requestIDColorStart, requestID, requestIDColorEnd, + entry.Message, + ) + } else { + logMessage = fmt.Sprintf("%s%-7s%s %s %sREQUEST_ID=%v%s msg=%s file= %v\n", + levelColor, levelText, resetColor, + entry.Time.Format("2006-01-02 15:04:05"), + requestIDColorStart, requestID, requestIDColorEnd, + entry.Message, + file, + ) + } + + return []byte(logMessage), nil } // [TODO] more pretty func Info(v ...interface{}) { if _, file, line, ok := runtime.Caller(1); ok { + relativePath := getRelativeFilePath(file) logger.WithFields(logrus.Fields{ - "file": file + ":" + strconv.Itoa(line), + "file": relativePath + ":" + strconv.Itoa(line), }).Info(v...) } else { logger.Info(v...) @@ -66,40 +115,26 @@ func Info(v ...interface{}) { } func Infof(format string, v ...interface{}) { if _, file, line, ok := runtime.Caller(1); ok { + relativePath := getRelativeFilePath(file) logger.WithFields(logrus.Fields{ - "file": file + ":" + strconv.Itoa(line), + "file": relativePath + ":" + strconv.Itoa(line), }).Infof(format, v...) } else { logger.Infof(format, v...) } } func InfoWithContext(ctx context.Context, v ...interface{}) { - reqID := ctx.Value(internal.ContextKeyRequestID) - if _, file, line, ok := runtime.Caller(1); ok { - logger.WithFields(logrus.Fields{ - "file": file + ":" + strconv.Itoa(line), - string(internal.ContextKeyRequestID): reqID, - }).Info(v...) - } else { - logger.WithField(string(internal.ContextKeyRequestID), reqID).Info(v...) - } + logger.WithField(string(internal.ContextKeyRequestID), ctx.Value(internal.ContextKeyRequestID)).Info(v...) } func InfofWithContext(ctx context.Context, format string, v ...interface{}) { - reqID := ctx.Value(internal.ContextKeyRequestID) - if _, file, line, ok := runtime.Caller(1); ok { - logger.WithFields(logrus.Fields{ - "file": file + ":" + strconv.Itoa(line), - string(internal.ContextKeyRequestID): reqID, - }).Infof(format, v...) - } else { - logger.WithField(string(internal.ContextKeyRequestID), reqID).Infof(format, v...) - } + logger.WithField(string(internal.ContextKeyRequestID), ctx.Value(internal.ContextKeyRequestID)).Infof(format, v...) } func Warn(v ...interface{}) { if _, file, line, ok := runtime.Caller(1); ok { + relativePath := getRelativeFilePath(file) logger.WithFields(logrus.Fields{ - "file": file + ":" + strconv.Itoa(line), + "file": relativePath + ":" + strconv.Itoa(line), }).Warn(v...) } else { logger.Warn(v...) @@ -107,40 +142,26 @@ func Warn(v ...interface{}) { } func Warnf(format string, v ...interface{}) { if _, file, line, ok := runtime.Caller(1); ok { + relativePath := getRelativeFilePath(file) logger.WithFields(logrus.Fields{ - "file": file + ":" + strconv.Itoa(line), + "file": relativePath + ":" + strconv.Itoa(line), }).Warnf(format, v...) } else { logger.Warnf(format, v...) } } func WarnWithContext(ctx context.Context, v ...interface{}) { - reqID := ctx.Value(internal.ContextKeyRequestID) - if _, file, line, ok := runtime.Caller(1); ok { - logger.WithFields(logrus.Fields{ - "file": file + ":" + strconv.Itoa(line), - string(internal.ContextKeyRequestID): reqID, - }).Warn(v...) - } else { - logger.WithField(string(internal.ContextKeyRequestID), reqID).Warn(v...) - } + logger.WithField(string(internal.ContextKeyRequestID), ctx.Value(internal.ContextKeyRequestID)).Warn(v...) } func WarnfWithContext(ctx context.Context, format string, v ...interface{}) { - reqID := ctx.Value(internal.ContextKeyRequestID) - if _, file, line, ok := runtime.Caller(1); ok { - logger.WithFields(logrus.Fields{ - "file": file + ":" + strconv.Itoa(line), - string(internal.ContextKeyRequestID): reqID, - }).Warnf(format, v...) - } else { - logger.WithField(string(internal.ContextKeyRequestID), reqID).Warnf(format, v...) - } + logger.WithField(string(internal.ContextKeyRequestID), ctx.Value(internal.ContextKeyRequestID)).Warnf(format, v...) } func Debug(v ...interface{}) { if _, file, line, ok := runtime.Caller(1); ok { + relativePath := getRelativeFilePath(file) logger.WithFields(logrus.Fields{ - "file": file + ":" + strconv.Itoa(line), + "file": relativePath + ":" + strconv.Itoa(line), }).Debug(v...) } else { logger.Debug(v...) @@ -148,40 +169,26 @@ func Debug(v ...interface{}) { } func Debugf(format string, v ...interface{}) { if _, file, line, ok := runtime.Caller(1); ok { + relativePath := getRelativeFilePath(file) logger.WithFields(logrus.Fields{ - "file": file + ":" + strconv.Itoa(line), + "file": relativePath + ":" + strconv.Itoa(line), }).Debugf(format, v...) } else { logger.Debugf(format, v...) } } func DebugWithContext(ctx context.Context, v ...interface{}) { - reqID := ctx.Value(internal.ContextKeyRequestID) - if _, file, line, ok := runtime.Caller(1); ok { - logger.WithFields(logrus.Fields{ - "file": file + ":" + strconv.Itoa(line), - string(internal.ContextKeyRequestID): reqID, - }).Debug(v...) - } else { - logger.WithField(string(internal.ContextKeyRequestID), reqID).Debug(v...) - } + logger.WithField(string(internal.ContextKeyRequestID), ctx.Value(internal.ContextKeyRequestID)).Debug(v...) } func DebugfWithContext(ctx context.Context, format string, v ...interface{}) { - reqID := ctx.Value(internal.ContextKeyRequestID) - if _, file, line, ok := runtime.Caller(1); ok { - logger.WithFields(logrus.Fields{ - "file": file + ":" + strconv.Itoa(line), - string(internal.ContextKeyRequestID): reqID, - }).Debugf(format, v...) - } else { - logger.WithField(string(internal.ContextKeyRequestID), reqID).Debugf(format, v...) - } + logger.WithField(string(internal.ContextKeyRequestID), ctx.Value(internal.ContextKeyRequestID)).Debugf(format, v...) } func Error(v ...interface{}) { if _, file, line, ok := runtime.Caller(1); ok { + relativePath := getRelativeFilePath(file) logger.WithFields(logrus.Fields{ - "file": file + ":" + strconv.Itoa(line), + "file": relativePath + ":" + strconv.Itoa(line), }).Error(v...) } else { logger.Error(v...) @@ -189,40 +196,26 @@ func Error(v ...interface{}) { } func Errorf(format string, v ...interface{}) { if _, file, line, ok := runtime.Caller(1); ok { + relativePath := getRelativeFilePath(file) logger.WithFields(logrus.Fields{ - "file": file + ":" + strconv.Itoa(line), + "file": relativePath + ":" + strconv.Itoa(line), }).Errorf(format, v...) } else { logger.Errorf(format, v...) } } func ErrorWithContext(ctx context.Context, v ...interface{}) { - reqID := ctx.Value(internal.ContextKeyRequestID) - if _, file, line, ok := runtime.Caller(1); ok { - logger.WithFields(logrus.Fields{ - "file": file + ":" + strconv.Itoa(line), - string(internal.ContextKeyRequestID): reqID, - }).Error(v...) - } else { - logger.WithField(string(internal.ContextKeyRequestID), reqID).Error(v...) - } + logger.WithField(string(internal.ContextKeyRequestID), ctx.Value(internal.ContextKeyRequestID)).Error(v...) } func ErrorfWithContext(ctx context.Context, format string, v ...interface{}) { - reqID := ctx.Value(internal.ContextKeyRequestID) - if _, file, line, ok := runtime.Caller(1); ok { - logger.WithFields(logrus.Fields{ - "file": file + ":" + strconv.Itoa(line), - string(internal.ContextKeyRequestID): reqID, - }).Errorf(format, v...) - } else { - logger.WithField(string(internal.ContextKeyRequestID), reqID).Errorf(format, v...) - } + logger.WithField(string(internal.ContextKeyRequestID), ctx.Value(internal.ContextKeyRequestID)).Errorf(format, v...) } func Fatal(v ...interface{}) { if _, file, line, ok := runtime.Caller(1); ok { + relativePath := getRelativeFilePath(file) logger.WithFields(logrus.Fields{ - "file": file + ":" + strconv.Itoa(line), + "file": relativePath + ":" + strconv.Itoa(line), }).Fatal(v...) } else { logger.Fatal(v...) @@ -230,8 +223,9 @@ func Fatal(v ...interface{}) { } func Fatalf(format string, v ...interface{}) { if _, file, line, ok := runtime.Caller(1); ok { + relativePath := getRelativeFilePath(file) logger.WithFields(logrus.Fields{ - "file": file + ":" + strconv.Itoa(line), + "file": relativePath + ":" + strconv.Itoa(line), }).Fatalf(format, v...) } else { logger.Fatalf(format, v...) @@ -241,3 +235,18 @@ func Fatalf(format string, v ...interface{}) { func Disable() { logger.Out = io.Discard } + +func getRelativeFilePath(absolutePath string) string { + wd, err := os.Getwd() + if err != nil { + return absolutePath + } + + relativePath := strings.TrimPrefix(absolutePath, wd) + + if strings.HasPrefix(relativePath, "/") { + relativePath = relativePath[1:] + } + + return relativePath +} From 22e51521a7caff2b0d982d5c0d6a3b8d0b8fbff8 Mon Sep 17 00:00:00 2001 From: donggyu Date: Tue, 12 Mar 2024 17:20:30 +0900 Subject: [PATCH 03/11] fix conflict during rebase --- internal/database/database.go | 8 +- internal/delivery/http/app-serve-app.go | 37 +- internal/delivery/http/auth.go | 47 +- internal/delivery/http/organization.go | 30 +- internal/delivery/http/permission.go | 4 +- internal/delivery/http/role.go | 18 +- internal/delivery/http/user.go | 26 +- internal/middleware/audit/audit.go | 2 +- .../middleware/auth/authorizer/password.go | 2 +- internal/middleware/auth/authorizer/rbac.go | 24 + internal/repository/alert.go | 53 ++- internal/repository/app-group.go | 55 +-- internal/repository/app-serve-app.go | 102 ++-- internal/repository/audit.go | 23 +- internal/repository/auth.go | 25 +- internal/repository/cloud-account.go | 49 +- internal/repository/cluster.go | 73 +-- internal/repository/endpoint.go | 19 +- internal/repository/organization.go | 49 +- internal/repository/permission.go | 31 +- internal/repository/permission_test.go | 445 ------------------ internal/repository/project.go | 163 +++---- internal/repository/role.go | 69 +-- internal/repository/stack-template.go | 51 +- internal/repository/user.go | 166 +++---- internal/route/route.go | 1 - internal/usecase/alert.go | 24 +- internal/usecase/app-group.go | 28 +- internal/usecase/app-serve-app.go | 124 +++-- internal/usecase/audit.go | 8 +- internal/usecase/auth.go | 123 ++--- internal/usecase/auth_test.go | 9 - internal/usecase/cloud-account.go | 40 +- internal/usecase/cluster.go | 58 +-- internal/usecase/dashboard.go | 32 +- internal/usecase/organization.go | 54 +-- internal/usecase/permission.go | 58 ++- internal/usecase/project.go | 74 +-- internal/usecase/role.go | 36 +- internal/usecase/stack-template.go | 20 +- internal/usecase/stack.go | 62 +-- internal/usecase/user.go | 94 ++-- 42 files changed, 917 insertions(+), 1499 deletions(-) delete mode 100644 internal/repository/permission_test.go delete mode 100644 internal/usecase/auth_test.go diff --git a/internal/database/database.go b/internal/database/database.go index 96ffa3eb..37485621 100644 --- a/internal/database/database.go +++ b/internal/database/database.go @@ -1,6 +1,7 @@ package database import ( + "context" "fmt" "os" "strings" @@ -176,7 +177,10 @@ func EnsureDefaultRows(db *gorm.DB) error { } // - eps, err := repoFactory.Endpoint.List(nil) + + ctx := context.Background() + + eps, err := repoFactory.Endpoint.List(ctx, nil) if err != nil { return err } @@ -187,7 +191,7 @@ func EnsureDefaultRows(db *gorm.DB) error { } for _, ep := range api.ApiMap { if _, ok := storedEps[ep.Name]; !ok { - if err := repoFactory.Endpoint.Create(&model.Endpoint{ + if err := repoFactory.Endpoint.Create(ctx, &model.Endpoint{ Name: ep.Name, Group: ep.Group, }); err != nil { diff --git a/internal/delivery/http/app-serve-app.go b/internal/delivery/http/app-serve-app.go index aa6f92b1..de7cbe7f 100644 --- a/internal/delivery/http/app-serve-app.go +++ b/internal/delivery/http/app-serve-app.go @@ -152,7 +152,7 @@ func (h *AppServeAppHandler) CreateAppServeApp(w http.ResponseWriter, r *http.Re return } - exist, err := h.usecase.IsAppServeAppNameExist(organizationId, app.Name) + exist, err := h.usecase.IsAppServeAppNameExist(r.Context(), organizationId, app.Name) if err != nil { ErrorJSON(w, r, httpErrors.NewInternalServerError(err, "", "")) return @@ -173,7 +173,7 @@ func (h *AppServeAppHandler) CreateAppServeApp(w http.ResponseWriter, r *http.Re r1 := rand.New(src) ns = fmt.Sprintf("%s-%s", app.Name, strconv.Itoa(r1.Intn(10000))) - nsExist, err = h.usecase.IsAppServeAppNamespaceExist(app.TargetClusterId, ns) + nsExist, err = h.usecase.IsAppServeAppNamespaceExist(r.Context(), app.TargetClusterId, ns) if err != nil { ErrorJSON(w, r, httpErrors.NewInternalServerError(err, "", "")) return @@ -201,7 +201,7 @@ func (h *AppServeAppHandler) CreateAppServeApp(w http.ResponseWriter, r *http.Re return } - _, _, err = h.usecase.CreateAppServeApp(&app) + _, _, err = h.usecase.CreateAppServeApp(r.Context(), &app) if err != nil { ErrorJSON(w, r, err) return @@ -257,7 +257,7 @@ func (h *AppServeAppHandler) GetAppServeApps(w http.ResponseWriter, r *http.Requ return } pg := pagination.NewPagination(&urlParams) - apps, err := h.usecase.GetAppServeApps(organizationId, showAll, pg) + apps, err := h.usecase.GetAppServeApps(r.Context(), organizationId, showAll, pg) if err != nil { log.ErrorWithContext(r.Context(), "Failed to get Failed to get app-serve-apps ", err) ErrorJSON(w, r, err) @@ -314,7 +314,7 @@ func (h *AppServeAppHandler) GetAppServeApp(w http.ResponseWriter, r *http.Reque ErrorJSON(w, r, httpErrors.NewBadRequestError(fmt.Errorf("invalid appId"), "C_INVALID_ASA_ID", "")) return } - app, err := h.usecase.GetAppServeAppById(appId) + app, err := h.usecase.GetAppServeAppById(r.Context(), appId) if err != nil { ErrorJSON(w, r, httpErrors.NewInternalServerError(err, "", "")) return @@ -376,7 +376,7 @@ func (h *AppServeAppHandler) GetAppServeAppLatestTask(w http.ResponseWriter, r * ErrorJSON(w, r, httpErrors.NewBadRequestError(fmt.Errorf("invalid appId"), "", "")) return } - task, err := h.usecase.GetAppServeAppLatestTask(appId) + task, err := h.usecase.GetAppServeAppLatestTask(r.Context(), appId) if err != nil { ErrorJSON(w, r, httpErrors.NewInternalServerError(err, "", "")) return @@ -424,7 +424,7 @@ func (h *AppServeAppHandler) GetNumOfAppsOnStack(w http.ResponseWriter, r *http. } fmt.Printf("stackId = [%s]\n", stackId) - numApps, err := h.usecase.GetNumOfAppsOnStack(organizationId, stackId) + numApps, err := h.usecase.GetNumOfAppsOnStack(r.Context(), organizationId, stackId) if err != nil { ErrorJSON(w, r, httpErrors.NewInternalServerError(err, "", "")) return @@ -467,7 +467,7 @@ func (h *AppServeAppHandler) GetAppServeAppTasksByAppId(w http.ResponseWriter, r urlParams := r.URL.Query() pg := pagination.NewPagination(&urlParams) - tasks, err := h.usecase.GetAppServeAppTasks(appId, pg) + tasks, err := h.usecase.GetAppServeAppTasks(r.Context(), appId, pg) if err != nil { log.ErrorWithContext(r.Context(), "Failed to get app-serve-app-tasks ", err) ErrorJSON(w, r, err) @@ -535,7 +535,7 @@ func (h *AppServeAppHandler) GetAppServeAppTaskDetail(w http.ResponseWriter, r * return } - task, app, err := h.usecase.GetAppServeAppTaskById(taskId) + task, app, err := h.usecase.GetAppServeAppTaskById(r.Context(), taskId) if err != nil { ErrorJSON(w, r, httpErrors.NewInternalServerError(err, "", "")) return @@ -693,7 +693,7 @@ func (h *AppServeAppHandler) IsAppServeAppExist(w http.ResponseWriter, r *http.R return } - exist, err := h.usecase.IsAppServeAppExist(appId) + exist, err := h.usecase.IsAppServeAppExist(r.Context(), appId) if err != nil { ErrorJSON(w, r, err) return @@ -734,7 +734,7 @@ func (h *AppServeAppHandler) IsAppServeAppNameExist(w http.ResponseWriter, r *ht return } - existed, err := h.usecase.IsAppServeAppNameExist(organizationId, appName) + existed, err := h.usecase.IsAppServeAppNameExist(r.Context(), organizationId, appName) if err != nil { ErrorJSON(w, r, err) return @@ -776,7 +776,7 @@ func (h *AppServeAppHandler) UpdateAppServeApp(w http.ResponseWriter, r *http.Re return } - app, err := h.usecase.GetAppServeAppById(appId) + app, err := h.usecase.GetAppServeAppById(r.Context(), appId) if err != nil { ErrorJSON(w, r, err) return @@ -843,11 +843,11 @@ func (h *AppServeAppHandler) UpdateAppServeApp(w http.ResponseWriter, r *http.Re var res string if appReq.Promote { - res, err = h.usecase.PromoteAppServeApp(appId) + res, err = h.usecase.PromoteAppServeApp(r.Context(), appId) } else if appReq.Abort { - res, err = h.usecase.AbortAppServeApp(appId) + res, err = h.usecase.AbortAppServeApp(r.Context(), appId) } else { - res, err = h.usecase.UpdateAppServeApp(app, &task) + res, err = h.usecase.UpdateAppServeApp(r.Context(), app, &task) } if err != nil { @@ -894,7 +894,7 @@ func (h *AppServeAppHandler) UpdateAppServeAppStatus(w http.ResponseWriter, r *h return } - res, err := h.usecase.UpdateAppServeAppStatus(appId, appStatusReq.TaskID, appStatusReq.Status, appStatusReq.Output) + res, err := h.usecase.UpdateAppServeAppStatus(r.Context(), appId, appStatusReq.TaskID, appStatusReq.Status, appStatusReq.Output) if err != nil { ErrorJSON(w, r, httpErrors.NewBadRequestError(err, "", "")) return @@ -940,6 +940,7 @@ func (h *AppServeAppHandler) UpdateAppServeAppEndpoint(w http.ResponseWriter, r } res, err := h.usecase.UpdateAppServeAppEndpoint( + r.Context(), appId, appReq.TaskID, appReq.EndpointUrl, @@ -981,7 +982,7 @@ func (h *AppServeAppHandler) DeleteAppServeApp(w http.ResponseWriter, r *http.Re return } - res, err := h.usecase.DeleteAppServeApp(appId) + res, err := h.usecase.DeleteAppServeApp(r.Context(), appId) if err != nil { log.ErrorWithContext(r.Context(), "Failed to delete appId err : ", err) ErrorJSON(w, r, err) @@ -1031,7 +1032,7 @@ func (h *AppServeAppHandler) RollbackAppServeApp(w http.ResponseWriter, r *http. return } - res, err := h.usecase.RollbackAppServeApp(appId, appReq.TaskId) + res, err := h.usecase.RollbackAppServeApp(r.Context(), appId, appReq.TaskId) if err != nil { ErrorJSON(w, r, httpErrors.NewBadRequestError(err, "", "")) diff --git a/internal/delivery/http/auth.go b/internal/delivery/http/auth.go index d2fea4d3..36359785 100644 --- a/internal/delivery/http/auth.go +++ b/internal/delivery/http/auth.go @@ -19,7 +19,6 @@ type IAuthHandler interface { Login(w http.ResponseWriter, r *http.Request) Logout(w http.ResponseWriter, r *http.Request) // Deprecated: PingToken is deprecated. Use VerifyToken instead. - PingToken(w http.ResponseWriter, r *http.Request) RefreshToken(w http.ResponseWriter, r *http.Request) FindId(w http.ResponseWriter, r *http.Request) FindPassword(w http.ResponseWriter, r *http.Request) @@ -59,7 +58,7 @@ func (h *AuthHandler) Login(w http.ResponseWriter, r *http.Request) { return } - user, err := h.usecase.Login(input.AccountId, input.Password, input.OrganizationId) + user, err := h.usecase.Login(r.Context(), input.AccountId, input.Password, input.OrganizationId) if err != nil { errorResponse, _ := httpErrors.ErrorResponse(err) _, _ = h.auditUsecase.Create(r.Context(), model.Audit{ @@ -85,7 +84,7 @@ func (h *AuthHandler) Login(w http.ResponseWriter, r *http.Request) { } var cookies []*http.Cookie - if targetCookies, err := h.usecase.SingleSignIn(input.OrganizationId, input.AccountId, input.Password); err != nil { + if targetCookies, err := h.usecase.SingleSignIn(r.Context(), input.OrganizationId, input.AccountId, input.Password); err != nil { log.ErrorfWithContext(r.Context(), "error is :%s(%T)", err.Error(), err) } else { cookies = append(cookies, targetCookies...) @@ -132,7 +131,7 @@ func (h *AuthHandler) Logout(w http.ResponseWriter, r *http.Request) { } organizationId := userInfo.GetOrganizationId() - err := h.usecase.Logout(sessionId, organizationId) + err := h.usecase.Logout(r.Context(), sessionId, organizationId) if err != nil { log.ErrorfWithContext(r.Context(), "error is :%s(%T)", err.Error(), err) ErrorJSON(w, r, httpErrors.NewBadRequestError(err, "", "")) @@ -140,7 +139,7 @@ func (h *AuthHandler) Logout(w http.ResponseWriter, r *http.Request) { } var cookies []*http.Cookie - redirectUrl, targetCookies, err := h.usecase.SingleSignOut(organizationId) + redirectUrl, targetCookies, err := h.usecase.SingleSignOut(r.Context(), organizationId) if err != nil { log.ErrorfWithContext(r.Context(), "error is :%s(%T)", err.Error(), err) } @@ -184,7 +183,7 @@ func (h *AuthHandler) FindId(w http.ResponseWriter, r *http.Request) { return } - accountId, err := h.usecase.FindId(input.Code, input.Email, input.UserName, input.OrganizationId) + accountId, err := h.usecase.FindId(r.Context(), input.Code, input.Email, input.UserName, input.OrganizationId) if err != nil { log.ErrorfWithContext(r.Context(), "error is :%s(%T)", err.Error(), err) @@ -216,7 +215,7 @@ func (h *AuthHandler) FindPassword(w http.ResponseWriter, r *http.Request) { return } - err = h.usecase.FindPassword(input.Code, input.AccountId, input.Email, input.UserName, input.OrganizationId) + err = h.usecase.FindPassword(r.Context(), input.Code, input.AccountId, input.Email, input.UserName, input.OrganizationId) if err != nil { log.ErrorfWithContext(r.Context(), "error is :%s(%T)", err.Error(), err) ErrorJSON(w, r, err) @@ -245,7 +244,7 @@ func (h *AuthHandler) VerifyIdentityForLostId(w http.ResponseWriter, r *http.Req return } - err = h.usecase.VerifyIdentity("", input.Email, input.UserName, input.OrganizationId) + err = h.usecase.VerifyIdentity(r.Context(), "", input.Email, input.UserName, input.OrganizationId) if err != nil { log.ErrorfWithContext(r.Context(), "error is :%s(%T)", err.Error(), err) ErrorJSON(w, r, err) @@ -276,7 +275,7 @@ func (h *AuthHandler) VerifyIdentityForLostPassword(w http.ResponseWriter, r *ht return } - err = h.usecase.VerifyIdentity(input.AccountId, input.Email, input.UserName, input.OrganizationId) + err = h.usecase.VerifyIdentity(r.Context(), input.AccountId, input.Email, input.UserName, input.OrganizationId) if err != nil { log.ErrorfWithContext(r.Context(), "error is :%s(%T)", err.Error(), err) ErrorJSON(w, r, err) @@ -288,34 +287,6 @@ func (h *AuthHandler) VerifyIdentityForLostPassword(w http.ResponseWriter, r *ht ResponseJSON(w, r, http.StatusOK, out) } -// Login godoc -// -// @Tags Auth -// @Summary ping with token -// @Description ping with token -// @Accept json -// @Produce json -// @Param body body domain.PingTokenRequest true "token info" -// @Success 200 {object} nil -// @Router /auth/ping [post] -func (h *AuthHandler) PingToken(w http.ResponseWriter, r *http.Request) { - input := domain.PingTokenRequest{} - err := UnmarshalRequestInput(r, &input) - if err != nil { - ErrorJSON(w, r, err) - return - } - - err = h.usecase.PingToken(input.Token, input.OrganizationId) - if err != nil { - log.ErrorfWithContext(r.Context(), "error is :%s(%T)", err.Error(), err) - ErrorJSON(w, r, err) - return - } - - ResponseJSON(w, r, http.StatusOK, nil) -} - // VerifyToken godoc // @Tags Auth // @Summary verify token @@ -332,7 +303,7 @@ func (h *AuthHandler) VerifyToken(w http.ResponseWriter, r *http.Request) { return } - isActive, err := h.usecase.VerifyToken(token) + isActive, err := h.usecase.VerifyToken(r.Context(), token) if err != nil { log.ErrorfWithContext(r.Context(), "error is :%s(%T)", err.Error(), err) ErrorJSON(w, r, httpErrors.NewInternalServerError(err, "", "")) diff --git a/internal/delivery/http/organization.go b/internal/delivery/http/organization.go index a588758d..77f77841 100644 --- a/internal/delivery/http/organization.go +++ b/internal/delivery/http/organization.go @@ -74,7 +74,7 @@ func (h *OrganizationHandler) CreateOrganization(w http.ResponseWriter, r *http. Description: "admin", Type: string(domain.RoleTypeTks), } - adminRoleId, err := h.roleUsecase.CreateTksRole(&adminRole) + adminRoleId, err := h.roleUsecase.CreateTksRole(r.Context(), &adminRole) if err != nil { log.ErrorfWithContext(r.Context(), "error is :%s(%T)", err.Error(), err) ErrorJSON(w, r, err) @@ -86,7 +86,7 @@ func (h *OrganizationHandler) CreateOrganization(w http.ResponseWriter, r *http. Description: "user", Type: string(domain.RoleTypeTks), } - userRoleId, err := h.roleUsecase.CreateTksRole(&userRole) + userRoleId, err := h.roleUsecase.CreateTksRole(r.Context(), &userRole) if err != nil { log.ErrorfWithContext(r.Context(), "error is :%s(%T)", err.Error(), err) ErrorJSON(w, r, err) @@ -94,18 +94,18 @@ func (h *OrganizationHandler) CreateOrganization(w http.ResponseWriter, r *http. } // Permission 생성 - adminPermissionSet := h.permissionUsecase.GetAllowedPermissionSet() - h.permissionUsecase.SetRoleIdToPermissionSet(adminRoleId, adminPermissionSet) - err = h.permissionUsecase.CreatePermissionSet(adminPermissionSet) + adminPermissionSet := h.permissionUsecase.GetAllowedPermissionSet(r.Context()) + h.permissionUsecase.SetRoleIdToPermissionSet(r.Context(), adminRoleId, adminPermissionSet) + err = h.permissionUsecase.CreatePermissionSet(r.Context(), adminPermissionSet) if err != nil { log.ErrorfWithContext(r.Context(), "error is :%s(%T)", err.Error(), err) ErrorJSON(w, r, err) return } - userPermissionSet := h.permissionUsecase.GetUserPermissionSet() - h.permissionUsecase.SetRoleIdToPermissionSet(userRoleId, userPermissionSet) - err = h.permissionUsecase.CreatePermissionSet(userPermissionSet) + userPermissionSet := h.permissionUsecase.GetUserPermissionSet(r.Context()) + h.permissionUsecase.SetRoleIdToPermissionSet(r.Context(), userRoleId, userPermissionSet) + err = h.permissionUsecase.CreatePermissionSet(r.Context(), userPermissionSet) if err != nil { log.ErrorfWithContext(r.Context(), "error is :%s(%T)", err.Error(), err) ErrorJSON(w, r, err) @@ -113,14 +113,14 @@ func (h *OrganizationHandler) CreateOrganization(w http.ResponseWriter, r *http. } // Admin user 생성 - admin, err := h.userUsecase.CreateAdmin(organizationId, input.AdminAccountId, input.AdminName, input.AdminEmail) + admin, err := h.userUsecase.CreateAdmin(r.Context(), organizationId, input.AdminAccountId, input.AdminName, input.AdminEmail) if err != nil { log.ErrorfWithContext(r.Context(), "error is :%s(%T)", err.Error(), err) ErrorJSON(w, r, err) return } - err = h.usecase.ChangeAdminId(organizationId, admin.ID) + err = h.usecase.ChangeAdminId(r.Context(), organizationId, admin.ID) if err != nil { log.ErrorfWithContext(r.Context(), "error is :%s(%T)", err.Error(), err) ErrorJSON(w, r, err) @@ -154,7 +154,7 @@ func (h *OrganizationHandler) CreateOrganization(w http.ResponseWriter, r *http. func (h *OrganizationHandler) GetOrganizations(w http.ResponseWriter, r *http.Request) { urlParams := r.URL.Query() pg := pagination.NewPagination(&urlParams) - organizations, err := h.usecase.Fetch(pg) + organizations, err := h.usecase.Fetch(r.Context(), pg) if err != nil { log.ErrorfWithContext(r.Context(), "error is :%s(%T)", err.Error(), err) @@ -199,7 +199,7 @@ func (h *OrganizationHandler) GetOrganization(w http.ResponseWriter, r *http.Req return } - organization, err := h.usecase.Get(organizationId) + organization, err := h.usecase.Get(r.Context(), organizationId) if err != nil { log.ErrorfWithContext(r.Context(), "error is :%s(%T)", err.Error(), err) if _, status := httpErrors.ErrorResponse(err); status == http.StatusNotFound { @@ -269,7 +269,7 @@ func (h *OrganizationHandler) DeleteOrganization(w http.ResponseWriter, r *http. } // organization 삭제 - err = h.usecase.Delete(organizationId, token) + err = h.usecase.Delete(r.Context(), organizationId, token) if err != nil { log.ErrorfWithContext(r.Context(), "error is :%s(%T)", err.Error(), err) if _, status := httpErrors.ErrorResponse(err); status == http.StatusNotFound { @@ -313,7 +313,7 @@ func (h *OrganizationHandler) UpdateOrganization(w http.ResponseWriter, r *http. return } - organization, err := h.usecase.Update(organizationId, input) + organization, err := h.usecase.Update(r.Context(), organizationId, input) if err != nil { log.ErrorfWithContext(r.Context(), "error is :%s(%T)", err.Error(), err) if _, status := httpErrors.ErrorResponse(err); status == http.StatusNotFound { @@ -359,7 +359,7 @@ func (h *OrganizationHandler) UpdatePrimaryCluster(w http.ResponseWriter, r *htt return } - err = h.usecase.UpdatePrimaryClusterId(organizationId, input.PrimaryClusterId) + err = h.usecase.UpdatePrimaryClusterId(r.Context(), organizationId, input.PrimaryClusterId) if err != nil { if _, status := httpErrors.ErrorResponse(err); status == http.StatusNotFound { ErrorJSON(w, r, httpErrors.NewBadRequestError(err, "", "")) diff --git a/internal/delivery/http/permission.go b/internal/delivery/http/permission.go index d7ca79d9..bdc65716 100644 --- a/internal/delivery/http/permission.go +++ b/internal/delivery/http/permission.go @@ -79,7 +79,7 @@ func (h PermissionHandler) GetPermissionsByRoleId(w http.ResponseWriter, r *http roleId = v } - permissionSet, err := h.permissionUsecase.GetPermissionSetByRoleId(roleId) + permissionSet, err := h.permissionUsecase.GetPermissionSetByRoleId(r.Context(), roleId) if err != nil { ErrorJSON(w, r, httpErrors.NewInternalServerError(err, "", "")) return @@ -143,7 +143,7 @@ func (h PermissionHandler) UpdatePermissionsByRoleId(w http.ResponseWriter, r *h log.InfoWithContext(r.Context(), err) } - if err := h.permissionUsecase.UpdatePermission(&permission); err != nil { + if err := h.permissionUsecase.UpdatePermission(r.Context(), &permission); err != nil { ErrorJSON(w, r, httpErrors.NewInternalServerError(err, "", "")) return } diff --git a/internal/delivery/http/role.go b/internal/delivery/http/role.go index 7fdb1157..3ada3dc3 100644 --- a/internal/delivery/http/role.go +++ b/internal/delivery/http/role.go @@ -78,15 +78,15 @@ func (h RoleHandler) CreateTksRole(w http.ResponseWriter, r *http.Request) { // create role var roleId string - if roleId, err = h.roleUsecase.CreateTksRole(&dto); err != nil { + if roleId, err = h.roleUsecase.CreateTksRole(r.Context(), &dto); err != nil { ErrorJSON(w, r, err) return } // create permission defaultPermissionSet := model.NewDefaultPermissionSet() - h.permissionUsecase.SetRoleIdToPermissionSet(roleId, defaultPermissionSet) - err = h.permissionUsecase.CreatePermissionSet(defaultPermissionSet) + h.permissionUsecase.SetRoleIdToPermissionSet(r.Context(), roleId, defaultPermissionSet) + err = h.permissionUsecase.CreatePermissionSet(r.Context(), defaultPermissionSet) if err != nil { ErrorJSON(w, r, err) return @@ -123,7 +123,7 @@ func (h RoleHandler) ListTksRoles(w http.ResponseWriter, r *http.Request) { pg := pagination.NewPagination(&urlParams) // list roles - roles, err := h.roleUsecase.ListTksRoles(organizationId, pg) + roles, err := h.roleUsecase.ListTksRoles(r.Context(), organizationId, pg) if err != nil { ErrorJSON(w, r, err) return @@ -173,7 +173,7 @@ func (h RoleHandler) GetTksRole(w http.ResponseWriter, r *http.Request) { } // get role - role, err := h.roleUsecase.GetTksRole(roleId) + role, err := h.roleUsecase.GetTksRole(r.Context(), roleId) if err != nil { ErrorJSON(w, r, err) return @@ -216,7 +216,7 @@ func (h RoleHandler) DeleteTksRole(w http.ResponseWriter, r *http.Request) { } // delete role - if err := h.roleUsecase.DeleteTksRole(roleId); err != nil { + if err := h.roleUsecase.DeleteTksRole(r.Context(), roleId); err != nil { ErrorJSON(w, r, err) return } @@ -264,7 +264,7 @@ func (h RoleHandler) UpdateTksRole(w http.ResponseWriter, r *http.Request) { } // update role - if err := h.roleUsecase.UpdateTksRole(&dto); err != nil { + if err := h.roleUsecase.UpdateTksRole(r.Context(), &dto); err != nil { ErrorJSON(w, r, err) return } @@ -300,7 +300,7 @@ func (h RoleHandler) Admin_ListTksRoles(w http.ResponseWriter, r *http.Request) pg := pagination.NewPagination(&urlParams) // list roles - roles, err := h.roleUsecase.ListTksRoles(organizationId, pg) + roles, err := h.roleUsecase.ListTksRoles(r.Context(), organizationId, pg) if err != nil { ErrorJSON(w, r, err) return @@ -350,7 +350,7 @@ func (h RoleHandler) Admin_GetTksRole(w http.ResponseWriter, r *http.Request) { } // get role - role, err := h.roleUsecase.GetTksRole(roleId) + role, err := h.roleUsecase.GetTksRole(r.Context(), roleId) if err != nil { ErrorJSON(w, r, err) return diff --git a/internal/delivery/http/user.go b/internal/delivery/http/user.go index 9fa3b8b7..f7ca4fce 100644 --- a/internal/delivery/http/user.go +++ b/internal/delivery/http/user.go @@ -95,7 +95,7 @@ func (u UserHandler) Create(w http.ResponseWriter, r *http.Request) { ID: organizationId, } - roles, err := u.roleUsecase.ListTksRoles(organizationId, nil) + roles, err := u.roleUsecase.ListTksRoles(r.Context(), organizationId, nil) if err != nil { log.ErrorfWithContext(r.Context(), "error is :%s(%T)", err.Error(), err) ErrorJSON(w, r, err) @@ -309,7 +309,7 @@ func (u UserHandler) Update(w http.ResponseWriter, r *http.Request) { } user.AccountId = accountId - roles, err := u.roleUsecase.ListTksRoles(organizationId, nil) + roles, err := u.roleUsecase.ListTksRoles(r.Context(), organizationId, nil) if err != nil { log.ErrorfWithContext(r.Context(), "error is :%s(%T)", err.Error(), err) ErrorJSON(w, r, err) @@ -368,7 +368,7 @@ func (u UserHandler) ResetPassword(w http.ResponseWriter, r *http.Request) { return } - err := u.usecase.ResetPasswordByAccountId(accountId, organizationId) + err := u.usecase.ResetPasswordByAccountId(r.Context(), accountId, organizationId) if err != nil { ErrorJSON(w, r, err) return @@ -395,7 +395,7 @@ func (u UserHandler) GetMyProfile(w http.ResponseWriter, r *http.Request) { return } - user, err := u.usecase.Get(requestUserInfo.GetUserId()) + user, err := u.usecase.Get(r.Context(), requestUserInfo.GetUserId()) if err != nil { ErrorJSON(w, r, err) } @@ -444,7 +444,7 @@ func (u UserHandler) UpdateMyProfile(w http.ResponseWriter, r *http.Request) { return } - err = u.usecase.ValidateAccount(requestUserInfo.GetUserId(), input.Password, requestUserInfo.GetOrganizationId()) + err = u.usecase.ValidateAccount(r.Context(), requestUserInfo.GetUserId(), input.Password, requestUserInfo.GetOrganizationId()) if err != nil { log.ErrorfWithContext(r.Context(), "error is :%s(%T)", err.Error(), err) ErrorJSON(w, r, err) @@ -506,7 +506,7 @@ func (u UserHandler) UpdateMyPassword(w http.ResponseWriter, r *http.Request) { return } - user, err := u.usecase.Get(requestUserInfo.GetUserId()) + user, err := u.usecase.Get(r.Context(), requestUserInfo.GetUserId()) if err != nil { ErrorJSON(w, r, err) return @@ -577,7 +577,7 @@ func (u UserHandler) DeleteMyProfile(w http.ResponseWriter, r *http.Request) { ErrorJSON(w, r, httpErrors.NewInternalServerError(fmt.Errorf("user not found in request context"), "A_INVALID_TOKEN", "")) return } - if err := u.usecase.Delete(requestUserInfo.GetUserId(), requestUserInfo.GetOrganizationId()); err != nil { + if err := u.usecase.Delete(r.Context(), requestUserInfo.GetUserId(), requestUserInfo.GetOrganizationId()); err != nil { ErrorJSON(w, r, err) return } @@ -704,7 +704,7 @@ func (u UserHandler) Admin_Create(w http.ResponseWriter, r *http.Request) { ErrorJSON(w, r, httpErrors.NewInternalServerError(fmt.Errorf("user not found in request"), "A_INVALID_TOKEN", "")) return } - err = u.usecase.ValidateAccount(requestUserInfo.GetUserId(), input.AdminPassword, requestUserInfo.GetOrganizationId()) + err = u.usecase.ValidateAccount(r.Context(), requestUserInfo.GetUserId(), input.AdminPassword, requestUserInfo.GetOrganizationId()) if err != nil { ErrorJSON(w, r, err) return @@ -719,7 +719,7 @@ func (u UserHandler) Admin_Create(w http.ResponseWriter, r *http.Request) { Description: input.Description, } - roles, err := u.roleUsecase.ListTksRoles(organizationId, nil) + roles, err := u.roleUsecase.ListTksRoles(r.Context(), organizationId, nil) if err != nil { log.ErrorfWithContext(r.Context(), "error is :%s(%T)", err.Error(), err) ErrorJSON(w, r, err) @@ -737,7 +737,7 @@ func (u UserHandler) Admin_Create(w http.ResponseWriter, r *http.Request) { ID: organizationId, } - user.Password = u.usecase.GenerateRandomPassword() + user.Password = u.usecase.GenerateRandomPassword(r.Context()) resUser, err := u.usecase.Create(r.Context(), &user) if err != nil { @@ -901,7 +901,7 @@ func (u UserHandler) Admin_Delete(w http.ResponseWriter, r *http.Request) { ErrorJSON(w, r, httpErrors.NewInternalServerError(fmt.Errorf("user not found in request"), "A_INVALID_TOKEN", "")) return } - err = u.usecase.ValidateAccount(requestUserInfo.GetUserId(), input.AdminPassword, requestUserInfo.GetOrganizationId()) + err = u.usecase.ValidateAccount(r.Context(), requestUserInfo.GetUserId(), input.AdminPassword, requestUserInfo.GetOrganizationId()) if err != nil { ErrorJSON(w, r, err) return @@ -966,7 +966,7 @@ func (u UserHandler) Admin_Update(w http.ResponseWriter, r *http.Request) { ErrorJSON(w, r, httpErrors.NewInternalServerError(fmt.Errorf("user not found in request"), "A_INVALID_TOKEN", "")) return } - err = u.usecase.ValidateAccount(requestUserInfo.GetUserId(), input.AdminPassword, requestUserInfo.GetOrganizationId()) + err = u.usecase.ValidateAccount(r.Context(), requestUserInfo.GetUserId(), input.AdminPassword, requestUserInfo.GetOrganizationId()) if err != nil { ErrorJSON(w, r, err) return @@ -985,7 +985,7 @@ func (u UserHandler) Admin_Update(w http.ResponseWriter, r *http.Request) { ID: organizationId, } - roles, err := u.roleUsecase.ListTksRoles(organizationId, nil) + roles, err := u.roleUsecase.ListTksRoles(r.Context(), organizationId, nil) if err != nil { log.ErrorfWithContext(r.Context(), "error is :%s(%T)", err.Error(), err) ErrorJSON(w, r, err) diff --git a/internal/middleware/audit/audit.go b/internal/middleware/audit/audit.go index 12360269..fc06c80f 100644 --- a/internal/middleware/audit/audit.go +++ b/internal/middleware/audit/audit.go @@ -67,7 +67,7 @@ func (a *defaultAudit) WithAudit(endpoint internalApi.Endpoint, handler http.Han ClientIP: GetClientIpAddress(w, r), UserId: &userId, } - if _, err := a.repo.Create(dto); err != nil { + if _, err := a.repo.Create(r.Context(), dto); err != nil { log.Error(err) } } diff --git a/internal/middleware/auth/authorizer/password.go b/internal/middleware/auth/authorizer/password.go index 4fd9b980..d9dc083c 100644 --- a/internal/middleware/auth/authorizer/password.go +++ b/internal/middleware/auth/authorizer/password.go @@ -20,7 +20,7 @@ func PasswordFilter(handler http.Handler, repo repository.Repository) http.Handl return } - storedUser, err := repo.User.GetByUuid(requestUserInfo.GetUserId()) + storedUser, err := repo.User.GetByUuid(r.Context(), requestUserInfo.GetUserId()) if err != nil { internalHttp.ErrorJSON(w, r, err) return diff --git a/internal/middleware/auth/authorizer/rbac.go b/internal/middleware/auth/authorizer/rbac.go index 722ccd8f..9c16508b 100644 --- a/internal/middleware/auth/authorizer/rbac.go +++ b/internal/middleware/auth/authorizer/rbac.go @@ -117,6 +117,30 @@ func AdminApiFilter(handler http.Handler, repo repository.Repository) http.Handl }) } +func RequestOrganizationValidationFilter(handler http.Handler, repo repository.Repository) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + requestUserInfo, ok := request.UserFrom(r.Context()) + if !ok { + internalHttp.ErrorJSON(w, r, httpErrors.NewInternalServerError(fmt.Errorf("user not found"), "", "")) + return + } + + vars := mux.Vars(r) + organizationId, ok := vars["organizationId"] + if !ok { + //internalHttp.ErrorJSON(w, r, httpErrors.NewInternalServerError(fmt.Errorf("organizationId not found"), "", "")) + //return + log.Warn("RequestOrganizationValidationFilter: organizationId not found. Passing through unsafely.") + } + if organizationId != requestUserInfo.GetOrganizationId() { + internalHttp.ErrorJSON(w, r, httpErrors.NewForbiddenError(fmt.Errorf("permission denied"), "", "")) + return + } + + handler.ServeHTTP(w, r) + }) +} + //type pair struct { // regexp string // method string diff --git a/internal/repository/alert.go b/internal/repository/alert.go index 2d35f536..ef25d7bf 100644 --- a/internal/repository/alert.go +++ b/internal/repository/alert.go @@ -1,6 +1,7 @@ package repository import ( + "context" "time" "github.com/google/uuid" @@ -14,15 +15,15 @@ import ( // Interfaces type IAlertRepository interface { - 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) + 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) + FetchPodRestart(ctx context.Context, organizationId string, start time.Time, end time.Time) ([]model.Alert, error) + Create(ctx context.Context, dto model.Alert) (alertId uuid.UUID, err error) + Update(ctx context.Context, dto model.Alert) (err error) + Delete(ctx context.Context, dto model.Alert) (err error) + + CreateAlertAction(ctx context.Context, dto model.AlertAction) (alertActionId uuid.UUID, err error) } type AlertRepository struct { @@ -36,28 +37,28 @@ func NewAlertRepository(db *gorm.DB) IAlertRepository { } // Logics -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) +func (r *AlertRepository) Get(ctx context.Context, alertId uuid.UUID) (out model.Alert, err error) { + res := r.db.WithContext(ctx).Preload("AlertActions.Taker").Preload(clause.Associations).First(&out, "id = ?", alertId) if res.Error != nil { return model.Alert{}, res.Error } return } -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) +func (r *AlertRepository) GetByName(ctx context.Context, organizationId string, name string) (out model.Alert, err error) { + res := r.db.WithContext(ctx).Preload("AlertActions.Taker").Preload(clause.Associations).First(&out, "organization_id = ? AND name = ?", organizationId, name) if res.Error != nil { return model.Alert{}, res.Error } return } -func (r *AlertRepository) Fetch(organizationId string, pg *pagination.Pagination) (out []model.Alert, err error) { +func (r *AlertRepository) Fetch(ctx context.Context, organizationId string, pg *pagination.Pagination) (out []model.Alert, err error) { if pg == nil { pg = pagination.NewPagination(nil) } - _, res := pg.Fetch(r.db.Model(&model.Alert{}). + _, res := pg.Fetch(r.db.WithContext(ctx).Model(&model.Alert{}). Preload("AlertActions", func(db *gorm.DB) *gorm.DB { return db.Order("created_at ASC") }).Preload("AlertActions.Taker"). @@ -72,8 +73,8 @@ func (r *AlertRepository) Fetch(organizationId string, pg *pagination.Pagination return } -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"). +func (r *AlertRepository) FetchPodRestart(ctx context.Context, organizationId string, start time.Time, end time.Time) (out []model.Alert, err error) { + res := r.db.WithContext(ctx).Preload(clause.Associations).Order("created_at DESC"). Where("organization_id = ? AND name = 'pod-restart-frequently' AND created_at BETWEEN ? AND ?", organizationId, start, end). Find(&out) if res.Error != nil { @@ -82,7 +83,7 @@ func (r *AlertRepository) FetchPodRestart(organizationId string, start time.Time return } -func (r *AlertRepository) Create(dto model.Alert) (alertId uuid.UUID, err error) { +func (r *AlertRepository) Create(ctx context.Context, dto model.Alert) (alertId uuid.UUID, err error) { alert := model.Alert{ OrganizationId: dto.OrganizationId, Name: dto.Name, @@ -98,15 +99,15 @@ func (r *AlertRepository) Create(dto model.Alert) (alertId uuid.UUID, err error) RawData: dto.RawData, Status: domain.AlertActionStatus_CREATED, } - res := r.db.Create(&alert) + res := r.db.WithContext(ctx).Create(&alert) if res.Error != nil { return uuid.Nil, res.Error } return alert.ID, nil } -func (r *AlertRepository) Update(dto model.Alert) (err error) { - res := r.db.Model(&model.Alert{}). +func (r *AlertRepository) Update(ctx context.Context, dto model.Alert) (err error) { + res := r.db.WithContext(ctx).Model(&model.Alert{}). Where("id = ?", dto.ID). Updates(map[string]interface{}{"Description": dto.Description}) if res.Error != nil { @@ -115,26 +116,26 @@ func (r *AlertRepository) Update(dto model.Alert) (err error) { return nil } -func (r *AlertRepository) Delete(dto model.Alert) (err error) { - res := r.db.Delete(&model.Alert{}, "id = ?", dto.ID) +func (r *AlertRepository) Delete(ctx context.Context, dto model.Alert) (err error) { + res := r.db.WithContext(ctx).Delete(&model.Alert{}, "id = ?", dto.ID) if res.Error != nil { return res.Error } return nil } -func (r *AlertRepository) CreateAlertAction(dto model.AlertAction) (alertActionId uuid.UUID, err error) { +func (r *AlertRepository) CreateAlertAction(ctx context.Context, dto model.AlertAction) (alertActionId uuid.UUID, err error) { alert := model.AlertAction{ AlertId: dto.AlertId, Content: dto.Content, Status: dto.Status, TakerId: dto.TakerId, } - res := r.db.Create(&alert) + res := r.db.WithContext(ctx).Create(&alert) if res.Error != nil { return uuid.Nil, res.Error } - res = r.db.Model(&model.Alert{}). + res = r.db.WithContext(ctx).Model(&model.Alert{}). Where("id = ?", dto.AlertId). Update("status", dto.Status) if res.Error != nil { diff --git a/internal/repository/app-group.go b/internal/repository/app-group.go index bd824996..edaf6a37 100644 --- a/internal/repository/app-group.go +++ b/internal/repository/app-group.go @@ -1,6 +1,7 @@ package repository import ( + "context" "fmt" "gorm.io/datatypes" @@ -14,15 +15,15 @@ import ( // Interfaces type IAppGroupRepository interface { - 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 []model.Application, err error) - UpsertApplication(dto model.Application) error - InitWorkflow(appGroupId domain.AppGroupId, workflowId string, status domain.AppGroupStatus) error - InitWorkflowDescription(clusterId domain.ClusterId) error + Fetch(ctx context.Context, clusterId domain.ClusterId, pg *pagination.Pagination) (res []model.AppGroup, err error) + Get(ctx context.Context, id domain.AppGroupId) (model.AppGroup, error) + Create(ctx context.Context, dto model.AppGroup) (id domain.AppGroupId, err error) + Update(ctx context.Context, dto model.AppGroup) (err error) + Delete(ctx context.Context, id domain.AppGroupId) error + GetApplications(ctx context.Context, id domain.AppGroupId, applicationType domain.ApplicationType) (applications []model.Application, err error) + UpsertApplication(ctx context.Context, dto model.Application) error + InitWorkflow(ctx context.Context, appGroupId domain.AppGroupId, workflowId string, status domain.AppGroupStatus) error + InitWorkflowDescription(ctx context.Context, clusterId domain.ClusterId) error } type AppGroupRepository struct { @@ -36,12 +37,12 @@ func NewAppGroupRepository(db *gorm.DB) IAppGroupRepository { } // Logics -func (r *AppGroupRepository) Fetch(clusterId domain.ClusterId, pg *pagination.Pagination) (out []model.AppGroup, err error) { +func (r *AppGroupRepository) Fetch(ctx context.Context, clusterId domain.ClusterId, pg *pagination.Pagination) (out []model.AppGroup, err error) { if pg == nil { pg = pagination.NewPagination(nil) } - _, res := pg.Fetch(r.db.Model(&model.AppGroup{}). + _, res := pg.Fetch(r.db.WithContext(ctx).Model(&model.AppGroup{}). Where("cluster_id = ?", clusterId), &out) if res.Error != nil { return nil, res.Error @@ -50,15 +51,15 @@ func (r *AppGroupRepository) Fetch(clusterId domain.ClusterId, pg *pagination.Pa return out, nil } -func (r *AppGroupRepository) Get(id domain.AppGroupId) (out model.AppGroup, err error) { - res := r.db.First(&out, "id = ?", id) +func (r *AppGroupRepository) Get(ctx context.Context, id domain.AppGroupId) (out model.AppGroup, err error) { + res := r.db.WithContext(ctx).First(&out, "id = ?", id) if res.RowsAffected == 0 || res.Error != nil { return model.AppGroup{}, fmt.Errorf("Not found appGroup for %s", id) } return out, nil } -func (r *AppGroupRepository) Create(dto model.AppGroup) (appGroupId domain.AppGroupId, err error) { +func (r *AppGroupRepository) Create(ctx context.Context, dto model.AppGroup) (appGroupId domain.AppGroupId, err error) { appGroup := model.AppGroup{ ClusterId: dto.ClusterId, AppGroupType: dto.AppGroupType, @@ -68,7 +69,7 @@ func (r *AppGroupRepository) Create(dto model.AppGroup) (appGroupId domain.AppGr CreatorId: dto.CreatorId, UpdatorId: nil, } - res := r.db.Create(&appGroup) + res := r.db.WithContext(ctx).Create(&appGroup) if res.Error != nil { log.Error(res.Error) return "", res.Error @@ -77,8 +78,8 @@ func (r *AppGroupRepository) Create(dto model.AppGroup) (appGroupId domain.AppGr return appGroup.ID, nil } -func (r *AppGroupRepository) Update(dto model.AppGroup) (err error) { - res := r.db.Model(&model.AppGroup{}). +func (r *AppGroupRepository) Update(ctx context.Context, dto model.AppGroup) (err error) { + res := r.db.WithContext(ctx).Model(&model.AppGroup{}). Where("id = ?", dto.ID). Updates(map[string]interface{}{ "ClusterId": dto.ClusterId, @@ -93,24 +94,24 @@ func (r *AppGroupRepository) Update(dto model.AppGroup) (err error) { return nil } -func (r *AppGroupRepository) Delete(id domain.AppGroupId) error { - res := r.db.Unscoped().Delete(&model.AppGroup{}, "id = ?", id) +func (r *AppGroupRepository) Delete(ctx context.Context, id domain.AppGroupId) error { + res := r.db.WithContext(ctx).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 []model.Application, err error) { - res := r.db.Where("app_group_id = ? AND type = ?", id, applicationType).Find(&out) +func (r *AppGroupRepository) GetApplications(ctx context.Context, id domain.AppGroupId, applicationType domain.ApplicationType) (out []model.Application, err error) { + res := r.db.WithContext(ctx).Where("app_group_id = ? AND type = ?", id, applicationType).Find(&out) if res.Error != nil { return nil, res.Error } return out, nil } -func (r *AppGroupRepository) UpsertApplication(dto model.Application) error { - res := r.db.Where(model.Application{ +func (r *AppGroupRepository) UpsertApplication(ctx context.Context, dto model.Application) error { + res := r.db.WithContext(ctx).Where(model.Application{ AppGroupId: dto.AppGroupId, Type: dto.Type, }). @@ -125,8 +126,8 @@ func (r *AppGroupRepository) UpsertApplication(dto model.Application) error { return nil } -func (r *AppGroupRepository) InitWorkflow(appGroupId domain.AppGroupId, workflowId string, status domain.AppGroupStatus) error { - res := r.db.Model(&model.AppGroup{}). +func (r *AppGroupRepository) InitWorkflow(ctx context.Context, appGroupId domain.AppGroupId, workflowId string, status domain.AppGroupStatus) error { + res := r.db.WithContext(ctx).Model(&model.AppGroup{}). Where("ID = ?", appGroupId). Updates(map[string]interface{}{"Status": status, "WorkflowId": workflowId, "StatusDesc": ""}) @@ -137,8 +138,8 @@ func (r *AppGroupRepository) InitWorkflow(appGroupId domain.AppGroupId, workflow return nil } -func (r *AppGroupRepository) InitWorkflowDescription(clusterId domain.ClusterId) error { - res := r.db.Model(&model.AppGroup{}). +func (r *AppGroupRepository) InitWorkflowDescription(ctx context.Context, clusterId domain.ClusterId) error { + res := r.db.WithContext(ctx).Model(&model.AppGroup{}). Where("cluster_id = ?", clusterId). Updates(map[string]interface{}{"WorkflowId": "", "StatusDesc": ""}) diff --git a/internal/repository/app-serve-app.go b/internal/repository/app-serve-app.go index a1d3e291..d2089fe2 100644 --- a/internal/repository/app-serve-app.go +++ b/internal/repository/app-serve-app.go @@ -1,6 +1,7 @@ package repository import ( + "context" "fmt" "time" @@ -12,22 +13,22 @@ import ( ) type IAppServeAppRepository interface { - 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) ([]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) (int64, error) - IsAppServeAppNameExist(orgId string, appName string) (int64, 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) + CreateAppServeApp(ctx context.Context, app *model.AppServeApp) (appId string, taskId string, err error) + GetAppServeApps(ctx context.Context, organizationId string, showAll bool, pg *pagination.Pagination) ([]model.AppServeApp, error) + GetAppServeAppById(ctx context.Context, appId string) (*model.AppServeApp, error) + + GetAppServeAppTasksByAppId(ctx context.Context, appId string, pg *pagination.Pagination) ([]model.AppServeAppTask, error) + GetAppServeAppTaskById(ctx context.Context, taskId string) (*model.AppServeAppTask, *model.AppServeApp, error) + + GetAppServeAppLatestTask(ctx context.Context, appId string) (*model.AppServeAppTask, error) + GetNumOfAppsOnStack(ctx context.Context, organizationId string, clusterId string) (int64, error) + + IsAppServeAppExist(ctx context.Context, appId string) (int64, error) + IsAppServeAppNameExist(ctx context.Context, orgId string, appName string) (int64, error) + CreateTask(ctx context.Context, task *model.AppServeAppTask) (taskId string, err error) + UpdateStatus(ctx context.Context, appId string, taskId string, status string, output string) error + UpdateEndpoint(ctx context.Context, appId string, taskId string, endpoint string, previewEndpoint string, helmRevision int32) error + GetTaskCountById(ctx context.Context, appId string) (int64, error) } type AppServeAppRepository struct { @@ -40,9 +41,9 @@ func NewAppServeAppRepository(db *gorm.DB) IAppServeAppRepository { } } -func (r *AppServeAppRepository) CreateAppServeApp(app *model.AppServeApp) (appId string, taskId string, err error) { +func (r *AppServeAppRepository) CreateAppServeApp(ctx context.Context, app *model.AppServeApp) (appId string, taskId string, err error) { - res := r.db.Create(&app) + res := r.db.WithContext(ctx).Create(&app) if res.Error != nil { return "", "", res.Error } @@ -51,9 +52,8 @@ func (r *AppServeAppRepository) CreateAppServeApp(app *model.AppServeApp) (appId } // Update creates new appServeApp task for existing appServeApp. -func (r *AppServeAppRepository) CreateTask( - task *model.AppServeAppTask) (string, error) { - res := r.db.Create(task) +func (r *AppServeAppRepository) CreateTask(ctx context.Context, task *model.AppServeAppTask) (string, error) { + res := r.db.WithContext(ctx).Create(task) if res.Error != nil { return "", res.Error } @@ -61,14 +61,14 @@ func (r *AppServeAppRepository) CreateTask( return task.ID, nil } -func (r *AppServeAppRepository) GetAppServeApps(organizationId string, showAll bool, pg *pagination.Pagination) (apps []model.AppServeApp, err error) { +func (r *AppServeAppRepository) GetAppServeApps(ctx context.Context, 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(&model.AppServeApp{}). + _, res := pg.Fetch(r.db.WithContext(ctx).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) @@ -81,7 +81,7 @@ func (r *AppServeAppRepository) GetAppServeApps(organizationId string, showAll b // Add cluster names to apps list queryStr := fmt.Sprintf("organization_id = '%s' AND status <> '%d'", organizationId, domain.ClusterStatus_DELETED) - res = r.db.Find(&clusters, queryStr) + res = r.db.WithContext(ctx).Find(&clusters, queryStr) if res.Error != nil { return nil, fmt.Errorf("error while fetching clusters with organizationId: %s", organizationId) } @@ -98,11 +98,11 @@ func (r *AppServeAppRepository) GetAppServeApps(organizationId string, showAll b return } -func (r *AppServeAppRepository) GetAppServeAppById(appId string) (*model.AppServeApp, error) { +func (r *AppServeAppRepository) GetAppServeAppById(ctx context.Context, appId string) (*model.AppServeApp, error) { var app model.AppServeApp var cluster model.Cluster - res := r.db.Where("id = ?", appId).First(&app) + res := r.db.WithContext(ctx).Where("id = ?", appId).First(&app) if res.Error != nil { log.Debug(res.Error) return nil, res.Error @@ -112,24 +112,24 @@ func (r *AppServeAppRepository) GetAppServeAppById(appId string) (*model.AppServ } // Populate tasks into app object - if err := r.db.Model(&app).Order("created_at desc").Association("AppServeAppTasks").Find(&app.AppServeAppTasks); err != nil { + if err := r.db.WithContext(ctx).Model(&app).Order("created_at desc").Association("AppServeAppTasks").Find(&app.AppServeAppTasks); err != nil { log.Debug(err) return nil, err } // Add cluster name to app object - r.db.Select("name").Where("id = ?", app.TargetClusterId).First(&cluster) + r.db.WithContext(ctx).Select("name").Where("id = ?", app.TargetClusterId).First(&cluster) app.TargetClusterName = cluster.Name return &app, nil } -func (r *AppServeAppRepository) GetAppServeAppTasksByAppId(appId string, pg *pagination.Pagination) (tasks []model.AppServeAppTask, err error) { +func (r *AppServeAppRepository) GetAppServeAppTasksByAppId(ctx context.Context, appId string, pg *pagination.Pagination) (tasks []model.AppServeAppTask, err error) { if pg == nil { pg = pagination.NewPagination(nil) } - _, res := pg.Fetch(r.db.Model(&model.AppServeAppTask{}). + _, res := pg.Fetch(r.db.WithContext(ctx).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) @@ -144,12 +144,12 @@ func (r *AppServeAppRepository) GetAppServeAppTasksByAppId(appId string, pg *pag } // Return single task info along with its parent app info -func (r *AppServeAppRepository) GetAppServeAppTaskById(taskId string) (*model.AppServeAppTask, *model.AppServeApp, error) { +func (r *AppServeAppRepository) GetAppServeAppTaskById(ctx context.Context, 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) + res := r.db.WithContext(ctx).Where("id = ?", taskId).First(&task) if res.Error != nil { log.Debug(res.Error) return nil, nil, res.Error @@ -159,7 +159,7 @@ func (r *AppServeAppRepository) GetAppServeAppTaskById(taskId string) (*model.Ap } // Retrieve app info - res = r.db.Where("id = ?", task.AppServeAppId).First(&app) + res = r.db.WithContext(ctx).Where("id = ?", task.AppServeAppId).First(&app) if res.Error != nil { log.Debug(res.Error) return nil, nil, res.Error @@ -171,11 +171,11 @@ func (r *AppServeAppRepository) GetAppServeAppTaskById(taskId string) (*model.Ap return &task, &app, nil } -func (r *AppServeAppRepository) GetAppServeAppLatestTask(appId string) (*model.AppServeAppTask, error) { +func (r *AppServeAppRepository) GetAppServeAppLatestTask(ctx context.Context, 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) + res := r.db.WithContext(ctx).Order("created_at desc").First(&task) if res.Error != nil { log.Debug(res.Error) return nil, res.Error @@ -187,11 +187,11 @@ func (r *AppServeAppRepository) GetAppServeAppLatestTask(appId string) (*model.A return &task, nil } -func (r *AppServeAppRepository) GetNumOfAppsOnStack(organizationId string, clusterId string) (int64, error) { +func (r *AppServeAppRepository) GetNumOfAppsOnStack(ctx context.Context, organizationId string, clusterId string) (int64, error) { 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) + res := r.db.WithContext(ctx).Find(&apps, queryStr) if res.Error != nil { return -1, fmt.Errorf("Error while finding appServeApps with organizationId: %s", organizationId) } @@ -199,10 +199,10 @@ func (r *AppServeAppRepository) GetNumOfAppsOnStack(organizationId string, clust return res.RowsAffected, nil } -func (r *AppServeAppRepository) IsAppServeAppExist(appId string) (int64, error) { +func (r *AppServeAppRepository) IsAppServeAppExist(ctx context.Context, appId string) (int64, error) { var result int64 - res := r.db.Table("app_serve_apps").Where("id = ? AND status <> 'DELETE_SUCCESS'", appId).Count(&result) + res := r.db.WithContext(ctx).Table("app_serve_apps").Where("id = ? AND status <> 'DELETE_SUCCESS'", appId).Count(&result) if res.Error != nil { log.Debug(res.Error) return 0, res.Error @@ -210,7 +210,7 @@ func (r *AppServeAppRepository) IsAppServeAppExist(appId string) (int64, error) return result, nil } -func (r *AppServeAppRepository) IsAppServeAppNameExist(orgId string, appName string) (int64, error) { +func (r *AppServeAppRepository) IsAppServeAppNameExist(ctx context.Context, orgId string, appName string) (int64, error) { var result int64 queryString := fmt.Sprintf("organization_id = '%v' "+ @@ -218,7 +218,7 @@ func (r *AppServeAppRepository) IsAppServeAppNameExist(orgId string, appName str "AND status <> 'DELETE_SUCCESS'", orgId, appName) log.Info("query = ", queryString) - res := r.db.Table("app_serve_apps").Where(queryString).Count(&result) + res := r.db.WithContext(ctx).Table("app_serve_apps").Where(queryString).Count(&result) if res.Error != nil { log.Debug(res.Error) return 0, res.Error @@ -226,14 +226,14 @@ func (r *AppServeAppRepository) IsAppServeAppNameExist(orgId string, appName str return result, nil } -func (r *AppServeAppRepository) UpdateStatus(appId string, taskId string, status string, output string) error { +func (r *AppServeAppRepository) UpdateStatus(ctx context.Context, appId string, taskId string, status string, output string) error { now := time.Now() app := model.AppServeApp{ ID: appId, Status: status, UpdatedAt: &now, } - res := r.db.Model(&app).Select("Status", "UpdatedAt").Updates(app) + res := r.db.WithContext(ctx).Model(&app).Select("Status", "UpdatedAt").Updates(app) if res.Error != nil || res.RowsAffected == 0 { return fmt.Errorf("UpdateStatus: nothing updated in AppServeApp with ID %s", appId) } @@ -244,7 +244,7 @@ func (r *AppServeAppRepository) UpdateStatus(appId string, taskId string, status Output: output, UpdatedAt: &now, } - res = r.db.Model(&task).Select("Status", "Output", "UpdatedAt").Updates(task) + res = r.db.WithContext(ctx).Model(&task).Select("Status", "Output", "UpdatedAt").Updates(task) if res.Error != nil || res.RowsAffected == 0 { return fmt.Errorf("UpdateStatus: nothing updated in AppServeAppTask with ID %s", taskId) } @@ -269,7 +269,7 @@ func (r *AppServeAppRepository) UpdateStatus(appId string, taskId string, status return nil } -func (r *AppServeAppRepository) UpdateEndpoint(appId string, taskId string, endpoint string, previewEndpoint string, helmRevision int32) error { +func (r *AppServeAppRepository) UpdateEndpoint(ctx context.Context, appId string, taskId string, endpoint string, previewEndpoint string, helmRevision int32) error { now := time.Now() app := model.AppServeApp{ ID: appId, @@ -287,13 +287,13 @@ func (r *AppServeAppRepository) UpdateEndpoint(appId string, taskId string, endp var res *gorm.DB if endpoint != "" && previewEndpoint != "" { // Both endpoints are valid - res = r.db.Model(&app).Select("EndpointUrl", "PreviewEndpointUrl", "UpdatedAt").Updates(app) + res = r.db.WithContext(ctx).Model(&app).Select("EndpointUrl", "PreviewEndpointUrl", "UpdatedAt").Updates(app) } else if endpoint != "" { // endpoint-only case - res = r.db.Model(&app).Select("EndpointUrl", "UpdatedAt").Updates(app) + res = r.db.WithContext(ctx).Model(&app).Select("EndpointUrl", "UpdatedAt").Updates(app) } else if previewEndpoint != "" { // previewEndpoint-only case - res = r.db.Model(&app).Select("PreviewEndpointUrl", "UpdatedAt").Updates(app) + res = r.db.WithContext(ctx).Model(&app).Select("PreviewEndpointUrl", "UpdatedAt").Updates(app) } else { return fmt.Errorf("updateEndpoint: No endpoint provided. " + "At least one of [endpoint, preview_endpoint] should be provided") @@ -305,7 +305,7 @@ func (r *AppServeAppRepository) UpdateEndpoint(appId string, taskId string, endp // Update helm revision // Ignore if the value is less than 0 if helmRevision > 0 { - res = r.db.Model(&task).Select("HelmRevision", "UpdatedAt").Updates(task) + res = r.db.WithContext(ctx).Model(&task).Select("HelmRevision", "UpdatedAt").Updates(task) if res.Error != nil || res.RowsAffected == 0 { return fmt.Errorf("UpdateEndpoint: "+ "helm revision was not updated for AppServeAppTask with task ID %s", taskId) @@ -315,9 +315,9 @@ func (r *AppServeAppRepository) UpdateEndpoint(appId string, taskId string, endp return nil } -func (r *AppServeAppRepository) GetTaskCountById(appId string) (int64, error) { +func (r *AppServeAppRepository) GetTaskCountById(ctx context.Context, appId string) (int64, error) { var count int64 - if err := r.db.Model(&model.AppServeAppTask{}).Where("AppServeAppId = ?", appId).Count(&count); err != nil { + if err := r.db.WithContext(ctx).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 f7e0c5dd..8d9a594f 100644 --- a/internal/repository/audit.go +++ b/internal/repository/audit.go @@ -1,6 +1,7 @@ package repository import ( + "context" "fmt" "github.com/google/uuid" @@ -13,10 +14,10 @@ import ( // Interfaces type IAuditRepository interface { - 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) + 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, auditId uuid.UUID) (err error) } type AuditRepository struct { @@ -30,20 +31,20 @@ func NewAuditRepository(db *gorm.DB) IAuditRepository { } // Logics -func (r *AuditRepository) Get(auditId uuid.UUID) (out model.Audit, err error) { - res := r.db.Preload(clause.Associations).First(&out, "id = ?", auditId) +func (r *AuditRepository) Get(ctx context.Context, auditId uuid.UUID) (out model.Audit, err error) { + res := r.db.WithContext(ctx).Preload(clause.Associations).First(&out, "id = ?", auditId) if res.Error != nil { return } return } -func (r *AuditRepository) Fetch(pg *pagination.Pagination) (out []model.Audit, err error) { +func (r *AuditRepository) Fetch(ctx context.Context, pg *pagination.Pagination) (out []model.Audit, err error) { if pg == nil { pg = pagination.NewPagination(nil) } - db := r.db.Model(&model.Audit{}).Preload(clause.Associations) + db := r.db.WithContext(ctx).Model(&model.Audit{}).Preload(clause.Associations) _, res := pg.Fetch(db, &out) if res.Error != nil { return nil, res.Error @@ -51,7 +52,7 @@ func (r *AuditRepository) Fetch(pg *pagination.Pagination) (out []model.Audit, e return } -func (r *AuditRepository) Create(dto model.Audit) (auditId uuid.UUID, err error) { +func (r *AuditRepository) Create(ctx context.Context, dto model.Audit) (auditId uuid.UUID, err error) { audit := model.Audit{ OrganizationId: dto.OrganizationId, Group: dto.Group, @@ -59,13 +60,13 @@ func (r *AuditRepository) Create(dto model.Audit) (auditId uuid.UUID, err error) Description: dto.Description, ClientIP: dto.ClientIP, UserId: dto.UserId} - res := r.db.Create(&audit) + res := r.db.WithContext(ctx).Create(&audit) if res.Error != nil { return uuid.Nil, res.Error } return audit.ID, nil } -func (r *AuditRepository) Delete(auditId uuid.UUID) (err error) { +func (r *AuditRepository) Delete(ctx context.Context, auditId uuid.UUID) (err error) { return fmt.Errorf("to be implemented") } diff --git a/internal/repository/auth.go b/internal/repository/auth.go index 3c2c980a..d9c86a59 100644 --- a/internal/repository/auth.go +++ b/internal/repository/auth.go @@ -1,15 +1,16 @@ package repository import ( + "context" "github.com/google/uuid" "gorm.io/gorm" ) type IAuthRepository interface { - CreateEmailCode(userId uuid.UUID, code string) error - GetEmailCode(userId uuid.UUID) (CacheEmailCode, error) - UpdateEmailCode(userId uuid.UUID, code string) error - DeleteEmailCode(userId uuid.UUID) error + CreateEmailCode(ctx context.Context, userId uuid.UUID, code string) error + GetEmailCode(ctx context.Context, userId uuid.UUID) (CacheEmailCode, error) + UpdateEmailCode(ctx context.Context, userId uuid.UUID, code string) error + DeleteEmailCode(ctx context.Context, userId uuid.UUID) error } type AuthRepository struct { @@ -31,26 +32,26 @@ func NewAuthRepository(db *gorm.DB) IAuthRepository { } } -func (r *AuthRepository) CreateEmailCode(userId uuid.UUID, code string) error { +func (r *AuthRepository) CreateEmailCode(ctx context.Context, userId uuid.UUID, code string) error { cacheEmailCode := CacheEmailCode{ UserId: userId, Code: code, } - return r.db.Create(&cacheEmailCode).Error + return r.db.WithContext(ctx).Create(&cacheEmailCode).Error } -func (r *AuthRepository) GetEmailCode(userId uuid.UUID) (CacheEmailCode, error) { +func (r *AuthRepository) GetEmailCode(ctx context.Context, userId uuid.UUID) (CacheEmailCode, error) { var cacheEmailCode CacheEmailCode - if err := r.db.Where("user_id = ?", userId).First(&cacheEmailCode).Error; err != nil { + if err := r.db.WithContext(ctx).Where("user_id = ?", userId).First(&cacheEmailCode).Error; err != nil { return CacheEmailCode{}, err } return cacheEmailCode, nil } -func (r *AuthRepository) UpdateEmailCode(userId uuid.UUID, code string) error { - return r.db.Model(&CacheEmailCode{}).Where("user_id = ?", userId).Update("code", code).Error +func (r *AuthRepository) UpdateEmailCode(ctx context.Context, userId uuid.UUID, code string) error { + return r.db.WithContext(ctx).Model(&CacheEmailCode{}).Where("user_id = ?", userId).Update("code", code).Error } -func (r *AuthRepository) DeleteEmailCode(userId uuid.UUID) error { - return r.db.Unscoped().Where("user_id = ?", userId).Delete(&CacheEmailCode{}).Error +func (r *AuthRepository) DeleteEmailCode(ctx context.Context, userId uuid.UUID) error { + return r.db.WithContext(ctx).Unscoped().Where("user_id = ?", userId).Delete(&CacheEmailCode{}).Error } diff --git a/internal/repository/cloud-account.go b/internal/repository/cloud-account.go index 08f635c8..72508451 100644 --- a/internal/repository/cloud-account.go +++ b/internal/repository/cloud-account.go @@ -1,6 +1,7 @@ package repository import ( + "context" "fmt" "github.com/google/uuid" @@ -14,14 +15,14 @@ import ( // Interfaces type ICloudAccountRepository interface { - 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) + 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) + 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) (err error) + Delete(ctx context.Context, cloudAccountId uuid.UUID) (err error) + InitWorkflow(ctx context.Context, cloudAccountId uuid.UUID, workflowId string, status domain.CloudAccountStatus) (err error) } type CloudAccountRepository struct { @@ -35,35 +36,35 @@ func NewCloudAccountRepository(db *gorm.DB) ICloudAccountRepository { } // Logics -func (r *CloudAccountRepository) Get(cloudAccountId uuid.UUID) (out model.CloudAccount, err error) { - res := r.db.Preload(clause.Associations).First(&out, "id = ?", cloudAccountId) +func (r *CloudAccountRepository) Get(ctx context.Context, cloudAccountId uuid.UUID) (out model.CloudAccount, err error) { + res := r.db.WithContext(ctx).Preload(clause.Associations).First(&out, "id = ?", cloudAccountId) if res.Error != nil { return model.CloudAccount{}, res.Error } return } -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) +func (r *CloudAccountRepository) GetByName(ctx context.Context, organizationId string, name string) (out model.CloudAccount, err error) { + res := r.db.WithContext(ctx).Preload(clause.Associations).First(&out, "organization_id = ? AND name = ?", organizationId, name) if res.Error != nil { return model.CloudAccount{}, res.Error } return } -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) +func (r *CloudAccountRepository) GetByAwsAccountId(ctx context.Context, awsAccountId string) (out model.CloudAccount, err error) { + res := r.db.WithContext(ctx).Preload(clause.Associations).First(&out, "aws_account_id = ? AND status != ?", awsAccountId, domain.CloudAccountStatus_DELETED) if res.Error != nil { return model.CloudAccount{}, res.Error } return } -func (r *CloudAccountRepository) Fetch(organizationId string, pg *pagination.Pagination) (out []model.CloudAccount, err error) { +func (r *CloudAccountRepository) Fetch(ctx context.Context, organizationId string, pg *pagination.Pagination) (out []model.CloudAccount, err error) { if pg == nil { pg = pagination.NewPagination(nil) } - _, res := pg.Fetch(r.db.Model(&model.CloudAccount{}). + _, res := pg.Fetch(r.db.WithContext(ctx).Model(&model.CloudAccount{}). Preload(clause.Associations). Where("organization_id = ? AND status != ?", organizationId, domain.CloudAccountStatus_DELETED), &out) if res.Error != nil { @@ -72,7 +73,7 @@ func (r *CloudAccountRepository) Fetch(organizationId string, pg *pagination.Pag return } -func (r *CloudAccountRepository) Create(dto model.CloudAccount) (cloudAccountId uuid.UUID, err error) { +func (r *CloudAccountRepository) Create(ctx context.Context, dto model.CloudAccount) (cloudAccountId uuid.UUID, err error) { cloudAccount := model.CloudAccount{ OrganizationId: dto.OrganizationId, Name: dto.Name, @@ -83,15 +84,15 @@ func (r *CloudAccountRepository) Create(dto model.CloudAccount) (cloudAccountId CreatedIAM: false, Status: domain.CloudAccountStatus_PENDING, CreatorId: dto.CreatorId} - res := r.db.Create(&cloudAccount) + res := r.db.WithContext(ctx).Create(&cloudAccount) if res.Error != nil { return uuid.Nil, res.Error } return cloudAccount.ID, nil } -func (r *CloudAccountRepository) Update(dto model.CloudAccount) (err error) { - res := r.db.Model(&model.CloudAccount{}). +func (r *CloudAccountRepository) Update(ctx context.Context, dto model.CloudAccount) (err error) { + res := r.db.WithContext(ctx).Model(&model.CloudAccount{}). Where("id = ?", dto.ID). Updates(map[string]interface{}{"Description": dto.Description, "Resource": dto.Resource, "UpdatorId": dto.UpdatorId}) if res.Error != nil { @@ -100,16 +101,16 @@ func (r *CloudAccountRepository) Update(dto model.CloudAccount) (err error) { return nil } -func (r *CloudAccountRepository) Delete(cloudAccountId uuid.UUID) (err error) { - res := r.db.Delete(&model.CloudAccount{}, "id = ?", cloudAccountId) +func (r *CloudAccountRepository) Delete(ctx context.Context, cloudAccountId uuid.UUID) (err error) { + res := r.db.WithContext(ctx).Delete(&model.CloudAccount{}, "id = ?", cloudAccountId) if res.Error != nil { return res.Error } return nil } -func (r *CloudAccountRepository) InitWorkflow(cloudAccountId uuid.UUID, workflowId string, status domain.CloudAccountStatus) error { - res := r.db.Model(&model.CloudAccount{}). +func (r *CloudAccountRepository) InitWorkflow(ctx context.Context, cloudAccountId uuid.UUID, workflowId string, status domain.CloudAccountStatus) error { + res := r.db.WithContext(ctx).Model(&model.CloudAccount{}). Where("ID = ?", cloudAccountId). Updates(map[string]interface{}{"Status": status, "WorkflowId": workflowId}) diff --git a/internal/repository/cluster.go b/internal/repository/cluster.go index 05d2cb00..7d92bdc5 100644 --- a/internal/repository/cluster.go +++ b/internal/repository/cluster.go @@ -1,6 +1,7 @@ package repository import ( + "context" "fmt" "github.com/google/uuid" @@ -17,20 +18,20 @@ import ( // Interfaces type IClusterRepository interface { WithTrx(*gorm.DB) IClusterRepository - 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 + Fetch(ctx context.Context, pg *pagination.Pagination) (res []model.Cluster, err error) + FetchByCloudAccountId(ctx context.Context, cloudAccountId uuid.UUID, pg *pagination.Pagination) (res []model.Cluster, err error) + FetchByOrganizationId(ctx context.Context, organizationId string, userId uuid.UUID, pg *pagination.Pagination) (res []model.Cluster, err error) + Get(ctx context.Context, id domain.ClusterId) (model.Cluster, error) + GetByName(ctx context.Context, organizationId string, name string) (model.Cluster, error) + Create(ctx context.Context, dto model.Cluster) (clusterId domain.ClusterId, err error) + Update(ctx context.Context, dto model.Cluster) (err error) + Delete(ctx context.Context, id domain.ClusterId) error - InitWorkflow(clusterId domain.ClusterId, workflowId string, status domain.ClusterStatus) error - InitWorkflowDescription(clusterId domain.ClusterId) error + InitWorkflow(ctx context.Context, clusterId domain.ClusterId, workflowId string, status domain.ClusterStatus) error + InitWorkflowDescription(ctx context.Context, clusterId domain.ClusterId) error - SetFavorite(clusterId domain.ClusterId, userId uuid.UUID) error - DeleteFavorite(clusterId domain.ClusterId, userId uuid.UUID) error + SetFavorite(ctx context.Context, clusterId domain.ClusterId, userId uuid.UUID) error + DeleteFavorite(ctx context.Context, clusterId domain.ClusterId, userId uuid.UUID) error } type ClusterRepository struct { @@ -55,12 +56,12 @@ func (r *ClusterRepository) WithTrx(trxHandle *gorm.DB) IClusterRepository { return r } -func (r *ClusterRepository) Fetch(pg *pagination.Pagination) (out []model.Cluster, err error) { +func (r *ClusterRepository) Fetch(ctx context.Context, pg *pagination.Pagination) (out []model.Cluster, err error) { if pg == nil { pg = pagination.NewPagination(nil) } - _, res := pg.Fetch(r.db.Model(&model.Cluster{}).Preload(clause.Associations), &out) + _, res := pg.Fetch(r.db.WithContext(ctx).Model(&model.Cluster{}).Preload(clause.Associations), &out) if res.Error != nil { return nil, res.Error } @@ -68,12 +69,12 @@ func (r *ClusterRepository) Fetch(pg *pagination.Pagination) (out []model.Cluste return } -func (r *ClusterRepository) FetchByOrganizationId(organizationId string, userId uuid.UUID, pg *pagination.Pagination) (out []model.Cluster, err error) { +func (r *ClusterRepository) FetchByOrganizationId(ctx context.Context, 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(&model.Cluster{}). + _, res := pg.Fetch(r.db.WithContext(ctx).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). @@ -84,11 +85,11 @@ func (r *ClusterRepository) FetchByOrganizationId(organizationId string, userId return } -func (r *ClusterRepository) FetchByCloudAccountId(cloudAccountId uuid.UUID, pg *pagination.Pagination) (out []model.Cluster, err error) { +func (r *ClusterRepository) FetchByCloudAccountId(ctx context.Context, cloudAccountId uuid.UUID, pg *pagination.Pagination) (out []model.Cluster, err error) { if pg == nil { pg = pagination.NewPagination(nil) } - _, res := pg.Fetch(r.db.Model(&model.Cluster{}).Preload("CloudAccount"). + _, res := pg.Fetch(r.db.WithContext(ctx).Model(&model.Cluster{}).Preload("CloudAccount"). Where("cloud_account_id = ?", cloudAccountId), &out) if res.Error != nil { return nil, res.Error @@ -96,23 +97,23 @@ func (r *ClusterRepository) FetchByCloudAccountId(cloudAccountId uuid.UUID, pg * return } -func (r *ClusterRepository) Get(id domain.ClusterId) (out model.Cluster, err error) { - res := r.db.Preload(clause.Associations).First(&out, "id = ?", id) +func (r *ClusterRepository) Get(ctx context.Context, id domain.ClusterId) (out model.Cluster, err error) { + res := r.db.WithContext(ctx).Preload(clause.Associations).First(&out, "id = ?", id) if res.Error != nil { return model.Cluster{}, res.Error } return } -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) +func (r *ClusterRepository) GetByName(ctx context.Context, organizationId string, name string) (out model.Cluster, err error) { + res := r.db.WithContext(ctx).Preload(clause.Associations).First(&out, "organization_id = ? AND name = ?", organizationId, name) if res.Error != nil { return model.Cluster{}, res.Error } return } -func (r *ClusterRepository) Create(dto model.Cluster) (clusterId domain.ClusterId, err error) { +func (r *ClusterRepository) Create(ctx context.Context, 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 { @@ -147,7 +148,7 @@ func (r *ClusterRepository) Create(dto model.Cluster) (clusterId domain.ClusterI cluster.ID = dto.ID } - res := r.db.Create(&cluster) + res := r.db.WithContext(ctx).Create(&cluster) if res.Error != nil { log.Error(res.Error) return "", res.Error @@ -156,16 +157,16 @@ func (r *ClusterRepository) Create(dto model.Cluster) (clusterId domain.ClusterI return cluster.ID, nil } -func (r *ClusterRepository) Delete(clusterId domain.ClusterId) error { - res := r.db.Unscoped().Delete(&model.Cluster{}, "id = ?", clusterId) +func (r *ClusterRepository) Delete(ctx context.Context, clusterId domain.ClusterId) error { + res := r.db.WithContext(ctx).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 model.Cluster) error { - res := r.db.Model(&model.Cluster{}). +func (r *ClusterRepository) Update(ctx context.Context, dto model.Cluster) error { + res := r.db.WithContext(ctx).Model(&model.Cluster{}). Where("id = ?", dto.ID). Updates(map[string]interface{}{"Description": dto.Description, "UpdatorId": dto.UpdatorId}) if res.Error != nil { @@ -174,8 +175,8 @@ func (r *ClusterRepository) Update(dto model.Cluster) error { return nil } -func (r *ClusterRepository) InitWorkflow(clusterId domain.ClusterId, workflowId string, status domain.ClusterStatus) error { - res := r.db.Model(&model.Cluster{}). +func (r *ClusterRepository) InitWorkflow(ctx context.Context, clusterId domain.ClusterId, workflowId string, status domain.ClusterStatus) error { + res := r.db.WithContext(ctx).Model(&model.Cluster{}). Where("ID = ?", clusterId). Updates(map[string]interface{}{"Status": status, "WorkflowId": workflowId, "StatusDesc": ""}) @@ -186,8 +187,8 @@ func (r *ClusterRepository) InitWorkflow(clusterId domain.ClusterId, workflowId return nil } -func (r *ClusterRepository) InitWorkflowDescription(clusterId domain.ClusterId) error { - res := r.db.Model(&model.AppGroup{}). +func (r *ClusterRepository) InitWorkflowDescription(ctx context.Context, clusterId domain.ClusterId) error { + res := r.db.WithContext(ctx).Model(&model.AppGroup{}). Where("id = ?", clusterId). Updates(map[string]interface{}{"WorkflowId": "", "StatusDesc": ""}) @@ -198,9 +199,9 @@ func (r *ClusterRepository) InitWorkflowDescription(clusterId domain.ClusterId) return nil } -func (r *ClusterRepository) SetFavorite(clusterId domain.ClusterId, userId uuid.UUID) error { +func (r *ClusterRepository) SetFavorite(ctx context.Context, clusterId domain.ClusterId, userId uuid.UUID) error { var clusterFavorites []model.ClusterFavorite - res := r.db.Where("cluster_id = ? AND user_id = ?", clusterId, userId).Find(&clusterFavorites) + res := r.db.WithContext(ctx).Where("cluster_id = ? AND user_id = ?", clusterId, userId).Find(&clusterFavorites) if res.Error != nil { log.Info(res.Error) return res.Error @@ -223,8 +224,8 @@ func (r *ClusterRepository) SetFavorite(clusterId domain.ClusterId, userId uuid. return nil } -func (r *ClusterRepository) DeleteFavorite(clusterId domain.ClusterId, userId uuid.UUID) error { - res := r.db.Unscoped().Delete(&model.ClusterFavorite{}, "cluster_id = ? AND user_id = ?", clusterId, userId) +func (r *ClusterRepository) DeleteFavorite(ctx context.Context, clusterId domain.ClusterId, userId uuid.UUID) error { + res := r.db.WithContext(ctx).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) diff --git a/internal/repository/endpoint.go b/internal/repository/endpoint.go index 2b290779..e1230aeb 100644 --- a/internal/repository/endpoint.go +++ b/internal/repository/endpoint.go @@ -1,6 +1,7 @@ package repository import ( + "context" "fmt" "math" @@ -10,9 +11,9 @@ import ( ) type IEndpointRepository interface { - Create(endpoint *model.Endpoint) error - List(pg *pagination.Pagination) ([]*model.Endpoint, error) - Get(id uint) (*model.Endpoint, error) + Create(ctx context.Context, endpoint *model.Endpoint) error + List(ctx context.Context, pg *pagination.Pagination) ([]*model.Endpoint, error) + Get(ctx context.Context, id uint) (*model.Endpoint, error) } type EndpointRepository struct { @@ -25,20 +26,20 @@ func NewEndpointRepository(db *gorm.DB) *EndpointRepository { } } -func (e *EndpointRepository) Create(endpoint *model.Endpoint) error { +func (e *EndpointRepository) Create(ctx context.Context, endpoint *model.Endpoint) error { obj := &model.Endpoint{ Name: endpoint.Name, Group: endpoint.Group, } - if err := e.db.Create(obj).Error; err != nil { + if err := e.db.WithContext(ctx).Create(obj).Error; err != nil { return err } return nil } -func (e *EndpointRepository) List(pg *pagination.Pagination) ([]*model.Endpoint, error) { +func (e *EndpointRepository) List(ctx context.Context, pg *pagination.Pagination) ([]*model.Endpoint, error) { var endpoints []*model.Endpoint if pg == nil { @@ -51,7 +52,7 @@ func (e *EndpointRepository) List(pg *pagination.Pagination) ([]*model.Endpoint, pg.TotalPages = int(math.Ceil(float64(pg.TotalRows) / float64(pg.Limit))) orderQuery := fmt.Sprintf("%s %s", pg.SortColumn, pg.SortOrder) - res := db.Offset(pg.GetOffset()).Limit(pg.GetLimit()).Order(orderQuery).Find(&endpoints) + res := db.WithContext(ctx).Offset(pg.GetOffset()).Limit(pg.GetLimit()).Order(orderQuery).Find(&endpoints) if res.Error != nil { return nil, res.Error } @@ -59,10 +60,10 @@ func (e *EndpointRepository) List(pg *pagination.Pagination) ([]*model.Endpoint, return endpoints, nil } -func (e *EndpointRepository) Get(id uint) (*model.Endpoint, error) { +func (e *EndpointRepository) Get(ctx context.Context, id uint) (*model.Endpoint, error) { var obj model.Endpoint - if err := e.db.Preload("Permission").First(&obj, "id = ?", id).Error; err != nil { + if err := e.db.WithContext(ctx).Preload("Permission").First(&obj, "id = ?", id).Error; err != nil { return nil, err } diff --git a/internal/repository/organization.go b/internal/repository/organization.go index 7b21fb77..072b2d6a 100644 --- a/internal/repository/organization.go +++ b/internal/repository/organization.go @@ -1,6 +1,7 @@ package repository import ( + "context" "github.com/google/uuid" "github.com/openinfradev/tks-api/internal/model" "github.com/openinfradev/tks-api/internal/pagination" @@ -12,14 +13,14 @@ import ( // Interfaces type IOrganizationRepository interface { - Create(dto *model.Organization) (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 - UpdateAdminId(organizationId string, adminId uuid.UUID) error - Delete(organizationId string) (err error) - InitWorkflow(organizationId string, workflowId string, status domain.OrganizationStatus) error + Create(ctx context.Context, dto *model.Organization) (model.Organization, error) + Fetch(ctx context.Context, pg *pagination.Pagination) (res *[]model.Organization, err error) + Get(ctx context.Context, organizationId string) (res model.Organization, err error) + Update(ctx context.Context, organizationId string, in domain.UpdateOrganizationRequest) (model.Organization, error) + UpdatePrimaryClusterId(ctx context.Context, organizationId string, primaryClusterId string) error + UpdateAdminId(ctx context.Context, organizationId string, adminId uuid.UUID) error + Delete(ctx context.Context, organizationId string) (err error) + InitWorkflow(ctx context.Context, organizationId string, workflowId string, status domain.OrganizationStatus) error } type OrganizationRepository struct { @@ -53,7 +54,7 @@ func NewOrganizationRepository(db *gorm.DB) IOrganizationRepository { // return nil //} -func (r *OrganizationRepository) Create(dto *model.Organization) (model.Organization, error) { +func (r *OrganizationRepository) Create(ctx context.Context, dto *model.Organization) (model.Organization, error) { organization := model.Organization{ ID: dto.ID, Name: dto.Name, @@ -62,7 +63,7 @@ func (r *OrganizationRepository) Create(dto *model.Organization) (model.Organiza Status: domain.OrganizationStatus_PENDING, Phone: dto.Phone, } - res := r.db.Create(&organization) + res := r.db.WithContext(ctx).Create(&organization) if res.Error != nil { log.Errorf("error is :%s(%T)", res.Error.Error(), res.Error) return model.Organization{}, res.Error @@ -71,20 +72,20 @@ func (r *OrganizationRepository) Create(dto *model.Organization) (model.Organiza return organization, nil } -func (r *OrganizationRepository) Fetch(pg *pagination.Pagination) (out *[]model.Organization, err error) { +func (r *OrganizationRepository) Fetch(ctx context.Context, pg *pagination.Pagination) (out *[]model.Organization, err error) { if pg == nil { pg = pagination.NewPagination(nil) } - _, res := pg.Fetch(r.db.Preload(clause.Associations), &out) + _, res := pg.Fetch(r.db.WithContext(ctx).Preload(clause.Associations), &out) if res.Error != nil { return nil, res.Error } return } -func (r *OrganizationRepository) Get(id string) (out model.Organization, err error) { - res := r.db.Preload(clause.Associations). +func (r *OrganizationRepository) Get(ctx context.Context, id string) (out model.Organization, err error) { + res := r.db.WithContext(ctx).Preload(clause.Associations). First(&out, "id = ?", id) if res.Error != nil { log.Errorf("error is :%s(%T)", res.Error.Error(), res.Error) @@ -93,8 +94,8 @@ func (r *OrganizationRepository) Get(id string) (out model.Organization, err err return } -func (r *OrganizationRepository) Update(organizationId string, in domain.UpdateOrganizationRequest) (out model.Organization, err error) { - res := r.db.Model(&model.Organization{}). +func (r *OrganizationRepository) Update(ctx context.Context, organizationId string, in domain.UpdateOrganizationRequest) (out model.Organization, err error) { + res := r.db.WithContext(ctx).Model(&model.Organization{}). Where("id = ?", organizationId). Updates(map[string]interface{}{ "name": in.Name, @@ -114,8 +115,8 @@ func (r *OrganizationRepository) Update(organizationId string, in domain.UpdateO return } -func (r *OrganizationRepository) UpdatePrimaryClusterId(organizationId string, primaryClusterId string) error { - res := r.db.Model(&model.Organization{}). +func (r *OrganizationRepository) UpdatePrimaryClusterId(ctx context.Context, organizationId string, primaryClusterId string) error { + res := r.db.WithContext(ctx).Model(&model.Organization{}). Where("id = ?", organizationId). Updates(map[string]interface{}{ "primary_cluster_id": primaryClusterId, @@ -128,8 +129,8 @@ func (r *OrganizationRepository) UpdatePrimaryClusterId(organizationId string, p return nil } -func (r *OrganizationRepository) UpdateAdminId(organizationId string, adminId uuid.UUID) (err error) { - res := r.db.Model(&model.Organization{}). +func (r *OrganizationRepository) UpdateAdminId(ctx context.Context, organizationId string, adminId uuid.UUID) (err error) { + res := r.db.WithContext(ctx).Model(&model.Organization{}). Where("id = ?", organizationId). Updates(map[string]interface{}{ "admin_id": adminId, @@ -142,8 +143,8 @@ func (r *OrganizationRepository) UpdateAdminId(organizationId string, adminId uu return nil } -func (r *OrganizationRepository) Delete(organizationId string) error { - res := r.db.Delete(&model.Organization{}, "id = ?", organizationId) +func (r *OrganizationRepository) Delete(ctx context.Context, organizationId string) error { + res := r.db.WithContext(ctx).Delete(&model.Organization{}, "id = ?", organizationId) if res.Error != nil { log.Errorf("error is :%s(%T)", res.Error.Error(), res.Error) return res.Error @@ -152,8 +153,8 @@ func (r *OrganizationRepository) Delete(organizationId string) error { return nil } -func (r *OrganizationRepository) InitWorkflow(organizationId string, workflowId string, status domain.OrganizationStatus) error { - res := r.db.Model(&model.Organization{}). +func (r *OrganizationRepository) InitWorkflow(ctx context.Context, organizationId string, workflowId string, status domain.OrganizationStatus) error { + res := r.db.WithContext(ctx).Model(&model.Organization{}). Where("ID = ?", organizationId). Updates(map[string]interface{}{"Status": status, "WorkflowId": workflowId}) if res.Error != nil { diff --git a/internal/repository/permission.go b/internal/repository/permission.go index ebed52e6..335ce2e4 100644 --- a/internal/repository/permission.go +++ b/internal/repository/permission.go @@ -1,17 +1,18 @@ package repository import ( + "context" "github.com/google/uuid" "github.com/openinfradev/tks-api/internal/model" "gorm.io/gorm" ) type IPermissionRepository interface { - 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 *model.Permission) error + Create(ctx context.Context, permission *model.Permission) error + List(ctx context.Context, roleId string) ([]*model.Permission, error) + Get(ctx context.Context, id uuid.UUID) (*model.Permission, error) + Delete(ctx context.Context, id uuid.UUID) error + Update(ctx context.Context, permission *model.Permission) error } type PermissionRepository struct { @@ -24,7 +25,7 @@ func NewPermissionRepository(db *gorm.DB) *PermissionRepository { } } -func (r PermissionRepository) Create(p *model.Permission) error { +func (r PermissionRepository) Create(ctx context.Context, p *model.Permission) error { //var parent *Permission //var children []*Permission // @@ -46,13 +47,13 @@ func (r PermissionRepository) Create(p *model.Permission) error { // } //} - return r.db.Create(p).Error + return r.db.WithContext(ctx).Create(p).Error } -func (r PermissionRepository) List(roleId string) ([]*model.Permission, error) { +func (r PermissionRepository) List(ctx context.Context, 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 + err := r.db.WithContext(ctx).Preload("Children.Children.Children.Children").Where("parent_id IS NULL AND role_id = ?", roleId).Find(&permissions).Error if err != nil { return nil, err } @@ -60,9 +61,9 @@ func (r PermissionRepository) List(roleId string) ([]*model.Permission, error) { return permissions, nil } -func (r PermissionRepository) Get(id uuid.UUID) (*model.Permission, error) { +func (r PermissionRepository) Get(ctx context.Context, id uuid.UUID) (*model.Permission, error) { permission := &model.Permission{} - result := r.db.Preload("Children.Children.Children").Preload("Parent").First(&permission, "id = ?", id) + result := r.db.WithContext(ctx).Preload("Children.Children.Children").Preload("Parent").First(&permission, "id = ?", id) if result.Error != nil { return nil, result.Error } @@ -70,11 +71,11 @@ func (r PermissionRepository) Get(id uuid.UUID) (*model.Permission, error) { return permission, nil } -func (r PermissionRepository) Delete(id uuid.UUID) error { - return r.db.Delete(&model.Permission{}, "id = ?", id).Error +func (r PermissionRepository) Delete(ctx context.Context, id uuid.UUID) error { + return r.db.WithContext(ctx).Delete(&model.Permission{}, "id = ?", id).Error } -func (r PermissionRepository) Update(p *model.Permission) error { +func (r PermissionRepository) Update(ctx context.Context, p *model.Permission) error { // update on is_allowed - return r.db.Model(&model.Permission{}).Where("id = ?", p.ID).Updates(map[string]interface{}{"is_allowed": p.IsAllowed}).Error + return r.db.WithContext(ctx).Model(&model.Permission{}).Where("id = ?", p.ID).Updates(map[string]interface{}{"is_allowed": p.IsAllowed}).Error } diff --git a/internal/repository/permission_test.go b/internal/repository/permission_test.go deleted file mode 100644 index dad9d96e..00000000 --- a/internal/repository/permission_test.go +++ /dev/null @@ -1,445 +0,0 @@ -package repository_test - -import ( - "encoding/json" - "fmt" - "github.com/openinfradev/tks-api/internal/helper" - "github.com/openinfradev/tks-api/internal/repository" - "github.com/openinfradev/tks-api/pkg/domain" - "gorm.io/driver/postgres" - "gorm.io/gorm" - "gorm_test/config" - "testing" -) - -func TestPermission(t *testing.T) { - db := db_connection() - - db.AutoMigrate(&repository.Permission{}) - - //model := domain.Permission{ - // Name: "대시보드", - //} - - repo := repository.NewPermissionRepository(db) - - permissions, err := repo.List() - if err != nil { - t.Fatal(err) - } - out, err := json.MarshalIndent(permissions, "", " ") - if err != nil { - t.Fatal(err) - } - t.Log("start") - t.Logf("permission: %s", string(out)) - t.Log("end") - - //t.Logf("permission: %+v", permissions) - - // - //for _, permission := range permissions { - // // encoding to json - // b, err := json.Marshal(permission) - // if err != nil { - // t.Fatal(err) - // } - // t.Logf("permission: %s", string(b)) - //} - // - ////create - - //if err := repo.Create(dashboard); err != nil { - // t.Fatal(err) - //} - //if err := repo.Create(stack); err != nil { - // t.Fatal(err) - //} - //if err := repo.Create(security_policy); err != nil { - // t.Fatal(err) - //} - //if err := repo.Create(projectManagement); err != nil { - // t.Fatal(err) - //} - //if err := repo.Create(notification); err != nil { - // t.Fatal(err) - //} - //if err := repo.Create(configuration); err != nil { - // t.Fatal(err) - //} - - // get - //permission, err := repo.Get(uuid.MustParse("fd4363a7-d1d2-4feb-b976-b87d99a775c4")) - //if err != nil { - // t.Fatal(err) - //} - //out, err := json.Marshal(permission) - //if err != nil { - // t.Fatal(err) - //} - //t.Logf("permission: %s", string(out)) - - // print json pretty - //out, err := json.MarshalIndent(permission, "", " ") - //if err != nil { - // t.Fatal(err) - //} - //t.Logf("permission: %s", string(out)) - -} - -func db_connection() *gorm.DB { - conf := config.NewDefaultConfig() - dsn := fmt.Sprintf( - "host=%s dbname=%s user=%s password=%s port=%d sslmode=disable TimeZone=Asia/Seoul", - conf.Address, conf.Database, conf.AdminId, conf.AdminPassword, conf.Port, - ) - - db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{}) - if err != nil { - panic(err) - } - - return db -} - -var dashboard = &domain.Permission{ - Name: "대시보드", - Children: []*domain.Permission{ - { - Name: "대시보드", - Children: []*domain.Permission{ - { - Name: "조회", - IsAllowed: helper.BoolP(false), - }, - }, - }, - { - Name: "대시보드 설정", - Children: []*domain.Permission{ - { - Name: "조회", - IsAllowed: helper.BoolP(false), - }, - { - Name: "생성", - IsAllowed: helper.BoolP(false), - }, - { - Name: "수정", - IsAllowed: helper.BoolP(false), - }, - { - Name: "삭제", - IsAllowed: helper.BoolP(false), - }, - }, - }, - }, -} - -var stack = &domain.Permission{ - Name: "스택 관리", - Children: []*domain.Permission{ - { - Name: "조회", - IsAllowed: helper.BoolP(false), - }, - { - Name: "생성", - IsAllowed: helper.BoolP(false), - }, - { - Name: "수정", - IsAllowed: helper.BoolP(false), - }, - { - Name: "삭제", - IsAllowed: helper.BoolP(false), - }, - }, -} - -var security_policy = &domain.Permission{ - Name: "보안/정책 관리", - Children: []*domain.Permission{ - { - Name: "보안/정책", - Children: []*domain.Permission{ - { - Name: "조회", - IsAllowed: helper.BoolP(false), - }, - { - Name: "생성", - IsAllowed: helper.BoolP(false), - }, - { - Name: "수정", - IsAllowed: helper.BoolP(false), - }, - { - Name: "삭제", - IsAllowed: helper.BoolP(false), - }, - }, - }, - }, -} - -var projectManagement = &domain.Permission{ - Name: "프로젝트 관리", - Children: []*domain.Permission{ - { - Name: "프로젝트", - Children: []*domain.Permission{ - { - Name: "조회", - IsAllowed: helper.BoolP(false), - }, - { - Name: "생성", - IsAllowed: helper.BoolP(false), - }, - }, - }, - { - Name: "앱 서빙", - Children: []*domain.Permission{ - { - Name: "조회", - IsAllowed: helper.BoolP(false), - }, - { - Name: "빌드", - IsAllowed: helper.BoolP(false), - }, - { - Name: "배포", - IsAllowed: helper.BoolP(false), - }, - { - Name: "삭제", - IsAllowed: helper.BoolP(false), - }, - }, - }, - { - Name: "설정-일반", - Children: []*domain.Permission{ - { - Name: "조회", - IsAllowed: helper.BoolP(false), - }, - { - Name: "수정", - IsAllowed: helper.BoolP(false), - }, - { - Name: "삭제", - IsAllowed: helper.BoolP(false), - }, - }, - }, - { - Name: "설정-멤버", - Children: []*domain.Permission{ - { - Name: "조회", - IsAllowed: helper.BoolP(false), - }, - { - Name: "생성", - IsAllowed: helper.BoolP(false), - }, - { - Name: "수정", - IsAllowed: helper.BoolP(false), - }, - { - Name: "삭제", - IsAllowed: helper.BoolP(false), - }, - }, - }, - { - Name: "설정-네임스페이스", - Children: []*domain.Permission{ - { - Name: "조회", - IsAllowed: helper.BoolP(false), - }, - { - Name: "생성", - IsAllowed: helper.BoolP(false), - }, - { - Name: "수정", - IsAllowed: helper.BoolP(false), - }, - { - Name: "삭제", - IsAllowed: helper.BoolP(false), - }, - }, - }, - }, -} - -var notification = &domain.Permission{ - Name: "알림", - Children: []*domain.Permission{ - { - Name: "시스템 경고", - Children: []*domain.Permission{ - { - Name: "조회", - IsAllowed: helper.BoolP(false), - }, - }, - }, - { - Name: "보안/정책 감사로그", - Children: []*domain.Permission{ - { - Name: "조회", - IsAllowed: helper.BoolP(false), - }, - }, - }, - }, -} - -var configuration = &domain.Permission{ - Name: "설정", - Children: []*domain.Permission{ - { - Name: "일반", - Children: []*domain.Permission{ - { - Name: "조회", - IsAllowed: helper.BoolP(false), - }, - { - Name: "수정", - IsAllowed: helper.BoolP(false), - }, - }, - }, - { - Name: "클라우드 계정", - Children: []*domain.Permission{ - { - Name: "조회", - IsAllowed: helper.BoolP(false), - }, - { - Name: "생성", - IsAllowed: helper.BoolP(false), - }, - { - Name: "수정", - IsAllowed: helper.BoolP(false), - }, - { - Name: "삭제", - IsAllowed: helper.BoolP(false), - }, - }, - }, - { - Name: "스택 템플릿", - Children: []*domain.Permission{ - { - Name: "조회", - IsAllowed: helper.BoolP(false), - }, - }, - }, - { - Name: "프로젝트 관리", - Children: []*domain.Permission{ - { - Name: "조회", - IsAllowed: helper.BoolP(false), - }, - { - Name: "생성", - IsAllowed: helper.BoolP(false), - }, - { - Name: "수정", - IsAllowed: helper.BoolP(false), - }, - { - Name: "삭제", - IsAllowed: helper.BoolP(false), - }, - }, - }, - { - Name: "사용자", - Children: []*domain.Permission{ - { - Name: "조회", - IsAllowed: helper.BoolP(false), - }, - { - Name: "생성", - IsAllowed: helper.BoolP(false), - }, - { - Name: "수정", - IsAllowed: helper.BoolP(false), - }, - { - Name: "삭제", - IsAllowed: helper.BoolP(false), - }, - }, - }, - { - Name: "사용자 권한 관리", - Children: []*domain.Permission{ - { - Name: "조회", - IsAllowed: helper.BoolP(false), - }, - { - Name: "생성", - IsAllowed: helper.BoolP(false), - }, - { - Name: "수정", - IsAllowed: helper.BoolP(false), - }, - { - Name: "삭제", - IsAllowed: helper.BoolP(false), - }, - }, - }, - { - Name: "알림 설정", - Children: []*domain.Permission{ - { - Name: "조회", - IsAllowed: helper.BoolP(false), - }, - { - Name: "생성", - IsAllowed: helper.BoolP(false), - }, - { - Name: "수정", - IsAllowed: helper.BoolP(false), - }, - { - Name: "삭제", - IsAllowed: helper.BoolP(false), - }, - }, - }, - }, -} diff --git a/internal/repository/project.go b/internal/repository/project.go index 198e89a4..4260ea6a 100644 --- a/internal/repository/project.go +++ b/internal/repository/project.go @@ -1,6 +1,7 @@ package repository import ( + "context" "database/sql" "github.com/google/uuid" @@ -14,33 +15,33 @@ import ( ) type IProjectRepository interface { - CreateProject(p *model.Project) (string, error) - GetProjects(organizationId string, userId uuid.UUID, pg *pagination.Pagination) ([]domain.ProjectResponse, error) - GetProjectsByUserId(organizationId string, userId uuid.UUID, pg *pagination.Pagination) ([]domain.ProjectResponse, error) - GetAllProjects(organizationId string, pg *pagination.Pagination) (pr []domain.ProjectResponse, err error) - GetProjectById(organizationId string, projectId string) (*model.Project, error) - GetProjectByIdAndLeader(organizationId string, projectId string) (*model.Project, error) - GetProjectByName(organizationId string, projectName string) (*model.Project, error) - UpdateProject(p *model.Project) error - GetAllProjectRoles() ([]model.ProjectRole, error) - GetProjectRoleByName(name string) (*model.ProjectRole, error) - GetProjectRoleById(id string) (*model.ProjectRole, error) - AddProjectMember(*model.ProjectMember) (string, error) - GetProjectMembersByProjectId(projectId string, pg *pagination.Pagination) ([]model.ProjectMember, error) - GetProjectMembersByProjectIdAndRoleName(projectId string, memberRole string, pg *pagination.Pagination) ([]model.ProjectMember, error) - GetProjectMemberCountByProjectId(projectId string) (*domain.GetProjectMemberCountResponse, error) - GetProjectMemberById(projectMemberId string) (*model.ProjectMember, error) - GetProjectMemberByUserId(projectId string, projectUserId string) (pm *model.ProjectMember, err error) - RemoveProjectMember(projectMemberId string) error - UpdateProjectMemberRole(pm *model.ProjectMember) error - CreateProjectNamespace(organizationId string, pn *model.ProjectNamespace) error - GetProjectNamespaceByName(organizationId string, projectId string, stackId string, projectNamespace string) (*model.ProjectNamespace, error) - GetProjectNamespaces(organizationId string, projectId string, pg *pagination.Pagination) ([]model.ProjectNamespace, error) - GetProjectNamespaceByPrimaryKey(organizationId string, projectId string, projectNamespace string, stackId string) (*model.ProjectNamespace, error) - UpdateProjectNamespace(pn *model.ProjectNamespace) error - DeleteProjectNamespace(organizationId string, projectId string, projectNamespace string, stackId string) error - GetAppCountByProjectId(organizationId string, projectId string) (int, error) - GetAppCountByNamespace(organizationId string, projectId string, namespace string) (int, error) + CreateProject(ctx context.Context, p *model.Project) (string, error) + GetProjects(ctx context.Context, organizationId string, userId uuid.UUID, pg *pagination.Pagination) ([]domain.ProjectResponse, error) + GetProjectsByUserId(ctx context.Context, organizationId string, userId uuid.UUID, pg *pagination.Pagination) ([]domain.ProjectResponse, error) + GetAllProjects(ctx context.Context, organizationId string, pg *pagination.Pagination) (pr []domain.ProjectResponse, err error) + GetProjectById(ctx context.Context, organizationId string, projectId string) (*model.Project, error) + GetProjectByIdAndLeader(ctx context.Context, organizationId string, projectId string) (*model.Project, error) + GetProjectByName(ctx context.Context, organizationId string, projectName string) (*model.Project, error) + UpdateProject(ctx context.Context, p *model.Project) error + GetAllProjectRoles(ctx context.Context) ([]model.ProjectRole, error) + GetProjectRoleByName(ctx context.Context, name string) (*model.ProjectRole, error) + GetProjectRoleById(ctx context.Context, id string) (*model.ProjectRole, error) + AddProjectMember(context.Context, *model.ProjectMember) (string, error) + GetProjectMembersByProjectId(ctx context.Context, projectId string, pg *pagination.Pagination) ([]model.ProjectMember, error) + GetProjectMembersByProjectIdAndRoleName(ctx context.Context, projectId string, memberRole string, pg *pagination.Pagination) ([]model.ProjectMember, error) + GetProjectMemberCountByProjectId(ctx context.Context, projectId string) (*domain.GetProjectMemberCountResponse, error) + GetProjectMemberById(ctx context.Context, projectMemberId string) (*model.ProjectMember, error) + GetProjectMemberByUserId(ctx context.Context, projectId string, projectUserId string) (pm *model.ProjectMember, err error) + RemoveProjectMember(ctx context.Context, projectMemberId string) error + UpdateProjectMemberRole(ctx context.Context, pm *model.ProjectMember) error + CreateProjectNamespace(ctx context.Context, organizationId string, pn *model.ProjectNamespace) error + GetProjectNamespaceByName(ctx context.Context, organizationId string, projectId string, stackId string, projectNamespace string) (*model.ProjectNamespace, error) + GetProjectNamespaces(ctx context.Context, organizationId string, projectId string, pg *pagination.Pagination) ([]model.ProjectNamespace, error) + GetProjectNamespaceByPrimaryKey(ctx context.Context, organizationId string, projectId string, projectNamespace string, stackId string) (*model.ProjectNamespace, error) + UpdateProjectNamespace(ctx context.Context, pn *model.ProjectNamespace) error + DeleteProjectNamespace(ctx context.Context, organizationId string, projectId string, projectNamespace string, stackId string) error + GetAppCountByProjectId(ctx context.Context, organizationId string, projectId string) (int, error) + GetAppCountByNamespace(ctx context.Context, organizationId string, projectId string, namespace string) (int, error) } type ProjectRepository struct { @@ -53,8 +54,8 @@ func NewProjectRepository(db *gorm.DB) IProjectRepository { } } -func (r *ProjectRepository) CreateProject(p *model.Project) (string, error) { - res := r.db.Create(&p) +func (r *ProjectRepository) CreateProject(ctx context.Context, p *model.Project) (string, error) { + res := r.db.WithContext(ctx).Create(&p) if res.Error != nil { return "", res.Error } @@ -62,11 +63,11 @@ func (r *ProjectRepository) CreateProject(p *model.Project) (string, error) { return p.ID, nil } -func (r *ProjectRepository) GetProjects(organizationId string, userId uuid.UUID, pg *pagination.Pagination) (pr []domain.ProjectResponse, err error) { +func (r *ProjectRepository) GetProjects(ctx context.Context, organizationId string, userId uuid.UUID, pg *pagination.Pagination) (pr []domain.ProjectResponse, err error) { if pg == nil { pg = pagination.NewPagination(nil) } - res := r.db.Raw(""+ + res := r.db.WithContext(ctx).Raw(""+ "select distinct p.id as id, p.organization_id as organization_id, p.name as name, p.description as description, p.created_at as created_at, "+ " true as is_my_project, pm.project_role_id as project_role_id, pm.pr_name as project_role_name, "+ " pn.count as namespace_count, asa.count as app_count, pm_count.count as member_count "+ @@ -156,11 +157,11 @@ func (r *ProjectRepository) GetProjects(organizationId string, userId uuid.UUID, return pr, nil } -func (r *ProjectRepository) GetProjectsByUserId(organizationId string, userId uuid.UUID, pg *pagination.Pagination) (pr []domain.ProjectResponse, err error) { +func (r *ProjectRepository) GetProjectsByUserId(ctx context.Context, organizationId string, userId uuid.UUID, pg *pagination.Pagination) (pr []domain.ProjectResponse, err error) { if pg == nil { pg = pagination.NewPagination(nil) } - res := r.db.Raw(""+ + res := r.db.WithContext(ctx).Raw(""+ "select distinct p.id as id, p.organization_id as organization_id, p.name as name, p.description as description, p.created_at as created_at, "+ " true as is_my_project, pm.project_role_id as project_role_id, pm.pr_name as project_role_name, "+ " pn.count as namespace_count, asa.count as app_count, pm_count.count as member_count "+ @@ -213,11 +214,11 @@ func (r *ProjectRepository) GetProjectsByUserId(organizationId string, userId uu return pr, nil } -func (r *ProjectRepository) GetAllProjects(organizationId string, pg *pagination.Pagination) (pr []domain.ProjectResponse, err error) { +func (r *ProjectRepository) GetAllProjects(ctx context.Context, organizationId string, pg *pagination.Pagination) (pr []domain.ProjectResponse, err error) { if pg == nil { pg = pagination.NewPagination(nil) } - res := r.db.Raw(""+ + res := r.db.WithContext(ctx).Raw(""+ "select distinct p.id as id, p.organization_id as organization_id, p.name as name, p.description as description, p.created_at as created_at, "+ " false as is_my_project, pm.project_role_id as project_role_id, pm.pr_name as project_role_name, "+ " pn.count as namespace_count, asa.count as app_count, pm_count.count as member_count "+ @@ -266,8 +267,8 @@ func (r *ProjectRepository) GetAllProjects(organizationId string, pg *pagination return pr, nil } -func (r *ProjectRepository) GetProjectById(organizationId string, projectId string) (p *model.Project, err error) { - res := r.db.Limit(1).Where("organization_id = ? and id = ?", organizationId, projectId).First(&p) +func (r *ProjectRepository) GetProjectById(ctx context.Context, organizationId string, projectId string) (p *model.Project, err error) { + res := r.db.WithContext(ctx).Limit(1).Where("organization_id = ? and id = ?", organizationId, projectId).First(&p) if res.Error != nil { if errors.Is(res.Error, gorm.ErrRecordNotFound) { log.Info("Cannot find project") @@ -281,8 +282,8 @@ func (r *ProjectRepository) GetProjectById(organizationId string, projectId stri return p, nil } -func (r *ProjectRepository) GetProjectByIdAndLeader(organizationId string, projectId string) (p *model.Project, err error) { - res := r.db.Limit(1). +func (r *ProjectRepository) GetProjectByIdAndLeader(ctx context.Context, organizationId string, projectId string) (p *model.Project, err error) { + res := r.db.WithContext(ctx).Limit(1). Preload("ProjectMembers", "is_project_leader = ?", true). Preload("ProjectMembers.ProjectRole"). Preload("ProjectMembers.ProjectUser"). @@ -301,8 +302,8 @@ func (r *ProjectRepository) GetProjectByIdAndLeader(organizationId string, proje return p, nil } -func (r *ProjectRepository) GetProjectByName(organizationId string, projectName string) (p *model.Project, err error) { - res := r.db.Limit(1). +func (r *ProjectRepository) GetProjectByName(ctx context.Context, organizationId string, projectName string) (p *model.Project, err error) { + res := r.db.WithContext(ctx).Limit(1). Where("organization_id = ? and name = ?", organizationId, projectName). First(&p) if res.Error != nil { @@ -318,8 +319,8 @@ func (r *ProjectRepository) GetProjectByName(organizationId string, projectName return p, nil } -func (r *ProjectRepository) UpdateProject(p *model.Project) error { - res := r.db.Model(&p).Updates(model.Project{Name: p.Name, Description: p.Description, UpdatedAt: p.UpdatedAt}) +func (r *ProjectRepository) UpdateProject(ctx context.Context, p *model.Project) error { + res := r.db.WithContext(ctx).Model(&p).Updates(model.Project{Name: p.Name, Description: p.Description, UpdatedAt: p.UpdatedAt}) if res.Error != nil { return res.Error } @@ -327,9 +328,9 @@ func (r *ProjectRepository) UpdateProject(p *model.Project) error { return nil } -func (r *ProjectRepository) GetProjectRoleById(id string) (*model.ProjectRole, error) { +func (r *ProjectRepository) GetProjectRoleById(ctx context.Context, id string) (*model.ProjectRole, error) { var pr = &model.ProjectRole{ID: id} - res := r.db.First(pr) + res := r.db.WithContext(ctx).First(pr) if res.Error != nil { if errors.Is(res.Error, gorm.ErrRecordNotFound) { log.Info("Cannot find project role") @@ -343,8 +344,8 @@ func (r *ProjectRepository) GetProjectRoleById(id string) (*model.ProjectRole, e return pr, nil } -func (r *ProjectRepository) GetAllProjectRoles() (prs []model.ProjectRole, err error) { - res := r.db.Find(&prs) +func (r *ProjectRepository) GetAllProjectRoles(ctx context.Context) (prs []model.ProjectRole, err error) { + res := r.db.WithContext(ctx).Find(&prs) if res.Error != nil { if errors.Is(res.Error, gorm.ErrRecordNotFound) { log.Info("Cannot find project roles") @@ -358,8 +359,8 @@ func (r *ProjectRepository) GetAllProjectRoles() (prs []model.ProjectRole, err e return prs, nil } -func (r *ProjectRepository) GetProjectRoleByName(name string) (pr *model.ProjectRole, err error) { - res := r.db.Where("name = ?", name).First(&pr) +func (r *ProjectRepository) GetProjectRoleByName(ctx context.Context, name string) (pr *model.ProjectRole, err error) { + res := r.db.WithContext(ctx).Where("name = ?", name).First(&pr) if res.Error != nil { if errors.Is(res.Error, gorm.ErrRecordNotFound) { log.Info("Cannot find project roles") @@ -373,8 +374,8 @@ func (r *ProjectRepository) GetProjectRoleByName(name string) (pr *model.Project return pr, nil } -func (r *ProjectRepository) AddProjectMember(pm *model.ProjectMember) (string, error) { - res := r.db.Create(&pm) +func (r *ProjectRepository) AddProjectMember(ctx context.Context, pm *model.ProjectMember) (string, error) { + res := r.db.WithContext(ctx).Create(&pm) if res.Error != nil { return "", res.Error } @@ -382,11 +383,11 @@ func (r *ProjectRepository) AddProjectMember(pm *model.ProjectMember) (string, e return pm.ID, nil } -func (r *ProjectRepository) GetProjectMembersByProjectId(projectId string, pg *pagination.Pagination) (pms []model.ProjectMember, err error) { +func (r *ProjectRepository) GetProjectMembersByProjectId(ctx context.Context, projectId string, pg *pagination.Pagination) (pms []model.ProjectMember, err error) { if pg == nil { pg = pagination.NewPagination(nil) } - _, res := pg.Fetch(r.db.Joins("ProjectUser"). + _, res := pg.Fetch(r.db.WithContext(ctx).Joins("ProjectUser"). Joins("ProjectRole"). Where("project_members.project_id = ?", projectId). Order("project_members.created_at ASC"), &pms) @@ -403,11 +404,11 @@ func (r *ProjectRepository) GetProjectMembersByProjectId(projectId string, pg *p return pms, nil } -func (r *ProjectRepository) GetProjectMembersByProjectIdAndRoleName(projectId string, memberRole string, pg *pagination.Pagination) (pms []model.ProjectMember, err error) { +func (r *ProjectRepository) GetProjectMembersByProjectIdAndRoleName(ctx context.Context, projectId string, memberRole string, pg *pagination.Pagination) (pms []model.ProjectMember, err error) { if pg == nil { pg = pagination.NewPagination(nil) } - _, res := pg.Fetch(r.db.Joins("ProjectUser"). + _, res := pg.Fetch(r.db.WithContext(ctx).Joins("ProjectUser"). InnerJoins("ProjectRole", r.db.Where(&model.ProjectRole{Name: memberRole})). Order("project_members.created_at ASC"). Where("project_members.project_id = ?", projectId), &pms) @@ -425,8 +426,8 @@ func (r *ProjectRepository) GetProjectMembersByProjectIdAndRoleName(projectId st return pms, nil } -func (r *ProjectRepository) GetProjectMemberCountByProjectId(projectId string) (pmcr *domain.GetProjectMemberCountResponse, err error) { - res := r.db.Raw(""+ +func (r *ProjectRepository) GetProjectMemberCountByProjectId(ctx context.Context, projectId string) (pmcr *domain.GetProjectMemberCountResponse, err error) { + res := r.db.WithContext(ctx).Raw(""+ "select (plc.count + pmc.count + pvc.count) as project_member_all_count,"+ " plc.count as project_leader_count,"+ " pmc.count as project_member_count,"+ @@ -460,8 +461,8 @@ func (r *ProjectRepository) GetProjectMemberCountByProjectId(projectId string) ( return pmcr, nil } -func (r *ProjectRepository) GetProjectMemberById(projectMemberId string) (pm *model.ProjectMember, err error) { - res := r.db.Preload("ProjectUser"). +func (r *ProjectRepository) GetProjectMemberById(ctx context.Context, projectMemberId string) (pm *model.ProjectMember, err error) { + res := r.db.WithContext(ctx).Preload("ProjectUser"). Joins("ProjectRole").Where("project_members.id = ?", projectMemberId).First(&pm) if res.Error != nil { if errors.Is(res.Error, gorm.ErrRecordNotFound) { @@ -476,8 +477,8 @@ func (r *ProjectRepository) GetProjectMemberById(projectMemberId string) (pm *mo return pm, nil } -func (r *ProjectRepository) GetProjectMemberByUserId(projectId string, projectUserId string) (pm *model.ProjectMember, err error) { - res := r.db.Preload("ProjectUser"). +func (r *ProjectRepository) GetProjectMemberByUserId(ctx context.Context, projectId string, projectUserId string) (pm *model.ProjectMember, err error) { + res := r.db.WithContext(ctx).Preload("ProjectUser"). Joins("ProjectRole").Where("project_id = ? and project_user_id = ?", projectId, projectUserId).First(&pm) if res.Error != nil { if errors.Is(res.Error, gorm.ErrRecordNotFound) { @@ -492,8 +493,8 @@ func (r *ProjectRepository) GetProjectMemberByUserId(projectId string, projectUs return pm, nil } -func (r *ProjectRepository) RemoveProjectMember(projectMemberId string) error { - res := r.db.Delete(&model.ProjectMember{ID: projectMemberId}) +func (r *ProjectRepository) RemoveProjectMember(ctx context.Context, projectMemberId string) error { + res := r.db.WithContext(ctx).Delete(&model.ProjectMember{ID: projectMemberId}) if res.Error != nil { return res.Error } @@ -510,8 +511,8 @@ func (r *ProjectRepository) RemoveProjectMember(projectMemberId string) error { // return nil //} -func (r *ProjectRepository) UpdateProjectMemberRole(pm *model.ProjectMember) error { - res := r.db.Model(&pm).Updates( +func (r *ProjectRepository) UpdateProjectMemberRole(ctx context.Context, pm *model.ProjectMember) error { + res := r.db.WithContext(ctx).Model(&pm).Updates( model.ProjectMember{ ProjectRoleId: pm.ProjectRoleId, IsProjectLeader: pm.IsProjectLeader, @@ -524,8 +525,8 @@ func (r *ProjectRepository) UpdateProjectMemberRole(pm *model.ProjectMember) err return nil } -func (r *ProjectRepository) CreateProjectNamespace(organizationId string, pn *model.ProjectNamespace) error { - res := r.db.Create(&pn) +func (r *ProjectRepository) CreateProjectNamespace(ctx context.Context, organizationId string, pn *model.ProjectNamespace) error { + res := r.db.WithContext(ctx).Create(&pn) if res.Error != nil { return res.Error } @@ -534,9 +535,9 @@ func (r *ProjectRepository) CreateProjectNamespace(organizationId string, pn *mo return nil } -func (r *ProjectRepository) GetProjectNamespaceByName(organizationId string, projectId string, stackId string, +func (r *ProjectRepository) GetProjectNamespaceByName(ctx context.Context, organizationId string, projectId string, stackId string, projectNamespace string) (pn *model.ProjectNamespace, err error) { - res := r.db.Limit(1). + res := r.db.WithContext(ctx).Limit(1). Where("stack_id = ? and namespace = ? and project_id = ?", stackId, projectNamespace, projectId). First(&pn) if res.Error != nil { @@ -552,11 +553,11 @@ func (r *ProjectRepository) GetProjectNamespaceByName(organizationId string, pro return pn, nil } -func (r *ProjectRepository) GetProjectNamespaces(organizationId string, projectId string, pg *pagination.Pagination) (pns []model.ProjectNamespace, err error) { +func (r *ProjectRepository) GetProjectNamespaces(ctx context.Context, organizationId string, projectId string, pg *pagination.Pagination) (pns []model.ProjectNamespace, err error) { if pg == nil { pg = pagination.NewPagination(nil) } - _, res := pg.Fetch(r.db.Where("project_id = ?", projectId). + _, res := pg.Fetch(r.db.WithContext(ctx).Where("project_id = ?", projectId). Preload("Stack"), &pns) if res.Error != nil { if errors.Is(res.Error, gorm.ErrRecordNotFound) { @@ -571,9 +572,9 @@ func (r *ProjectRepository) GetProjectNamespaces(organizationId string, projectI return pns, nil } -func (r *ProjectRepository) GetProjectNamespaceByPrimaryKey(organizationId string, projectId string, +func (r *ProjectRepository) GetProjectNamespaceByPrimaryKey(ctx context.Context, organizationId string, projectId string, projectNamespace string, stackId string) (pn *model.ProjectNamespace, err error) { - res := r.db.Limit(1). + res := r.db.WithContext(ctx).Limit(1). Where("stack_id = ? and namespace = ? and project_id = ?", stackId, projectNamespace, projectId). Preload("Stack"). First(&pn) @@ -590,8 +591,8 @@ func (r *ProjectRepository) GetProjectNamespaceByPrimaryKey(organizationId strin return pn, nil } -func (r *ProjectRepository) UpdateProjectNamespace(pn *model.ProjectNamespace) error { - res := r.db.Model(&pn).Updates(model.ProjectNamespace{Description: pn.Description, UpdatedAt: pn.UpdatedAt}) +func (r *ProjectRepository) UpdateProjectNamespace(ctx context.Context, pn *model.ProjectNamespace) error { + res := r.db.WithContext(ctx).Model(&pn).Updates(model.ProjectNamespace{Description: pn.Description, UpdatedAt: pn.UpdatedAt}) if res.Error != nil { return res.Error } @@ -599,9 +600,9 @@ func (r *ProjectRepository) UpdateProjectNamespace(pn *model.ProjectNamespace) e return nil } -func (r *ProjectRepository) DeleteProjectNamespace(organizationId string, projectId string, projectNamespace string, +func (r *ProjectRepository) DeleteProjectNamespace(ctx context.Context, organizationId string, projectId string, projectNamespace string, stackId string) error { - res := r.db.Where("stack_id = ? and namespace = ? and project_id = ?", stackId, projectNamespace, projectId). + res := r.db.WithContext(ctx).Where("stack_id = ? and namespace = ? and project_id = ?", stackId, projectNamespace, projectId). Delete(&model.ProjectNamespace{StackId: stackId, Namespace: projectNamespace}) if res.Error != nil { return res.Error @@ -610,8 +611,8 @@ func (r *ProjectRepository) DeleteProjectNamespace(organizationId string, projec return nil } -func (r *ProjectRepository) GetAppCountByProjectId(organizationId string, projectId string) (appCount int, err error) { - res := r.db.Select("count(*) as app_count"). +func (r *ProjectRepository) GetAppCountByProjectId(ctx context.Context, organizationId string, projectId string) (appCount int, err error) { + res := r.db.WithContext(ctx).Select("count(*) as app_count"). Table("app_serve_apps"). Where("organization_id = ? and project_Id = ?", organizationId, projectId). Find(&appCount) @@ -623,8 +624,8 @@ func (r *ProjectRepository) GetAppCountByProjectId(organizationId string, projec return appCount, nil } -func (r *ProjectRepository) GetAppCountByNamespace(organizationId string, projectId string, namespace string) (appCount int, err error) { - res := r.db.Select("count(*) as app_count"). +func (r *ProjectRepository) GetAppCountByNamespace(ctx context.Context, organizationId string, projectId string, namespace string) (appCount int, err error) { + res := r.db.WithContext(ctx).Select("count(*) as app_count"). Table("app_serve_apps"). Where("organization_id = ? and project_Id = ? and namespace = ?", organizationId, projectId, namespace). Find(&appCount) diff --git a/internal/repository/role.go b/internal/repository/role.go index ab5c7f50..b3b1aa12 100644 --- a/internal/repository/role.go +++ b/internal/repository/role.go @@ -3,6 +3,7 @@ package repository import ( "fmt" "math" + "context" "github.com/openinfradev/tks-api/internal/model" "github.com/openinfradev/tks-api/internal/pagination" @@ -10,41 +11,39 @@ import ( ) type IRoleRepository interface { - 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 *model.Role) error + Create(ctx context.Context, roleObj *model.Role) (string, error) + ListTksRoles(ctx context.Context, organizationId string, pg *pagination.Pagination) ([]*model.Role, error) + GetTksRole(ctx context.Context, id string) (*model.Role, error) + GetTksRoleByRoleName(ctx context.Context, roleName string) (*model.Role, error) + Delete(ctx context.Context, id string) error + Update(ctx context.Context, roleObj *model.Role) error } type RoleRepository struct { db *gorm.DB } -func (r RoleRepository) GetTksRoleByRoleName(roleName string) (*model.Role, error) { +func (r RoleRepository) GetTksRoleByRoleName(ctx context.Context, roleName string) (*model.Role, error) { var role model.Role - if err := r.db.Preload("Role").First(&role, "Role.name = ?", roleName).Error; err != nil { + if err := r.db.WithContext(ctx).Preload("Role").First(&role, "Role.name = ?", roleName).Error; err != nil { return nil, err } return &role, nil } -func (r RoleRepository) Create(roleObj *model.Role) (string, error) { +func (r RoleRepository) Create(ctx context.Context, roleObj *model.Role) (string, error) { if roleObj == nil { return "", fmt.Errorf("roleObj is nil") } - if err := r.db.Create(roleObj).Error; err != nil { + if err := r.db.WithContext(ctx).Create(roleObj).Error; err != nil { return "", err } return roleObj.ID, nil } -func (r RoleRepository) List(pg *pagination.Pagination) ([]*model.Role, error) { +func (r RoleRepository) ListTksRoles(ctx context.Context, organizationId string, pg *pagination.Pagination) ([]*model.Role, error) { var roles []*model.Role if pg == nil { @@ -57,29 +56,7 @@ func (r RoleRepository) List(pg *pagination.Pagination) ([]*model.Role, error) { pg.TotalPages = int(math.Ceil(float64(pg.TotalRows) / float64(pg.Limit))) orderQuery := fmt.Sprintf("%s %s", pg.SortColumn, pg.SortOrder) - res := db.Offset(pg.GetOffset()).Limit(pg.GetLimit()).Order(orderQuery).Find(&roles) - - if res.Error != nil { - return nil, res.Error - } - - return roles, nil -} - -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(&model.Role{})) - - db.Count(&pg.TotalRows) - pg.TotalPages = int(math.Ceil(float64(pg.TotalRows) / float64(pg.Limit))) - - orderQuery := fmt.Sprintf("%s %s", pg.SortColumn, pg.SortOrder) - res := db. + res := db.WithContext(ctx). Offset(pg.GetOffset()). Limit(pg.GetLimit()). Order(orderQuery). @@ -92,30 +69,22 @@ func (r RoleRepository) ListTksRoles(organizationId string, pg *pagination.Pagin return roles, nil } -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 - } - - return &role, nil -} -func (r RoleRepository) GetTksRole(id string) (*model.Role, error) { +func (r RoleRepository) GetTksRole(ctx context.Context, id string) (*model.Role, error) { var role model.Role - if err := r.db.First(&role, "id = ?", id).Error; err != nil { + if err := r.db.WithContext(ctx).First(&role, "id = ?", id).Error; err != nil { return nil, err } return &role, nil } -func (r RoleRepository) Update(roleObj *model.Role) error { +func (r RoleRepository) Update(ctx context.Context, roleObj *model.Role) error { if roleObj == nil { return fmt.Errorf("roleObj is nil") } - err := r.db.Model(&model.Role{}).Where("id = ?", roleObj.ID).Updates(model.Role{ + err := r.db.WithContext(ctx).Model(&model.Role{}).Where("id = ?", roleObj.ID).Updates(model.Role{ Name: roleObj.Name, Description: roleObj.Description, }).Error @@ -127,8 +96,8 @@ func (r RoleRepository) Update(roleObj *model.Role) error { return nil } -func (r RoleRepository) Delete(id string) error { - if err := r.db.Delete(&model.Role{}, "id = ?", id).Error; err != nil { +func (r RoleRepository) Delete(ctx context.Context, id string) error { + if err := r.db.WithContext(ctx).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 7fdf1b4e..56dc5bd1 100644 --- a/internal/repository/stack-template.go +++ b/internal/repository/stack-template.go @@ -1,6 +1,7 @@ package repository import ( + "context" "github.com/google/uuid" "gorm.io/gorm" "gorm.io/gorm/clause" @@ -11,14 +12,14 @@ import ( // Interfaces type IStackTemplateRepository interface { - Get(stackTemplateId uuid.UUID) (model.StackTemplate, error) - GetByName(name string) (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) + Get(ctx context.Context, stackTemplateId uuid.UUID) (model.StackTemplate, error) + GetByName(ctx context.Context, name string) (model.StackTemplate, error) + Fetch(ctx context.Context, pg *pagination.Pagination) ([]model.StackTemplate, error) + FetchWithOrganization(ctx context.Context, organizationId string, pg *pagination.Pagination) (out []model.StackTemplate, err error) + Create(ctx context.Context, dto model.StackTemplate) (stackTemplateId uuid.UUID, err error) + Update(ctx context.Context, dto model.StackTemplate) (err error) + Delete(ctx context.Context, dto model.StackTemplate) (err error) + UpdateOrganizations(ctx context.Context, stackTemplateId uuid.UUID, organizationIds []model.Organization) (err error) } type StackTemplateRepository struct { @@ -32,41 +33,41 @@ func NewStackTemplateRepository(db *gorm.DB) IStackTemplateRepository { } // Logics -func (r *StackTemplateRepository) Get(stackTemplateId uuid.UUID) (out model.StackTemplate, err error) { - res := r.db.Preload(clause.Associations).First(&out, "id = ?", stackTemplateId) +func (r *StackTemplateRepository) Get(ctx context.Context, stackTemplateId uuid.UUID) (out model.StackTemplate, err error) { + res := r.db.WithContext(ctx).Preload(clause.Associations).First(&out, "id = ?", stackTemplateId) if res.Error != nil { return model.StackTemplate{}, res.Error } return } -func (r *StackTemplateRepository) GetByName(name string) (out model.StackTemplate, err error) { - res := r.db.First(&out, "name = ?", name) +func (r *StackTemplateRepository) GetByName(ctx context.Context, name string) (out model.StackTemplate, err error) { + res := r.db.WithContext(ctx).First(&out, "name = ?", name) if res.Error != nil { return out, res.Error } return } -func (r *StackTemplateRepository) Fetch(pg *pagination.Pagination) (out []model.StackTemplate, err error) { +func (r *StackTemplateRepository) Fetch(ctx context.Context, pg *pagination.Pagination) (out []model.StackTemplate, err error) { if pg == nil { pg = pagination.NewPagination(nil) } - _, res := pg.Fetch(r.db.Preload(clause.Associations), &out) + _, res := pg.Fetch(r.db.WithContext(ctx).Preload(clause.Associations), &out) if res.Error != nil { return nil, res.Error } return } -func (r *StackTemplateRepository) FetchWithOrganization(organizationId string, pg *pagination.Pagination) (out []model.StackTemplate, err error) { +func (r *StackTemplateRepository) FetchWithOrganization(ctx context.Context, 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). + r.db.WithContext(ctx).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 { @@ -75,16 +76,16 @@ func (r *StackTemplateRepository) FetchWithOrganization(organizationId string, p return } -func (r *StackTemplateRepository) Create(dto model.StackTemplate) (stackTemplateId uuid.UUID, err error) { - res := r.db.Create(&dto) +func (r *StackTemplateRepository) Create(ctx context.Context, dto model.StackTemplate) (stackTemplateId uuid.UUID, err error) { + res := r.db.WithContext(ctx).Create(&dto) if res.Error != nil { return uuid.Nil, res.Error } return dto.ID, nil } -func (r *StackTemplateRepository) Update(dto model.StackTemplate) (err error) { - res := r.db.Model(&model.StackTemplate{}). +func (r *StackTemplateRepository) Update(ctx context.Context, dto model.StackTemplate) (err error) { + res := r.db.WithContext(ctx).Model(&model.StackTemplate{}). Where("id = ?", dto.ID). Updates(map[string]interface{}{ "Template": dto.Template, @@ -103,21 +104,21 @@ func (r *StackTemplateRepository) Update(dto model.StackTemplate) (err error) { return nil } -func (r *StackTemplateRepository) Delete(dto model.StackTemplate) (err error) { - res := r.db.Delete(&model.StackTemplate{}, "id = ?", dto.ID) +func (r *StackTemplateRepository) Delete(ctx context.Context, dto model.StackTemplate) (err error) { + res := r.db.WithContext(ctx).Delete(&model.StackTemplate{}, "id = ?", dto.ID) if res.Error != nil { return res.Error } return nil } -func (r *StackTemplateRepository) UpdateOrganizations(stackTemplateId uuid.UUID, organizations []model.Organization) (err error) { +func (r *StackTemplateRepository) UpdateOrganizations(ctx context.Context, stackTemplateId uuid.UUID, organizations []model.Organization) (err error) { var stackTemplate = model.StackTemplate{} - res := r.db.Preload("Organizations").First(&stackTemplate, "id = ?", stackTemplateId) + res := r.db.WithContext(ctx).Preload("Organizations").First(&stackTemplate, "id = ?", stackTemplateId) if res.Error != nil { return res.Error } - err = r.db.Model(&stackTemplate).Association("Organizations").Replace(organizations) + err = r.db.WithContext(ctx).Model(&stackTemplate).Association("Organizations").Replace(organizations) if err != nil { return err } diff --git a/internal/repository/user.go b/internal/repository/user.go index fcfd4981..99a4b98e 100644 --- a/internal/repository/user.go +++ b/internal/repository/user.go @@ -1,6 +1,7 @@ package repository import ( + "context" "time" "github.com/google/uuid" @@ -13,17 +14,17 @@ import ( // Interface type IUserRepository interface { - CreateWithUuid(uuid uuid.UUID, accountId string, name string, email string, + CreateWithUuid(ctx context.Context, uuid uuid.UUID, accountId string, name string, email string, 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, + List(ctx context.Context, filters ...FilterFunc) (out *[]model.User, err error) + ListWithPagination(ctx context.Context, pg *pagination.Pagination, organizationId string) (out *[]model.User, err error) + Get(ctx context.Context, accountId string, organizationId string) (model.User, error) + GetByUuid(ctx context.Context, userId uuid.UUID) (model.User, error) + UpdateWithUuid(ctx context.Context, uuid uuid.UUID, accountId string, name string, roleId string, email string, 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 + UpdatePasswordAt(ctx context.Context, userId uuid.UUID, organizationId string, isTemporary bool) error + DeleteWithUuid(ctx context.Context, uuid uuid.UUID) error + Flush(ctx context.Context, organizationId string) error AccountIdFilter(accountId string) FilterFunc OrganizationFilter(organization string) FilterFunc @@ -35,8 +36,8 @@ type UserRepository struct { db *gorm.DB } -func (r *UserRepository) Flush(organizationId string) error { - res := r.db.Where("organization_id = ?", organizationId).Delete(&model.User{}) +func (r *UserRepository) Flush(ctx context.Context, organizationId string) error { + res := r.db.WithContext(ctx).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 @@ -50,33 +51,7 @@ func NewUserRepository(db *gorm.DB) IUserRepository { } } -//// Models -//type User struct { -// gorm.Model -// -// ID uuid.UUID `gorm:"primarykey;type:uuid"` -// AccountId string -// Name string -// Password string -// AuthType string `gorm:"authType"` -// RoleId uuid.UUID -// Role Role `gorm:"foreignKey:RoleId;references:ID"` -// OrganizationId string -// Organization Organization `gorm:"foreignKey:OrganizationId;references:ID"` -// Creator uuid.UUID -// Email string -// Department string -// Description string -// -// PasswordUpdatedAt time.Time `json:"passwordUpdatedAt"` -//} - -//func (g *User) BeforeCreate(tx *gorm.DB) (err error) { -// g.PasswordUpdatedAt = time.Now() -// return nil -//} - -func (r *UserRepository) CreateWithUuid(uuid uuid.UUID, accountId string, name string, email string, +func (r *UserRepository) CreateWithUuid(ctx context.Context, uuid uuid.UUID, accountId string, name string, email string, department string, description string, organizationId string, roleId string) (model.User, error) { newUser := model.User{ @@ -89,45 +64,25 @@ func (r *UserRepository) CreateWithUuid(uuid uuid.UUID, accountId string, name s OrganizationId: organizationId, RoleId: roleId, } - res := r.db.Create(&newUser) + res := r.db.WithContext(ctx).Create(&newUser) if res.Error != nil { log.Error(res.Error.Error()) return model.User{}, res.Error } - user, err := r.getUserByAccountId(accountId, organizationId) + user, err := r.getUserByAccountId(nil, accountId, organizationId) if err != nil { return model.User{}, err } return user, nil } -func (r *UserRepository) AccountIdFilter(accountId string) FilterFunc { - return func(user *gorm.DB) *gorm.DB { - return user.Where("account_id = ?", accountId) - } -} -func (r *UserRepository) OrganizationFilter(organization string) FilterFunc { - return func(user *gorm.DB) *gorm.DB { - return user.Where("organization_id = ?", organization) - } -} -func (r *UserRepository) EmailFilter(email string) FilterFunc { - return func(user *gorm.DB) *gorm.DB { - return user.Where("email = ?", email) - } -} -func (r *UserRepository) NameFilter(name string) FilterFunc { - return func(user *gorm.DB) *gorm.DB { - return user.Where("name = ?", name) - } -} -func (r *UserRepository) List(filters ...FilterFunc) (*[]model.User, error) { +func (r *UserRepository) List(ctx context.Context, filters ...FilterFunc) (*[]model.User, error) { var users []model.User var res *gorm.DB if filters == nil { - res = r.db.Model(&model.User{}).Preload("Organization").Preload("Role").Find(&users) + res = r.db.WithContext(ctx).Model(&model.User{}).Preload("Organization").Preload("Role").Find(&users) } else { combinedFilter := func(filters ...FilterFunc) FilterFunc { return func(user *gorm.DB) *gorm.DB { @@ -157,14 +112,14 @@ func (r *UserRepository) List(filters ...FilterFunc) (*[]model.User, error) { return &out, nil } -func (r *UserRepository) ListWithPagination(pg *pagination.Pagination, organizationId string) (*[]model.User, error) { +func (r *UserRepository) ListWithPagination(ctx context.Context, 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(&model.User{}).Where("organization_id = ?", organizationId), &users) + _, res := pg.Fetch(r.db.WithContext(ctx).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 @@ -178,17 +133,18 @@ func (r *UserRepository) ListWithPagination(pg *pagination.Pagination, organizat return &out, nil } -func (r *UserRepository) Get(accountId string, organizationId string) (model.User, error) { - user, err := r.getUserByAccountId(accountId, organizationId) +func (r *UserRepository) Get(ctx context.Context, accountId string, organizationId string) (model.User, error) { + user, err := r.getUserByAccountId(ctx, accountId, organizationId) if err != nil { return model.User{}, err } return user, nil } -func (r *UserRepository) GetByUuid(userId uuid.UUID) (respUser model.User, err error) { + +func (r *UserRepository) GetByUuid(ctx context.Context, 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) + res := r.db.WithContext(ctx).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) @@ -200,10 +156,10 @@ func (r *UserRepository) GetByUuid(userId uuid.UUID) (respUser model.User, err e return user, nil } -func (r *UserRepository) UpdateWithUuid(uuid uuid.UUID, accountId string, name string, roleId string, +func (r *UserRepository) UpdateWithUuid(ctx context.Context, uuid uuid.UUID, accountId string, name string, roleId string, 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{ + res := r.db.WithContext(ctx).Model(&model.User{}).Where("id = ?", uuid).Updates(model.User{ AccountId: accountId, Name: name, Email: email, @@ -224,14 +180,15 @@ func (r *UserRepository) UpdateWithUuid(uuid uuid.UUID, accountId string, name s } return user, nil } -func (r *UserRepository) UpdatePasswordAt(userId uuid.UUID, organizationId string, isTemporary bool) error { + +func (r *UserRepository) UpdatePasswordAt(ctx context.Context, userId uuid.UUID, organizationId string, isTemporary bool) error { var updateUser = model.User{} if isTemporary { updateUser.PasswordUpdatedAt = time.Time{} } else { updateUser.PasswordUpdatedAt = time.Now() } - res := r.db.Model(&model.User{}).Where("id = ? AND organization_id = ?", userId, organizationId). + res := r.db.WithContext(ctx).Model(&model.User{}).Where("id = ? AND organization_id = ?", userId, organizationId). Select("password_updated_at").Updates(updateUser) if res.RowsAffected == 0 || res.Error != nil { @@ -244,8 +201,9 @@ func (r *UserRepository) UpdatePasswordAt(userId uuid.UUID, organizationId strin return nil } -func (r *UserRepository) DeleteWithUuid(uuid uuid.UUID) error { - res := r.db.Unscoped().Delete(&model.User{}, "id = ?", uuid) + +func (r *UserRepository) DeleteWithUuid(ctx context.Context, uuid uuid.UUID) error { + res := r.db.WithContext(ctx).Unscoped().Delete(&model.User{}, "id = ?", uuid) if res.Error != nil { log.Errorf("error is :%s(%T)", res.Error.Error(), res.Error) return res.Error @@ -253,28 +211,8 @@ func (r *UserRepository) DeleteWithUuid(uuid uuid.UUID) error { return nil } -//// Deprecated: -//type Policy struct { -// gorm.Model -// -// //ID uuid.UUID `gorm:"primarykey;type:uuid;"` -// RoleId uuid.UUID -// Role Role `gorm:"references:ID"` -// Name string -// Description string -// Create bool `gorm:"column:c"` -// CreatePriviledge string -// Update bool `gorm:"column:u"` -// UpdatePriviledge string -// Read bool `gorm:"column:r"` -// ReadPriviledge string -// Delete bool `gorm:"column:d"` -// DeletePriviledge string -// Creator uuid.UUID -//} - -func (r *UserRepository) GetRoleByName(roleName string) (model.Role, error) { - role, err := r.getRoleByName(roleName) +func (r *UserRepository) GetRoleByName(ctx context.Context, roleName string) (model.Role, error) { + role, err := r.getRoleByName(ctx, roleName) if err != nil { return model.Role{}, err } @@ -305,9 +243,9 @@ func (r *UserRepository) GetRoleByName(roleName string) (model.Role, error) { //} // private members -func (r *UserRepository) getUserByAccountId(accountId string, organizationId string) (model.User, error) { +func (r *UserRepository) getUserByAccountId(ctx context.Context, accountId string, organizationId string) (model.User, error) { user := model.User{} - res := r.db.Model(&model.User{}).Preload("Organization").Preload("Role"). + res := r.db.WithContext(ctx).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) @@ -320,9 +258,9 @@ func (r *UserRepository) getUserByAccountId(accountId string, organizationId str return user, nil } -func (r *UserRepository) getRoleByName(roleName string) (model.Role, error) { +func (r *UserRepository) getRoleByName(ctx context.Context, roleName string) (model.Role, error) { role := model.Role{} - res := r.db.First(&role, "name = ?", roleName) + res := r.db.WithContext(ctx).First(&role, "name = ?", roleName) if res.Error != nil { log.Errorf("error is :%s(%T)", res.Error.Error(), res.Error) return model.Role{}, res.Error @@ -331,9 +269,29 @@ func (r *UserRepository) getRoleByName(roleName string) (model.Role, error) { return model.Role{}, httpErrors.NewNotFoundError(httpErrors.NotFound, "", "") } - //if res.RowsAffected == 0 { - // return Role{}, nil - //} - return role, nil } + +func (r *UserRepository) AccountIdFilter(accountId string) FilterFunc { + return func(user *gorm.DB) *gorm.DB { + return user.Where("account_id = ?", accountId) + } +} + +func (r *UserRepository) OrganizationFilter(organization string) FilterFunc { + return func(user *gorm.DB) *gorm.DB { + return user.Where("organization_id = ?", organization) + } +} + +func (r *UserRepository) EmailFilter(email string) FilterFunc { + return func(user *gorm.DB) *gorm.DB { + return user.Where("email = ?", email) + } +} + +func (r *UserRepository) NameFilter(name string) FilterFunc { + return func(user *gorm.DB) *gorm.DB { + return user.Where("name = ?", name) + } +} diff --git a/internal/route/route.go b/internal/route/route.go index 6c8f16a3..b7d0b827 100644 --- a/internal/route/route.go +++ b/internal/route/route.go @@ -90,7 +90,6 @@ func SetupRouter(db *gorm.DB, argoClient argowf.ArgoClient, kc keycloak.IKeycloa authHandler := delivery.NewAuthHandler(usecaseFactory) r.HandleFunc(API_PREFIX+API_VERSION+"/auth/login", authHandler.Login).Methods(http.MethodPost) - r.HandleFunc(API_PREFIX+API_VERSION+"/auth/ping", authHandler.PingToken).Methods(http.MethodPost) r.Handle(API_PREFIX+API_VERSION+"/auth/logout", customMiddleware.Handle(internalApi.Logout, http.HandlerFunc(authHandler.Logout))).Methods(http.MethodPost) r.Handle(API_PREFIX+API_VERSION+"/auth/refresh", customMiddleware.Handle(internalApi.RefreshToken, http.HandlerFunc(authHandler.RefreshToken))).Methods(http.MethodPost) r.HandleFunc(API_PREFIX+API_VERSION+"/auth/find-id/verification", authHandler.FindId).Methods(http.MethodPost) diff --git a/internal/usecase/alert.go b/internal/usecase/alert.go index de77595a..01e6929b 100644 --- a/internal/usecase/alert.go +++ b/internal/usecase/alert.go @@ -51,7 +51,7 @@ func (u *AlertUsecase) Create(ctx context.Context, input domain.CreateAlertReque return fmt.Errorf("No data found") } - allClusters, err := u.clusterRepo.Fetch(nil) + allClusters, err := u.clusterRepo.Fetch(ctx, nil) if err != nil { return fmt.Errorf("No clusters") } @@ -64,12 +64,12 @@ func (u *AlertUsecase) Create(ctx context.Context, input domain.CreateAlertReque continue } - organization, err := u.organizationRepo.Get(organizationId) + organization, err := u.organizationRepo.Get(ctx, organizationId) if err != nil { log.ErrorWithContext(ctx, err) continue } - primaryCluster, err := u.clusterRepo.Get(domain.ClusterId(organization.PrimaryClusterId)) + primaryCluster, err := u.clusterRepo.Get(ctx, domain.ClusterId(organization.PrimaryClusterId)) if err != nil { log.ErrorWithContext(ctx, err) continue @@ -116,7 +116,7 @@ func (u *AlertUsecase) Create(ctx context.Context, input domain.CreateAlertReque RawData: rawData, } - _, err = u.repo.Create(dto) + _, err = u.repo.Create(ctx, dto) if err != nil { continue } @@ -130,7 +130,7 @@ func (u *AlertUsecase) Update(ctx context.Context, dto model.Alert) error { } func (u *AlertUsecase) Get(ctx context.Context, alertId uuid.UUID) (alert model.Alert, err error) { - alert, err = u.repo.Get(alertId) + alert, err = u.repo.Get(ctx, alertId) if err != nil { return alert, err } @@ -140,7 +140,7 @@ func (u *AlertUsecase) Get(ctx context.Context, alertId uuid.UUID) (alert model. } func (u *AlertUsecase) GetByName(ctx context.Context, organizationId string, name string) (out model.Alert, err error) { - out, err = u.repo.GetByName(organizationId, name) + out, err = u.repo.GetByName(ctx, organizationId, name) if err != nil { if errors.Is(err, gorm.ErrRecordNotFound) { return out, httpErrors.NewNotFoundError(err, "", "") @@ -151,7 +151,7 @@ func (u *AlertUsecase) GetByName(ctx context.Context, organizationId string, nam } func (u *AlertUsecase) Fetch(ctx context.Context, organizationId string, pg *pagination.Pagination) (alerts []model.Alert, err error) { - alerts, err = u.repo.Fetch(organizationId, pg) + alerts, err = u.repo.Fetch(ctx, organizationId, pg) if err != nil { return nil, err } @@ -174,7 +174,7 @@ func (u *AlertUsecase) Delete(ctx context.Context, dto model.Alert) (err error) return httpErrors.NewNotFoundError(err, "AL_NOT_FOUND_ALERT", "") } - err = u.repo.Delete(dto) + err = u.repo.Delete(ctx, dto) if err != nil { return err } @@ -188,7 +188,7 @@ func (u *AlertUsecase) CreateAlertAction(ctx context.Context, dto model.AlertAct return uuid.Nil, httpErrors.NewUnauthorizedError(fmt.Errorf("Invalid token"), "A_INVALID_TOKEN", "") } - _, err = u.repo.Get(dto.AlertId) + _, err = u.repo.Get(ctx, dto.AlertId) if err != nil { return uuid.Nil, httpErrors.NewBadRequestError(fmt.Errorf("Not found alert"), "AL_NOT_FOUND_ALERT", "") } @@ -197,7 +197,7 @@ func (u *AlertUsecase) CreateAlertAction(ctx context.Context, dto model.AlertAct dto.TakerId = &userId dto.CreatedAt = time.Now() - alertActionId, err = u.repo.CreateAlertAction(dto) + alertActionId, err = u.repo.CreateAlertAction(ctx, dto) if err != nil { return uuid.Nil, err } @@ -242,11 +242,11 @@ func (u *AlertUsecase) makeAdditionalInfo(alert *model.Alert) { 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) + appGroups, err := u.appGroupRepo.Fetch(ctx, primaryCluster.ID, nil) if err == nil { for _, appGroup := range appGroups { if appGroup.AppGroupType == domain.AppGroupType_LMA { - applications, err := u.appGroupRepo.GetApplications(appGroup.ID, domain.ApplicationType_GRAFANA) + applications, err := u.appGroupRepo.GetApplications(ctx, appGroup.ID, domain.ApplicationType_GRAFANA) if err != nil { return "" } diff --git a/internal/usecase/app-group.go b/internal/usecase/app-group.go index a73c0e6b..d492128d 100644 --- a/internal/usecase/app-group.go +++ b/internal/usecase/app-group.go @@ -43,7 +43,7 @@ func NewAppGroupUsecase(r repository.Repository, argoClient argowf.ArgoClient) I } 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) + out, err = u.repo.Fetch(ctx, clusterId, pg) if err != nil { return nil, err } @@ -58,12 +58,12 @@ func (u *AppGroupUsecase) Create(ctx context.Context, dto model.AppGroup) (id do userId := user.GetUserId() dto.CreatorId = &userId - cluster, err := u.clusterRepo.Get(dto.ClusterId) + cluster, err := u.clusterRepo.Get(ctx, dto.ClusterId) if err != nil { return "", httpErrors.NewBadRequestError(err, "AG_NOT_FOUND_CLUSTER", "") } - resAppGroups, err := u.repo.Fetch(dto.ClusterId, nil) + resAppGroups, err := u.repo.Fetch(ctx, dto.ClusterId, nil) if err != nil { return "", httpErrors.NewBadRequestError(err, "AG_NOT_FOUND_APPGROUP", "") } @@ -83,7 +83,7 @@ func (u *AppGroupUsecase) Create(ctx context.Context, dto model.AppGroup) (id do tksObjectStore := "minio" if cluster.CloudService != domain.CloudService_BYOH { tksObjectStore = "s3" - cloudAccounts, err := u.cloudAccountRepo.Fetch(cluster.OrganizationId, nil) + cloudAccounts, err := u.cloudAccountRepo.Fetch(ctx, cluster.OrganizationId, nil) if err != nil { return "", httpErrors.NewBadRequestError(fmt.Errorf("Failed to get cloudAccounts"), "", "") } @@ -107,9 +107,9 @@ func (u *AppGroupUsecase) Create(ctx context.Context, dto model.AppGroup) (id do } if dto.ID == "" { - dto.ID, err = u.repo.Create(dto) + dto.ID, err = u.repo.Create(ctx, dto) } else { - err = u.repo.Update(dto) + err = u.repo.Update(ctx, dto) } if err != nil { return "", httpErrors.NewInternalServerError(err, "AG_FAILED_TO_CREATE_APPGROUP", "") @@ -152,7 +152,7 @@ func (u *AppGroupUsecase) Create(ctx context.Context, dto model.AppGroup) (id do return "", httpErrors.NewInternalServerError(err, "AG_FAILED_TO_CALL_WORKFLOW", "") } - if err := u.repo.InitWorkflow(dto.ID, workflowId, domain.AppGroupStatus_INSTALLING); err != nil { + if err := u.repo.InitWorkflow(ctx, dto.ID, workflowId, domain.AppGroupStatus_INSTALLING); err != nil { return "", errors.Wrap(err, "Failed to initialize appGroup status") } @@ -160,7 +160,7 @@ func (u *AppGroupUsecase) Create(ctx context.Context, dto model.AppGroup) (id do } func (u *AppGroupUsecase) Get(ctx context.Context, id domain.AppGroupId) (out model.AppGroup, err error) { - appGroup, err := u.repo.Get(id) + appGroup, err := u.repo.Get(ctx, id) if err != nil { return model.AppGroup{}, err } @@ -168,11 +168,11 @@ func (u *AppGroupUsecase) Get(ctx context.Context, id domain.AppGroupId) (out mo } func (u *AppGroupUsecase) Delete(ctx context.Context, id domain.AppGroupId) (err error) { - appGroup, err := u.repo.Get(id) + appGroup, err := u.repo.Get(ctx, id) if err != nil { return fmt.Errorf("No appGroup for deletiing : %s", id) } - cluster, err := u.clusterRepo.Get(appGroup.ClusterId) + cluster, err := u.clusterRepo.Get(ctx, appGroup.ClusterId) if err != nil { return httpErrors.NewBadRequestError(err, "AG_NOT_FOUND_CLUSTER", "") } @@ -183,7 +183,7 @@ func (u *AppGroupUsecase) Delete(ctx context.Context, id domain.AppGroupId) (err tksObjectStore := "minio" if cluster.CloudService != domain.CloudService_BYOH { tksObjectStore = "s3" - cloudAccounts, err := u.cloudAccountRepo.Fetch(cluster.OrganizationId, nil) + cloudAccounts, err := u.cloudAccountRepo.Fetch(ctx, cluster.OrganizationId, nil) if err != nil { return httpErrors.NewBadRequestError(fmt.Errorf("Failed to get cloudAccounts"), "", "") } @@ -242,7 +242,7 @@ func (u *AppGroupUsecase) Delete(ctx context.Context, id domain.AppGroupId) (err log.DebugWithContext(ctx, "submited workflow name : ", workflowId) - if err := u.repo.InitWorkflow(id, workflowId, domain.AppGroupStatus_DELETING); err != nil { + if err := u.repo.InitWorkflow(ctx, id, workflowId, domain.AppGroupStatus_DELETING); err != nil { return fmt.Errorf("Failed to initialize appGroup status. err : %s", err) } @@ -257,7 +257,7 @@ func (u *AppGroupUsecase) Delete(ctx context.Context, id domain.AppGroupId) (err } 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) + out, err = u.repo.GetApplications(ctx, id, applicationType) if err != nil { return nil, err } @@ -265,7 +265,7 @@ func (u *AppGroupUsecase) GetApplications(ctx context.Context, id domain.AppGrou } func (u *AppGroupUsecase) UpdateApplication(ctx context.Context, dto model.Application) (err error) { - err = u.repo.UpsertApplication(dto) + err = u.repo.UpsertApplication(ctx, dto) if err != nil { return err } diff --git a/internal/usecase/app-serve-app.go b/internal/usecase/app-serve-app.go index 198b31a3..c58539c1 100644 --- a/internal/usecase/app-serve-app.go +++ b/internal/usecase/app-serve-app.go @@ -24,23 +24,23 @@ import ( ) type IAppServeAppUsecase interface { - 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 *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) - RollbackAppServeApp(appId string, taskId string) (ret string, err error) + CreateAppServeApp(ctx context.Context, app *model.AppServeApp) (appId string, taskId string, err error) + GetAppServeApps(ctx context.Context, organizationId string, showAll bool, pg *pagination.Pagination) ([]model.AppServeApp, error) + GetAppServeAppById(ctx context.Context, appId string) (*model.AppServeApp, error) + GetAppServeAppTasks(ctx context.Context, appId string, pg *pagination.Pagination) ([]model.AppServeAppTask, error) + GetAppServeAppTaskById(ctx context.Context, taskId string) (*model.AppServeAppTask, *model.AppServeApp, error) + GetAppServeAppLatestTask(ctx context.Context, appId string) (*model.AppServeAppTask, error) + GetNumOfAppsOnStack(ctx context.Context, organizationId string, clusterId string) (int64, error) + IsAppServeAppExist(ctx context.Context, appId string) (bool, error) + IsAppServeAppNameExist(ctx context.Context, orgId string, appName string) (bool, error) + IsAppServeAppNamespaceExist(ctx context.Context, clusterId string, namespace string) (bool, error) + UpdateAppServeAppStatus(ctx context.Context, appId string, taskId string, status string, output string) (ret string, err error) + DeleteAppServeApp(ctx context.Context, appId string) (res string, err error) + UpdateAppServeApp(ctx context.Context, app *model.AppServeApp, appTask *model.AppServeAppTask) (ret string, err error) + UpdateAppServeAppEndpoint(ctx context.Context, appId string, taskId string, endpoint string, previewEndpoint string, helmRevision int32) (string, error) + PromoteAppServeApp(ctx context.Context, appId string) (ret string, err error) + AbortAppServeApp(ctx context.Context, appId string) (ret string, err error) + RollbackAppServeApp(ctx context.Context, appId string, taskId string) (ret string, err error) } type AppServeAppUsecase struct { @@ -59,7 +59,7 @@ func NewAppServeAppUsecase(r repository.Repository, argoClient argowf.ArgoClient } } -func (u *AppServeAppUsecase) CreateAppServeApp(app *model.AppServeApp) (string, string, error) { +func (u *AppServeAppUsecase) CreateAppServeApp(ctx context.Context, app *model.AppServeApp) (string, string, error) { if app == nil { return "", "", fmt.Errorf("invalid app obj") } @@ -125,7 +125,7 @@ func (u *AppServeAppUsecase) CreateAppServeApp(app *model.AppServeApp) (string, log.Debug("After transform, extraEnv: ", extEnv) } - appId, taskId, err := u.repo.CreateAppServeApp(app) + appId, taskId, err := u.repo.CreateAppServeApp(ctx, app) if err != nil { log.Error(err) return "", "", errors.Wrap(err, "Failed to create app.") @@ -180,8 +180,8 @@ func (u *AppServeAppUsecase) CreateAppServeApp(app *model.AppServeApp) (string, return appId, app.Name, nil } -func (u *AppServeAppUsecase) GetAppServeApps(organizationId string, showAll bool, pg *pagination.Pagination) ([]model.AppServeApp, error) { - apps, err := u.repo.GetAppServeApps(organizationId, showAll, pg) +func (u *AppServeAppUsecase) GetAppServeApps(ctx context.Context, organizationId string, showAll bool, pg *pagination.Pagination) ([]model.AppServeApp, error) { + apps, err := u.repo.GetAppServeApps(ctx, organizationId, showAll, pg) if err != nil { fmt.Println(apps) } @@ -189,8 +189,8 @@ func (u *AppServeAppUsecase) GetAppServeApps(organizationId string, showAll bool return apps, nil } -func (u *AppServeAppUsecase) GetAppServeAppById(appId string) (*model.AppServeApp, error) { - asa, err := u.repo.GetAppServeAppById(appId) +func (u *AppServeAppUsecase) GetAppServeAppById(ctx context.Context, appId string) (*model.AppServeApp, error) { + asa, err := u.repo.GetAppServeAppById(ctx, appId) if err != nil { return nil, err } @@ -198,19 +198,19 @@ func (u *AppServeAppUsecase) GetAppServeAppById(appId string) (*model.AppServeAp /************************ * Construct grafana URL * ************************/ - organization, err := u.organizationRepo.Get(asa.OrganizationId) + organization, err := u.organizationRepo.Get(ctx, asa.OrganizationId) if err != nil { return asa, httpErrors.NewInternalServerError(errors.Wrap(err, fmt.Sprintf("Failed to get organization for app %s", asa.Name)), "S_FAILED_FETCH_ORGANIZATION", "") } - appGroupsInPrimaryCluster, err := u.appGroupRepo.Fetch(domain.ClusterId(organization.PrimaryClusterId), nil) + appGroupsInPrimaryCluster, err := u.appGroupRepo.Fetch(ctx, domain.ClusterId(organization.PrimaryClusterId), nil) if err != nil { return asa, err } for _, appGroup := range appGroupsInPrimaryCluster { if appGroup.AppGroupType == domain.AppGroupType_LMA { - applications, err := u.appGroupRepo.GetApplications(appGroup.ID, domain.ApplicationType_GRAFANA) + applications, err := u.appGroupRepo.GetApplications(ctx, appGroup.ID, domain.ApplicationType_GRAFANA) if err != nil { return asa, err } @@ -223,8 +223,8 @@ func (u *AppServeAppUsecase) GetAppServeAppById(appId string) (*model.AppServeAp return asa, nil } -func (u *AppServeAppUsecase) GetAppServeAppTasks(appId string, pg *pagination.Pagination) ([]model.AppServeAppTask, error) { - tasks, err := u.repo.GetAppServeAppTasksByAppId(appId, pg) +func (u *AppServeAppUsecase) GetAppServeAppTasks(ctx context.Context, appId string, pg *pagination.Pagination) ([]model.AppServeAppTask, error) { + tasks, err := u.repo.GetAppServeAppTasksByAppId(ctx, appId, pg) if err != nil { log.Debugf("Tasks: %v", tasks) } @@ -232,8 +232,8 @@ func (u *AppServeAppUsecase) GetAppServeAppTasks(appId string, pg *pagination.Pa return tasks, nil } -func (u *AppServeAppUsecase) GetAppServeAppTaskById(taskId string) (*model.AppServeAppTask, *model.AppServeApp, error) { - task, app, err := u.repo.GetAppServeAppTaskById(taskId) +func (u *AppServeAppUsecase) GetAppServeAppTaskById(ctx context.Context, taskId string) (*model.AppServeAppTask, *model.AppServeApp, error) { + task, app, err := u.repo.GetAppServeAppTaskById(ctx, taskId) if err != nil { return nil, nil, err } @@ -241,8 +241,8 @@ func (u *AppServeAppUsecase) GetAppServeAppTaskById(taskId string) (*model.AppSe return task, app, nil } -func (u *AppServeAppUsecase) GetAppServeAppLatestTask(appId string) (*model.AppServeAppTask, error) { - task, err := u.repo.GetAppServeAppLatestTask(appId) +func (u *AppServeAppUsecase) GetAppServeAppLatestTask(ctx context.Context, appId string) (*model.AppServeAppTask, error) { + task, err := u.repo.GetAppServeAppLatestTask(ctx, appId) if err != nil { return nil, err } @@ -250,8 +250,8 @@ func (u *AppServeAppUsecase) GetAppServeAppLatestTask(appId string) (*model.AppS return task, nil } -func (u *AppServeAppUsecase) GetNumOfAppsOnStack(organizationId string, clusterId string) (int64, error) { - numApps, err := u.repo.GetNumOfAppsOnStack(organizationId, clusterId) +func (u *AppServeAppUsecase) GetNumOfAppsOnStack(ctx context.Context, organizationId string, clusterId string) (int64, error) { + numApps, err := u.repo.GetNumOfAppsOnStack(ctx, organizationId, clusterId) if err != nil { return -1, err } @@ -259,8 +259,8 @@ func (u *AppServeAppUsecase) GetNumOfAppsOnStack(organizationId string, clusterI return numApps, nil } -func (u *AppServeAppUsecase) IsAppServeAppExist(appId string) (bool, error) { - count, err := u.repo.IsAppServeAppExist(appId) +func (u *AppServeAppUsecase) IsAppServeAppExist(ctx context.Context, appId string) (bool, error) { + count, err := u.repo.IsAppServeAppExist(ctx, appId) if err != nil { return false, err } @@ -272,8 +272,8 @@ func (u *AppServeAppUsecase) IsAppServeAppExist(appId string) (bool, error) { return false, nil } -func (u *AppServeAppUsecase) IsAppServeAppNameExist(orgId string, appName string) (bool, error) { - count, err := u.repo.IsAppServeAppNameExist(orgId, appName) +func (u *AppServeAppUsecase) IsAppServeAppNameExist(ctx context.Context, orgId string, appName string) (bool, error) { + count, err := u.repo.IsAppServeAppNameExist(ctx, orgId, appName) if err != nil { return false, err } @@ -285,7 +285,7 @@ func (u *AppServeAppUsecase) IsAppServeAppNameExist(orgId string, appName string return false, nil } -func (u *AppServeAppUsecase) IsAppServeAppNamespaceExist(clusterId string, new_ns string) (bool, error) { +func (u *AppServeAppUsecase) IsAppServeAppNamespaceExist(ctx context.Context, clusterId string, new_ns string) (bool, error) { clientset, err := kubernetes.GetClientFromClusterId(clusterId) if err != nil { log.Error(err) @@ -307,15 +307,12 @@ func (u *AppServeAppUsecase) IsAppServeAppNamespaceExist(clusterId string, new_n return false, nil } -func (u *AppServeAppUsecase) UpdateAppServeAppStatus( - appId string, - taskId string, - status string, +func (u *AppServeAppUsecase) UpdateAppServeAppStatus(ctx context.Context, appId string, taskId string, status string, output string) (string, error) { log.Info("Starting status update process..") - err := u.repo.UpdateStatus(appId, taskId, status, output) + err := u.repo.UpdateStatus(ctx, appId, taskId, status, output) if err != nil { log.Info("appId = ", appId) log.Info("taskId = ", taskId) @@ -325,6 +322,7 @@ func (u *AppServeAppUsecase) UpdateAppServeAppStatus( } func (u *AppServeAppUsecase) UpdateAppServeAppEndpoint( + ctx context.Context, appId string, taskId string, endpoint string, @@ -333,7 +331,7 @@ func (u *AppServeAppUsecase) UpdateAppServeAppEndpoint( log.Info("Starting endpoint update process..") - err := u.repo.UpdateEndpoint(appId, taskId, endpoint, previewEndpoint, helmRevision) + err := u.repo.UpdateEndpoint(ctx, appId, taskId, endpoint, previewEndpoint, helmRevision) if err != nil { log.Info("appId = ", appId) log.Info("taskId = ", taskId) @@ -342,8 +340,8 @@ func (u *AppServeAppUsecase) UpdateAppServeAppEndpoint( return fmt.Sprintf("The appId '%s' endpoint is being updated.", appId), nil } -func (u *AppServeAppUsecase) DeleteAppServeApp(appId string) (res string, err error) { - app, err := u.repo.GetAppServeAppById(appId) +func (u *AppServeAppUsecase) DeleteAppServeApp(ctx context.Context, appId string) (res string, err error) { + app, err := u.repo.GetAppServeAppById(ctx, appId) if err != nil { return "", fmt.Errorf("error while getting ASA Info from DB. Err: %s", err) } @@ -373,7 +371,7 @@ func (u *AppServeAppUsecase) DeleteAppServeApp(appId string) (res string, err er CreatedAt: time.Now(), } - taskId, err := u.repo.CreateTask(appTask) + taskId, err := u.repo.CreateTask(ctx, appTask) if err != nil { log.Error("taskId = ", taskId) log.Error("Failed to create delete task. Err:", err) @@ -382,7 +380,7 @@ func (u *AppServeAppUsecase) DeleteAppServeApp(appId string) (res string, err er log.Info("Updating app status to 'DELETING'..") - err = u.repo.UpdateStatus(appId, taskId, "DELETING", "") + err = u.repo.UpdateStatus(ctx, appId, taskId, "DELETING", "") if err != nil { log.Debug("appId = ", appId) log.Debug("taskId = ", taskId) @@ -413,12 +411,12 @@ 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 *model.AppServeApp, appTask *model.AppServeAppTask) (ret string, err error) { +func (u *AppServeAppUsecase) UpdateAppServeApp(ctx context.Context, app *model.AppServeApp, appTask *model.AppServeAppTask) (ret string, err error) { if appTask == nil { return "", errors.New("invalid parameters. appTask is nil") } - app_, err := u.repo.GetAppServeAppById(app.ID) + app_, err := u.repo.GetAppServeAppById(ctx, app.ID) if err != nil { return "", fmt.Errorf("error while getting ASA Info from DB. Err: %s", err) } @@ -480,7 +478,7 @@ func (u *AppServeAppUsecase) UpdateAppServeApp(app *model.AppServeApp, appTask * log.Debug("After transform, extraEnv: ", extEnv) } - taskId, err := u.repo.CreateTask(appTask) + taskId, err := u.repo.CreateTask(ctx, appTask) if err != nil { log.Info("taskId = ", taskId) return "", fmt.Errorf("failed to update app-serve application. Err: %s", err) @@ -489,7 +487,7 @@ func (u *AppServeAppUsecase) UpdateAppServeApp(app *model.AppServeApp, appTask * // Sync new task status to the parent app log.Info("Updating app status to 'PREPARING'..") - err = u.repo.UpdateStatus(app.ID, taskId, "PREPARING", "") + err = u.repo.UpdateStatus(ctx, app.ID, taskId, "PREPARING", "") if err != nil { log.Debug("appId = ", app.ID) log.Debug("taskId = ", taskId) @@ -547,8 +545,8 @@ func (u *AppServeAppUsecase) UpdateAppServeApp(app *model.AppServeApp, appTask * return message, nil } -func (u *AppServeAppUsecase) PromoteAppServeApp(appId string) (ret string, err error) { - app, err := u.repo.GetAppServeAppById(appId) +func (u *AppServeAppUsecase) PromoteAppServeApp(ctx context.Context, appId string) (ret string, err error) { + app, err := u.repo.GetAppServeAppById(ctx, appId) if err != nil { return "", fmt.Errorf("error while getting ASA Info from DB. Err: %s", err) } @@ -565,7 +563,7 @@ func (u *AppServeAppUsecase) PromoteAppServeApp(appId string) (ret string, err e log.Info("Updating app status to 'PROMOTING'..") - err = u.repo.UpdateStatus(appId, latestTaskId, "PROMOTING", "") + err = u.repo.UpdateStatus(ctx, appId, latestTaskId, "PROMOTING", "") if err != nil { log.Debug("appId = ", appId) log.Debug("taskId = ", latestTaskId) @@ -599,8 +597,8 @@ func (u *AppServeAppUsecase) PromoteAppServeApp(appId string) (ret string, err e "Confirm result by checking the app status after a while.", app.Name), nil } -func (u *AppServeAppUsecase) AbortAppServeApp(appId string) (ret string, err error) { - app, err := u.repo.GetAppServeAppById(appId) +func (u *AppServeAppUsecase) AbortAppServeApp(ctx context.Context, appId string) (ret string, err error) { + app, err := u.repo.GetAppServeAppById(ctx, appId) if err != nil { return "", fmt.Errorf("error while getting ASA Info from DB. Err: %s", err) } @@ -617,7 +615,7 @@ func (u *AppServeAppUsecase) AbortAppServeApp(appId string) (ret string, err err log.Info("Updating app status to 'ABORTING'..") - err = u.repo.UpdateStatus(appId, latestTaskId, "ABORTING", "") + err = u.repo.UpdateStatus(ctx, appId, latestTaskId, "ABORTING", "") if err != nil { log.Debug("appId = ", appId) log.Debug("taskId = ", latestTaskId) @@ -651,10 +649,10 @@ func (u *AppServeAppUsecase) AbortAppServeApp(appId string) (ret string, err err "Confirm result by checking the app status after a while.", app.Name), nil } -func (u *AppServeAppUsecase) RollbackAppServeApp(appId string, taskId string) (ret string, err error) { +func (u *AppServeAppUsecase) RollbackAppServeApp(ctx context.Context, appId string, taskId string) (ret string, err error) { log.Info("Starting rollback process..") - app, err := u.repo.GetAppServeAppById(appId) + app, err := u.repo.GetAppServeAppById(ctx, appId) if err != nil { return "", err } @@ -683,7 +681,7 @@ func (u *AppServeAppUsecase) RollbackAppServeApp(appId string, taskId string) (r task.RollbackVersion = targetVer // Creates new task record from the target task - newTaskId, err := u.repo.CreateTask(&task) + newTaskId, err := u.repo.CreateTask(ctx, &task) if err != nil { log.Info("taskId = ", newTaskId) return "", fmt.Errorf("failed to rollback app-serve application. Err: %s", err) @@ -691,7 +689,7 @@ func (u *AppServeAppUsecase) RollbackAppServeApp(appId string, taskId string) (r log.Info("Updating app status to 'ROLLBACKING'..") - err = u.repo.UpdateStatus(appId, newTaskId, "ROLLBACKING", "") + err = u.repo.UpdateStatus(ctx, appId, newTaskId, "ROLLBACKING", "") if err != nil { log.Debug("appId = ", appId) log.Debug("taskId = ", newTaskId) diff --git a/internal/usecase/audit.go b/internal/usecase/audit.go index 0e3e5165..9a0f06cc 100644 --- a/internal/usecase/audit.go +++ b/internal/usecase/audit.go @@ -36,7 +36,7 @@ func (u *AuditUsecase) Create(ctx context.Context, dto model.Audit) (auditId uui dto.UserId = &userId } } - auditId, err = u.repo.Create(dto) + auditId, err = u.repo.Create(ctx, dto) if err != nil { return uuid.Nil, httpErrors.NewInternalServerError(err, "", "") } @@ -44,7 +44,7 @@ func (u *AuditUsecase) Create(ctx context.Context, dto model.Audit) (auditId uui } func (u *AuditUsecase) Get(ctx context.Context, auditId uuid.UUID) (res model.Audit, err error) { - res, err = u.repo.Get(auditId) + res, err = u.repo.Get(ctx, auditId) if err != nil { return model.Audit{}, err } @@ -52,7 +52,7 @@ func (u *AuditUsecase) Get(ctx context.Context, auditId uuid.UUID) (res model.Au } func (u *AuditUsecase) Fetch(ctx context.Context, pg *pagination.Pagination) (audits []model.Audit, err error) { - audits, err = u.repo.Fetch(pg) + audits, err = u.repo.Fetch(ctx, pg) if err != nil { return nil, err } @@ -60,7 +60,7 @@ func (u *AuditUsecase) Fetch(ctx context.Context, pg *pagination.Pagination) (au } func (u *AuditUsecase) Delete(ctx context.Context, dto model.Audit) (err error) { - err = u.repo.Delete(dto.ID) + err = u.repo.Delete(ctx, dto.ID) if err != nil { return httpErrors.NewNotFoundError(err, "", "") } diff --git a/internal/usecase/auth.go b/internal/usecase/auth.go index 7213d1f2..a85c2c09 100644 --- a/internal/usecase/auth.go +++ b/internal/usecase/auth.go @@ -1,6 +1,7 @@ package usecase import ( + "context" "crypto/rand" "crypto/tls" "encoding/base64" @@ -19,7 +20,6 @@ import ( "golang.org/x/oauth2" "github.com/Nerzal/gocloak/v13" - "github.com/google/uuid" "github.com/openinfradev/tks-api/internal" "github.com/openinfradev/tks-api/internal/helper" "github.com/openinfradev/tks-api/internal/keycloak" @@ -31,15 +31,14 @@ import ( ) type IAuthUsecase interface { - 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) - FindPassword(code string, accountId string, email string, userName string, organizationId string) error - VerifyIdentity(accountId string, email string, userName string, organizationId string) error - SingleSignIn(organizationId, accountId, password string) ([]*http.Cookie, error) - SingleSignOut(organizationId string) (string, []*http.Cookie, error) - VerifyToken(token string) (bool, error) + Login(ctx context.Context, accountId string, password string, organizationId string) (model.User, error) + Logout(ctx context.Context, accessToken string, organizationId string) error + FindId(ctx context.Context, code string, email string, userName string, organizationId string) (string, error) + FindPassword(ctx context.Context, code string, accountId string, email string, userName string, organizationId string) error + VerifyIdentity(ctx context.Context, accountId string, email string, userName string, organizationId string) error + SingleSignIn(ctx context.Context, organizationId, accountId, password string) ([]*http.Cookie, error) + SingleSignOut(ctx context.Context, organizationId string) (string, []*http.Cookie, error) + VerifyToken(ctx context.Context, token string) (bool, error) } const ( @@ -68,9 +67,9 @@ func NewAuthUsecase(r repository.Repository, kc keycloak.IKeycloak) IAuthUsecase } } -func (u *AuthUsecase) Login(accountId string, password string, organizationId string) (model.User, error) { +func (u *AuthUsecase) Login(ctx context.Context, accountId string, password string, organizationId string) (model.User, error) { // Authentication with DB - user, err := u.userRepository.Get(accountId, organizationId) + user, err := u.userRepository.Get(ctx, accountId, organizationId) if err != nil { return model.User{}, httpErrors.NewBadRequestError(err, "A_INVALID_ID", "") } @@ -102,7 +101,7 @@ func (u *AuthUsecase) Login(accountId string, password string, organizationId st return user, nil } -func (u *AuthUsecase) Logout(accessToken string, organizationName string) error { +func (u *AuthUsecase) Logout(ctx context.Context, accessToken string, organizationName string) error { // [TODO] refresh token 을 추가하고, session timeout 을 줄이는 방향으로 고려할 것 err := u.kc.Logout(accessToken, organizationName) if err != nil { @@ -111,64 +110,8 @@ func (u *AuthUsecase) Logout(accessToken string, organizationName string) error return nil } -func (u *AuthUsecase) PingToken(accessToken string, organizationId string) error { - parsedToken, _, err := new(jwtWithouKey.Parser).ParseUnverified(accessToken, jwtWithouKey.MapClaims{}) - if err != nil { - return err - } - - if parsedToken.Method.Alg() != "RS256" { - return fmt.Errorf("invalid token") - } - - if parsedToken.Claims.Valid() != nil { - return fmt.Errorf("invalid token") - } - - isActive, err := u.kc.VerifyAccessToken(accessToken, organizationId) - if err != nil { - log.Errorf("failed to verify access token: %v", err) - return err - } - if !isActive { - return fmt.Errorf("token is not active") - } - - userId, err := uuid.Parse(parsedToken.Claims.(jwtWithouKey.MapClaims)["sub"].(string)) - if err != nil { - log.Errorf("failed to verify access token: %v", err) - - return err - } - requestSessionId, ok := parsedToken.Claims.(jwtWithouKey.MapClaims)["sid"].(string) - if !ok { - return fmt.Errorf("session id is not found in token") - } - - sessionIds, err := u.kc.GetSessions(userId.String(), organizationId) - if err != nil { - log.Errorf("failed to get sessions: %v", err) - - return err - } - if len(*sessionIds) == 0 { - return fmt.Errorf("invalid session") - } - var matched bool = false - for _, id := range *sessionIds { - if id == requestSessionId { - matched = true - break - } - } - if !matched { - return fmt.Errorf("invalid session") - } - return nil -} - -func (u *AuthUsecase) FindId(code string, email string, userName string, organizationId string) (string, error) { - users, err := u.userRepository.List(u.userRepository.OrganizationFilter(organizationId), +func (u *AuthUsecase) FindId(ctx context.Context, code string, email string, userName string, organizationId string) (string, error) { + users, err := u.userRepository.List(ctx, u.userRepository.OrganizationFilter(organizationId), u.userRepository.NameFilter(userName), u.userRepository.EmailFilter(email)) if err != nil && users == nil { return "", httpErrors.NewBadRequestError(err, "A_INVALID_ID", "") @@ -176,7 +119,7 @@ func (u *AuthUsecase) FindId(code string, email string, userName string, organiz if err != nil { return "", httpErrors.NewInternalServerError(err, "", "") } - emailCode, err := u.authRepository.GetEmailCode((*users)[0].ID) + emailCode, err := u.authRepository.GetEmailCode(ctx, (*users)[0].ID) if err != nil { return "", httpErrors.NewInternalServerError(err, "", "") } @@ -186,15 +129,15 @@ func (u *AuthUsecase) FindId(code string, email string, userName string, organiz if emailCode.Code != code { return "", httpErrors.NewBadRequestError(fmt.Errorf("invalid code"), "A_INVALID_CODE", "") } - if err := u.authRepository.DeleteEmailCode((*users)[0].ID); err != nil { + if err := u.authRepository.DeleteEmailCode(ctx, (*users)[0].ID); err != nil { return "", httpErrors.NewInternalServerError(err, "", "") } return (*users)[0].AccountId, nil } -func (u *AuthUsecase) FindPassword(code string, accountId string, email string, userName string, organizationId string) error { - users, err := u.userRepository.List(u.userRepository.OrganizationFilter(organizationId), +func (u *AuthUsecase) FindPassword(ctx context.Context, code string, accountId string, email string, userName string, organizationId string) error { + users, err := u.userRepository.List(ctx, u.userRepository.OrganizationFilter(organizationId), u.userRepository.AccountIdFilter(accountId), u.userRepository.NameFilter(userName), u.userRepository.EmailFilter(email)) if err != nil && users == nil { @@ -204,7 +147,7 @@ func (u *AuthUsecase) FindPassword(code string, accountId string, email string, return httpErrors.NewInternalServerError(err, "", "") } user := (*users)[0] - emailCode, err := u.authRepository.GetEmailCode(user.ID) + emailCode, err := u.authRepository.GetEmailCode(ctx, user.ID) if err != nil { return httpErrors.NewInternalServerError(err, "", "") } @@ -231,7 +174,7 @@ func (u *AuthUsecase) FindPassword(code string, accountId string, email string, return httpErrors.NewInternalServerError(err, "", "") } - if err = u.userRepository.UpdatePasswordAt(user.ID, organizationId, true); err != nil { + if err = u.userRepository.UpdatePasswordAt(ctx, user.ID, organizationId, true); err != nil { return httpErrors.NewInternalServerError(err, "", "") } @@ -247,22 +190,22 @@ func (u *AuthUsecase) FindPassword(code string, accountId string, email string, return httpErrors.NewInternalServerError(err, "", "") } - if err = u.authRepository.DeleteEmailCode(user.ID); err != nil { + if err = u.authRepository.DeleteEmailCode(ctx, user.ID); err != nil { return httpErrors.NewInternalServerError(err, "", "") } return nil } -func (u *AuthUsecase) VerifyIdentity(accountId string, email string, userName string, organizationId string) error { +func (u *AuthUsecase) VerifyIdentity(ctx context.Context, accountId string, email string, userName string, organizationId string) error { var users *[]model.User var err error if accountId == "" { - users, err = u.userRepository.List(u.userRepository.OrganizationFilter(organizationId), + users, err = u.userRepository.List(ctx, u.userRepository.OrganizationFilter(organizationId), u.userRepository.NameFilter(userName), u.userRepository.EmailFilter(email)) } else { - users, err = u.userRepository.List(u.userRepository.OrganizationFilter(organizationId), + users, err = u.userRepository.List(ctx, u.userRepository.OrganizationFilter(organizationId), u.userRepository.AccountIdFilter(accountId), u.userRepository.NameFilter(userName), u.userRepository.EmailFilter(email)) } @@ -277,13 +220,13 @@ func (u *AuthUsecase) VerifyIdentity(accountId string, email string, userName st if err != nil { return httpErrors.NewInternalServerError(err, "", "") } - _, err = u.authRepository.GetEmailCode((*users)[0].ID) + _, err = u.authRepository.GetEmailCode(ctx, (*users)[0].ID) if err != nil { - if err := u.authRepository.CreateEmailCode((*users)[0].ID, code); err != nil { + if err := u.authRepository.CreateEmailCode(ctx, (*users)[0].ID, code); err != nil { return httpErrors.NewInternalServerError(err, "", "") } } else { - if err := u.authRepository.UpdateEmailCode((*users)[0].ID, code); err != nil { + if err := u.authRepository.UpdateEmailCode(ctx, (*users)[0].ID, code); err != nil { return httpErrors.NewInternalServerError(err, "", "") } } @@ -304,7 +247,7 @@ func (u *AuthUsecase) VerifyIdentity(accountId string, email string, userName st return nil } -func (u *AuthUsecase) SingleSignIn(organizationId, accountId, password string) ([]*http.Cookie, error) { +func (u *AuthUsecase) SingleSignIn(ctx context.Context, organizationId, accountId, password string) ([]*http.Cookie, error) { cookies, err := makingCookie(organizationId, accountId, password) if err != nil { return nil, err @@ -316,22 +259,22 @@ func (u *AuthUsecase) SingleSignIn(organizationId, accountId, password string) ( return cookies, nil } -func (u *AuthUsecase) SingleSignOut(organizationId string) (string, []*http.Cookie, error) { +func (u *AuthUsecase) SingleSignOut(ctx context.Context, organizationId string) (string, []*http.Cookie, error) { var redirectUrl string - organization, err := u.organizationRepository.Get(organizationId) + organization, err := u.organizationRepository.Get(ctx, organizationId) if err != nil { return "", nil, err } - appGroupsInPrimaryCluster, err := u.appgroupRepository.Fetch(domain.ClusterId(organization.PrimaryClusterId), nil) + appGroupsInPrimaryCluster, err := u.appgroupRepository.Fetch(ctx, domain.ClusterId(organization.PrimaryClusterId), nil) if err != nil { return "", nil, err } for _, appGroup := range appGroupsInPrimaryCluster { if appGroup.AppGroupType == domain.AppGroupType_LMA { - applications, err := u.appgroupRepository.GetApplications(appGroup.ID, domain.ApplicationType_GRAFANA) + applications, err := u.appgroupRepository.GetApplications(ctx, appGroup.ID, domain.ApplicationType_GRAFANA) if err != nil { return "", nil, err } @@ -366,7 +309,7 @@ func (u *AuthUsecase) SingleSignOut(organizationId string) (string, []*http.Cook return redirectUrl, cookies, nil } -func (u *AuthUsecase) VerifyToken(token string) (bool, error) { +func (u *AuthUsecase) VerifyToken(ctx context.Context, token string) (bool, error) { parsedToken, _, err := new(jwtWithouKey.Parser).ParseUnverified(token, jwtWithouKey.MapClaims{}) if err != nil { return false, err diff --git a/internal/usecase/auth_test.go b/internal/usecase/auth_test.go deleted file mode 100644 index 85a2c829..00000000 --- a/internal/usecase/auth_test.go +++ /dev/null @@ -1,9 +0,0 @@ -package usecase_test - -import ( - "testing" -) - -func TestGet(t *testing.T) { - -} diff --git a/internal/usecase/cloud-account.go b/internal/usecase/cloud-account.go index b6719bbb..26e948e9 100644 --- a/internal/usecase/cloud-account.go +++ b/internal/usecase/cloud-account.go @@ -76,7 +76,7 @@ func (u *CloudAccountUsecase) Create(ctx context.Context, dto model.CloudAccount return uuid.Nil, httpErrors.NewBadRequestError(httpErrors.DuplicateResource, "", "사용 중인 AwsAccountId 입니다. 관리자에게 문의하세요.") } - cloudAccountId, err = u.repo.Create(dto) + cloudAccountId, err = u.repo.Create(ctx, dto) if err != nil { return uuid.Nil, httpErrors.NewInternalServerError(err, "", "") } @@ -84,7 +84,7 @@ func (u *CloudAccountUsecase) Create(ctx context.Context, dto model.CloudAccount // FOR TEST. ADD MAGIC KEYWORD if strings.Contains(dto.Name, domain.CLOUD_ACCOUNT_INCLUSTER) { - if err := u.repo.InitWorkflow(cloudAccountId, "", domain.CloudAccountStatus_CREATED); err != nil { + if err := u.repo.InitWorkflow(ctx, cloudAccountId, "", domain.CloudAccountStatus_CREATED); err != nil { return uuid.Nil, errors.Wrap(err, "Failed to initialize status") } return cloudAccountId, nil @@ -108,7 +108,7 @@ func (u *CloudAccountUsecase) Create(ctx context.Context, dto model.CloudAccount } log.InfoWithContext(ctx, "submited workflow :", workflowId) - if err := u.repo.InitWorkflow(cloudAccountId, workflowId, domain.CloudAccountStatus_CREATING); err != nil { + if err := u.repo.InitWorkflow(ctx, cloudAccountId, workflowId, domain.CloudAccountStatus_CREATING); err != nil { return uuid.Nil, errors.Wrap(err, "Failed to initialize status") } @@ -124,7 +124,7 @@ func (u *CloudAccountUsecase) Update(ctx context.Context, dto model.CloudAccount dto.Resource = "TODO server result or additional information" dto.UpdatorId = &userId - err := u.repo.Update(dto) + err := u.repo.Update(ctx, dto) if err != nil { return httpErrors.NewInternalServerError(err, "", "") } @@ -132,48 +132,48 @@ func (u *CloudAccountUsecase) Update(ctx context.Context, dto model.CloudAccount } func (u *CloudAccountUsecase) Get(ctx context.Context, cloudAccountId uuid.UUID) (res model.CloudAccount, err error) { - res, err = u.repo.Get(cloudAccountId) + res, err = u.repo.Get(ctx, cloudAccountId) if err != nil { return model.CloudAccount{}, err } - res.Clusters = u.getClusterCnt(cloudAccountId) + res.Clusters = u.getClusterCnt(ctx, cloudAccountId) return } func (u *CloudAccountUsecase) GetByName(ctx context.Context, organizationId string, name string) (res model.CloudAccount, err error) { - res, err = u.repo.GetByName(organizationId, name) + res, err = u.repo.GetByName(ctx, organizationId, name) if err != nil { if errors.Is(err, gorm.ErrRecordNotFound) { return model.CloudAccount{}, httpErrors.NewNotFoundError(err, "", "") } return model.CloudAccount{}, err } - res.Clusters = u.getClusterCnt(res.ID) + res.Clusters = u.getClusterCnt(ctx, res.ID) return } func (u *CloudAccountUsecase) GetByAwsAccountId(ctx context.Context, awsAccountId string) (res model.CloudAccount, err error) { - res, err = u.repo.GetByAwsAccountId(awsAccountId) + res, err = u.repo.GetByAwsAccountId(ctx, awsAccountId) if err != nil { if errors.Is(err, gorm.ErrRecordNotFound) { return model.CloudAccount{}, httpErrors.NewNotFoundError(err, "", "") } return model.CloudAccount{}, err } - res.Clusters = u.getClusterCnt(res.ID) + res.Clusters = u.getClusterCnt(ctx, res.ID) return } func (u *CloudAccountUsecase) Fetch(ctx context.Context, organizationId string, pg *pagination.Pagination) (cloudAccounts []model.CloudAccount, err error) { - cloudAccounts, err = u.repo.Fetch(organizationId, pg) + cloudAccounts, err = u.repo.Fetch(ctx, organizationId, pg) if err != nil { return nil, err } for i, cloudAccount := range cloudAccounts { - cloudAccounts[i].Clusters = u.getClusterCnt(cloudAccount.ID) + cloudAccounts[i].Clusters = u.getClusterCnt(ctx, cloudAccount.ID) } return } @@ -191,7 +191,7 @@ func (u *CloudAccountUsecase) Delete(ctx context.Context, dto model.CloudAccount } dto.UpdatorId = &userId - if u.getClusterCnt(dto.ID) > 0 { + if u.getClusterCnt(ctx, dto.ID) > 0 { return fmt.Errorf("사용 중인 클러스터가 있어 삭제할 수 없습니다.") } @@ -213,7 +213,7 @@ func (u *CloudAccountUsecase) Delete(ctx context.Context, dto model.CloudAccount } log.InfoWithContext(ctx, "submited workflow :", workflowId) - if err := u.repo.InitWorkflow(dto.ID, workflowId, domain.CloudAccountStatus_DELETING); err != nil { + if err := u.repo.InitWorkflow(ctx, dto.ID, workflowId, domain.CloudAccountStatus_DELETING); err != nil { return errors.Wrap(err, "Failed to initialize status") } @@ -221,7 +221,7 @@ func (u *CloudAccountUsecase) Delete(ctx context.Context, dto model.CloudAccount } func (u *CloudAccountUsecase) DeleteForce(ctx context.Context, cloudAccountId uuid.UUID) (err error) { - cloudAccount, err := u.repo.Get(cloudAccountId) + cloudAccount, err := u.repo.Get(ctx, cloudAccountId) if err != nil { return err } @@ -231,11 +231,11 @@ func (u *CloudAccountUsecase) DeleteForce(ctx context.Context, cloudAccountId uu return fmt.Errorf("The status is not CREATE_ERROR. %s", cloudAccount.Status) } - if u.getClusterCnt(cloudAccountId) > 0 { + if u.getClusterCnt(ctx, cloudAccountId) > 0 { return fmt.Errorf("사용 중인 클러스터가 있어 삭제할 수 없습니다.") } - err = u.repo.Delete(cloudAccountId) + err = u.repo.Delete(ctx, cloudAccountId) if err != nil { return err } @@ -244,7 +244,7 @@ func (u *CloudAccountUsecase) DeleteForce(ctx context.Context, cloudAccountId uu } func (u *CloudAccountUsecase) GetResourceQuota(ctx context.Context, cloudAccountId uuid.UUID) (available bool, out domain.ResourceQuota, err error) { - cloudAccount, err := u.repo.Get(cloudAccountId) + cloudAccount, err := u.repo.Get(ctx, cloudAccountId) if err != nil { return false, out, err } @@ -442,10 +442,10 @@ func (u *CloudAccountUsecase) GetResourceQuota(ctx context.Context, cloudAccount return true, out, nil } -func (u *CloudAccountUsecase) getClusterCnt(cloudAccountId uuid.UUID) (cnt int) { +func (u *CloudAccountUsecase) getClusterCnt(ctx context.Context, cloudAccountId uuid.UUID) (cnt int) { cnt = 0 - clusters, err := u.clusterRepo.FetchByCloudAccountId(cloudAccountId, nil) + clusters, err := u.clusterRepo.FetchByCloudAccountId(ctx, cloudAccountId, nil) if err != nil { log.Error("Failed to get clusters by cloudAccountId. err : ", err) return cnt diff --git a/internal/usecase/cluster.go b/internal/usecase/cluster.go index e22233f3..b7f3df01 100644 --- a/internal/usecase/cluster.go +++ b/internal/usecase/cluster.go @@ -109,9 +109,9 @@ func (u *ClusterUsecase) Fetch(ctx context.Context, organizationId string, pg *p if organizationId == "" { // [TODO] 사용자가 속한 organization 리스트 - out, err = u.repo.Fetch(pg) + out, err = u.repo.Fetch(ctx, pg) } else { - out, err = u.repo.FetchByOrganizationId(organizationId, user.GetUserId(), pg) + out, err = u.repo.FetchByOrganizationId(ctx, organizationId, user.GetUserId(), pg) } if err != nil { @@ -125,7 +125,7 @@ func (u *ClusterUsecase) FetchByCloudAccountId(ctx context.Context, cloudAccount return nil, fmt.Errorf("Invalid cloudAccountId") } - out, err = u.repo.Fetch(pg) + out, err = u.repo.Fetch(ctx, pg) if err != nil { return nil, err @@ -139,13 +139,13 @@ func (u *ClusterUsecase) Create(ctx context.Context, dto model.Cluster) (cluster return "", httpErrors.NewBadRequestError(fmt.Errorf("Invalid token"), "", "") } - _, err = u.repo.GetByName(dto.OrganizationId, dto.Name) + _, err = u.repo.GetByName(ctx, dto.OrganizationId, dto.Name) if err == nil { return "", httpErrors.NewBadRequestError(httpErrors.DuplicateResource, "", "") } // check cloudAccount - cloudAccounts, err := u.cloudAccountRepo.Fetch(dto.OrganizationId, nil) + cloudAccounts, err := u.cloudAccountRepo.Fetch(ctx, dto.OrganizationId, nil) if err != nil { return "", httpErrors.NewBadRequestError(fmt.Errorf("Failed to get cloudAccounts"), "", "") } @@ -168,7 +168,7 @@ func (u *ClusterUsecase) Create(ctx context.Context, dto model.Cluster) (cluster } // check stackTemplate - stackTemplate, err := u.stackTemplateRepo.Get(dto.StackTemplateId) + stackTemplate, err := u.stackTemplateRepo.Get(ctx, dto.StackTemplateId) if err != nil { return "", httpErrors.NewBadRequestError(errors.Wrap(err, "Invalid stackTemplateId"), "", "") } @@ -178,7 +178,7 @@ func (u *ClusterUsecase) Create(ctx context.Context, dto model.Cluster) (cluster userId := user.GetUserId() dto.CreatorId = &userId - clusterId, err = u.repo.Create(dto) + clusterId, err = u.repo.Create(ctx, dto) if err != nil { return "", errors.Wrap(err, "Failed to create cluster") } @@ -206,7 +206,7 @@ func (u *ClusterUsecase) Create(ctx context.Context, dto model.Cluster) (cluster } log.InfoWithContext(ctx, "Successfully submited workflow: ", workflowId) - if err := u.repo.InitWorkflow(clusterId, workflowId, domain.ClusterStatus_INSTALLING); err != nil { + if err := u.repo.InitWorkflow(ctx, clusterId, workflowId, domain.ClusterStatus_INSTALLING); err != nil { return "", errors.Wrap(err, "Failed to initialize status") } @@ -219,18 +219,18 @@ func (u *ClusterUsecase) Import(ctx context.Context, dto model.Cluster) (cluster return "", httpErrors.NewBadRequestError(fmt.Errorf("Invalid token"), "", "") } - _, err = u.repo.GetByName(dto.OrganizationId, dto.Name) + _, err = u.repo.GetByName(ctx, dto.OrganizationId, dto.Name) if err == nil { return "", httpErrors.NewBadRequestError(httpErrors.DuplicateResource, "", "") } - _, err = u.organizationRepo.Get(dto.OrganizationId) + _, err = u.organizationRepo.Get(ctx, dto.OrganizationId) if err != nil { return "", httpErrors.NewBadRequestError(fmt.Errorf("Invalid organizationId"), "", "") } // check stackTemplate - stackTemplate, err := u.stackTemplateRepo.Get(dto.StackTemplateId) + stackTemplate, err := u.stackTemplateRepo.Get(ctx, dto.StackTemplateId) if err != nil { return "", httpErrors.NewBadRequestError(errors.Wrap(err, "Invalid stackTemplateId"), "", "") } @@ -241,7 +241,7 @@ func (u *ClusterUsecase) Import(ctx context.Context, dto model.Cluster) (cluster dto.ID = "tks-admin" dto.Name = "tks-admin" } - clusterId, err = u.repo.Create(dto) + clusterId, err = u.repo.Create(ctx, dto) if err != nil { return "", errors.Wrap(err, "Failed to create cluster") } @@ -268,7 +268,7 @@ func (u *ClusterUsecase) Import(ctx context.Context, dto model.Cluster) (cluster } log.InfoWithContext(ctx, "Successfully submited workflow: ", workflowId) - if err := u.repo.InitWorkflow(clusterId, workflowId, domain.ClusterStatus_INSTALLING); err != nil { + if err := u.repo.InitWorkflow(ctx, clusterId, workflowId, domain.ClusterStatus_INSTALLING); err != nil { return "", errors.Wrap(err, "Failed to initialize status") } @@ -281,12 +281,12 @@ func (u *ClusterUsecase) Bootstrap(ctx context.Context, dto model.Cluster) (clus return "", httpErrors.NewBadRequestError(fmt.Errorf("Invalid token"), "", "") } - _, err = u.repo.GetByName(dto.OrganizationId, dto.Name) + _, err = u.repo.GetByName(ctx, dto.OrganizationId, dto.Name) if err == nil { return "", httpErrors.NewBadRequestError(httpErrors.DuplicateResource, "", "") } - stackTemplate, err := u.stackTemplateRepo.Get(dto.StackTemplateId) + stackTemplate, err := u.stackTemplateRepo.Get(ctx, dto.StackTemplateId) if err != nil { return "", httpErrors.NewBadRequestError(errors.Wrap(err, "Invalid stackTemplateId"), "", "") } @@ -297,7 +297,7 @@ func (u *ClusterUsecase) Bootstrap(ctx context.Context, dto model.Cluster) (clus userId := user.GetUserId() dto.CreatorId = &userId - clusterId, err = u.repo.Create(dto) + clusterId, err = u.repo.Create(ctx, dto) if err != nil { return "", errors.Wrap(err, "Failed to create cluster") } @@ -315,7 +315,7 @@ func (u *ClusterUsecase) Bootstrap(ctx context.Context, dto model.Cluster) (clus } log.InfoWithContext(ctx, "Successfully submited workflow: ", workflowId) - if err := u.repo.InitWorkflow(clusterId, workflowId, domain.ClusterStatus_BOOTSTRAPPING); err != nil { + if err := u.repo.InitWorkflow(ctx, clusterId, workflowId, domain.ClusterStatus_BOOTSTRAPPING); err != nil { return "", errors.Wrap(err, "Failed to initialize status") } @@ -328,7 +328,7 @@ func (u *ClusterUsecase) Install(ctx context.Context, clusterId domain.ClusterId return httpErrors.NewBadRequestError(fmt.Errorf("Invalid token"), "", "") } - cluster, err := u.repo.Get(clusterId) + cluster, err := u.repo.Get(ctx, clusterId) if err != nil { return httpErrors.NewBadRequestError(fmt.Errorf("Invalid clusterId"), "C_INVALID_CLUSTER_ID", "") } @@ -336,7 +336,7 @@ func (u *ClusterUsecase) Install(ctx context.Context, clusterId domain.ClusterId return httpErrors.NewBadRequestError(fmt.Errorf("Invalid cloudService"), "C_INVALID_CLOUD_SERVICE", "") } - stackTemplate, err := u.stackTemplateRepo.Get(cluster.StackTemplateId) + stackTemplate, err := u.stackTemplateRepo.Get(ctx, cluster.StackTemplateId) if err != nil { return httpErrors.NewBadRequestError(errors.Wrap(err, "Invalid stackTemplateId"), "", "") } @@ -367,7 +367,7 @@ func (u *ClusterUsecase) Install(ctx context.Context, clusterId domain.ClusterId } log.InfoWithContext(ctx, "Successfully submited workflow: ", workflowId) - if err := u.repo.InitWorkflow(cluster.ID, workflowId, domain.ClusterStatus_INSTALLING); err != nil { + if err := u.repo.InitWorkflow(ctx, cluster.ID, workflowId, domain.ClusterStatus_INSTALLING); err != nil { return errors.Wrap(err, "Failed to initialize status") } @@ -375,7 +375,7 @@ func (u *ClusterUsecase) Install(ctx context.Context, clusterId domain.ClusterId } func (u *ClusterUsecase) Get(ctx context.Context, clusterId domain.ClusterId) (out model.Cluster, err error) { - cluster, err := u.repo.Get(clusterId) + cluster, err := u.repo.Get(ctx, clusterId) if err != nil { return model.Cluster{}, err } @@ -384,7 +384,7 @@ func (u *ClusterUsecase) Get(ctx context.Context, clusterId domain.ClusterId) (o } func (u *ClusterUsecase) Delete(ctx context.Context, clusterId domain.ClusterId) (err error) { - cluster, err := u.repo.Get(clusterId) + cluster, err := u.repo.Get(ctx, clusterId) if err != nil { return httpErrors.NewNotFoundError(err, "", "") } @@ -393,7 +393,7 @@ func (u *ClusterUsecase) Delete(ctx context.Context, clusterId domain.ClusterId) return fmt.Errorf("The cluster can not be deleted. cluster status : %s", cluster.Status) } - resAppGroups, err := u.appGroupRepo.Fetch(clusterId, nil) + resAppGroups, err := u.appGroupRepo.Fetch(ctx, clusterId, nil) if err != nil { return errors.Wrap(err, "Failed to get appgroup") } @@ -408,7 +408,7 @@ func (u *ClusterUsecase) Delete(ctx context.Context, clusterId domain.ClusterId) // check cloudAccount tksCloudAccountId := "NULL" if cluster.CloudService != domain.CloudService_BYOH { - cloudAccount, err := u.cloudAccountRepo.Get(cluster.CloudAccount.ID) + cloudAccount, err := u.cloudAccountRepo.Get(ctx, cluster.CloudAccount.ID) if err != nil { return httpErrors.NewInternalServerError(fmt.Errorf("Failed to get cloudAccount"), "", "") } @@ -437,7 +437,7 @@ func (u *ClusterUsecase) Delete(ctx context.Context, clusterId domain.ClusterId) log.DebugWithContext(ctx, "submited workflow name : ", workflowId) - if err := u.repo.InitWorkflow(clusterId, workflowId, domain.ClusterStatus_DELETING); err != nil { + if err := u.repo.InitWorkflow(ctx, clusterId, workflowId, domain.ClusterStatus_DELETING); err != nil { return errors.Wrap(err, "Failed to initialize status") } @@ -445,7 +445,7 @@ func (u *ClusterUsecase) Delete(ctx context.Context, clusterId domain.ClusterId) } func (u *ClusterUsecase) GetClusterSiteValues(ctx context.Context, clusterId domain.ClusterId) (out domain.ClusterSiteValuesResponse, err error) { - cluster, err := u.repo.Get(clusterId) + cluster, err := u.repo.Get(ctx, clusterId) if err != nil { return domain.ClusterSiteValuesResponse{}, errors.Wrap(err, "Failed to get cluster") } @@ -483,7 +483,7 @@ func (u *ClusterUsecase) GetClusterSiteValues(ctx context.Context, clusterId dom } func (u *ClusterUsecase) CreateBootstrapKubeconfig(ctx context.Context, clusterId domain.ClusterId) (out domain.BootstrapKubeconfig, err error) { - _, err = u.repo.Get(clusterId) + _, err = u.repo.Get(ctx, clusterId) if err != nil { return out, httpErrors.NewNotFoundError(err, "", "") } @@ -528,7 +528,7 @@ func (u *ClusterUsecase) CreateBootstrapKubeconfig(ctx context.Context, clusterI } func (u *ClusterUsecase) GetBootstrapKubeconfig(ctx context.Context, clusterId domain.ClusterId) (out domain.BootstrapKubeconfig, err error) { - cluster, err := u.repo.Get(clusterId) + cluster, err := u.repo.Get(ctx, clusterId) if err != nil { return out, httpErrors.NewNotFoundError(err, "", "") } @@ -599,7 +599,7 @@ func (u *ClusterUsecase) GetBootstrapKubeconfig(ctx context.Context, clusterId d } func (u *ClusterUsecase) GetNodes(ctx context.Context, clusterId domain.ClusterId) (out []domain.ClusterNode, err error) { - cluster, err := u.repo.Get(clusterId) + cluster, err := u.repo.Get(ctx, clusterId) if err != nil { if errors.Is(err, gorm.ErrRecordNotFound) { return out, httpErrors.NewNotFoundError(err, "S_FAILED_FETCH_CLUSTER", "") diff --git a/internal/usecase/dashboard.go b/internal/usecase/dashboard.go index a4f271a8..99ce9329 100644 --- a/internal/usecase/dashboard.go +++ b/internal/usecase/dashboard.go @@ -51,7 +51,7 @@ func NewDashboardUsecase(r repository.Repository, cache *gcache.Cache) IDashboar } func (u *DashboardUsecase) GetCharts(ctx context.Context, organizationId string, chartType domain.ChartType, duration string, interval string, year string, month string) (out []domain.DashboardChart, err error) { - _, err = u.organizationRepo.Get(organizationId) + _, err = u.organizationRepo.Get(ctx, organizationId) if err != nil { return nil, errors.Wrap(err, "invalid organization") } @@ -61,7 +61,7 @@ func (u *DashboardUsecase) GetCharts(ctx context.Context, organizationId string, continue } - chart, err := u.getChartFromPrometheus(organizationId, strType, duration, interval, year, month) + chart, err := u.getChartFromPrometheus(ctx, organizationId, strType, duration, interval, year, month) if err != nil { return nil, err } @@ -73,12 +73,12 @@ func (u *DashboardUsecase) GetCharts(ctx context.Context, organizationId string, } func (u *DashboardUsecase) GetStacks(ctx context.Context, organizationId string) (out []domain.DashboardStack, err error) { - clusters, err := u.clusterRepo.FetchByOrganizationId(organizationId, uuid.Nil, nil) + clusters, err := u.clusterRepo.FetchByOrganizationId(ctx, organizationId, uuid.Nil, nil) if err != nil { return out, err } - thanosUrl, err := u.getThanosUrl(organizationId) + thanosUrl, err := u.getThanosUrl(ctx, organizationId) if err != nil { log.ErrorWithContext(ctx, err) return out, httpErrors.NewInternalServerError(err, "D_INVALID_PRIMARY_STACK", "") @@ -99,7 +99,7 @@ func (u *DashboardUsecase) GetStacks(ctx context.Context, organizationId string) } for _, cluster := range clusters { - appGroups, err := u.appGroupRepo.Fetch(cluster.ID, nil) + appGroups, err := u.appGroupRepo.Fetch(ctx, cluster.ID, nil) if err != nil { return nil, err } @@ -137,7 +137,7 @@ func (u *DashboardUsecase) GetStacks(ctx context.Context, organizationId string) } func (u *DashboardUsecase) GetResources(ctx context.Context, organizationId string) (out domain.DashboardResource, err error) { - thanosUrl, err := u.getThanosUrl(organizationId) + thanosUrl, err := u.getThanosUrl(ctx, organizationId) if err != nil { log.ErrorWithContext(ctx, err) return out, httpErrors.NewInternalServerError(err, "D_INVALID_PRIMARY_STACK", "") @@ -149,7 +149,7 @@ func (u *DashboardUsecase) GetResources(ctx context.Context, organizationId stri } // Stack - clusters, err := u.clusterRepo.FetchByOrganizationId(organizationId, uuid.Nil, nil) + clusters, err := u.clusterRepo.FetchByOrganizationId(ctx, organizationId, uuid.Nil, nil) if err != nil { return out, err } @@ -222,8 +222,8 @@ func (u *DashboardUsecase) GetResources(ctx context.Context, organizationId stri return } -func (u *DashboardUsecase) getChartFromPrometheus(organizationId string, chartType string, duration string, interval string, year string, month string) (res domain.DashboardChart, err error) { - thanosUrl, err := u.getThanosUrl(organizationId) +func (u *DashboardUsecase) getChartFromPrometheus(ctx context.Context, organizationId string, chartType string, duration string, interval string, year string, month string) (res domain.DashboardChart, err error) { + thanosUrl, err := u.getThanosUrl(ctx, organizationId) if err != nil { log.Error(err) return res, httpErrors.NewInternalServerError(err, "D_INVALID_PRIMARY_STACK", "") @@ -286,12 +286,12 @@ func (u *DashboardUsecase) getChartFromPrometheus(organizationId string, chartTy return res, fmt.Errorf("Invalid month") } - alerts, err := u.alertRepo.FetchPodRestart(organizationId, startDate, endDate) + alerts, err := u.alertRepo.FetchPodRestart(ctx, organizationId, startDate, endDate) if err != nil { return res, err } - organization, err := u.organizationRepo.Get(organizationId) + organization, err := u.organizationRepo.Get(ctx, organizationId) if err != nil { return res, err } @@ -375,7 +375,7 @@ func (u *DashboardUsecase) getChartFromPrometheus(organizationId string, chartTy yAxisData = append(yAxisData, u.getChartYValue(val.Values, xAxis, percentage)) } - clusterName, err := u.getClusterNameFromId(val.Metric.TacoCluster) + clusterName, err := u.getClusterNameFromId(ctx, val.Metric.TacoCluster) if err != nil { clusterName = val.Metric.TacoCluster } @@ -402,14 +402,14 @@ func (u *DashboardUsecase) getChartFromPrometheus(organizationId string, chartTy } -func (u *DashboardUsecase) getThanosUrl(organizationId string) (out string, err error) { +func (u *DashboardUsecase) getThanosUrl(ctx context.Context, organizationId string) (out string, err error) { const prefix = "CACHE_KEY_THANOS_URL" value, found := u.cache.Get(prefix + organizationId) if found { return value.(string), nil } - organization, err := u.organizationRepo.Get(organizationId) + organization, err := u.organizationRepo.Get(ctx, organizationId) if err != nil { return out, errors.Wrap(err, "Failed to get organization") } @@ -530,14 +530,14 @@ func (u *DashboardUsecase) getStackCpu(result []thanos.MetricDataResult, cluster return } -func (u *DashboardUsecase) getClusterNameFromId(clusterId string) (clusterName string, err error) { +func (u *DashboardUsecase) getClusterNameFromId(ctx context.Context, clusterId string) (clusterName string, err error) { const prefix = "CACHE_KEY_CLUSTER_NAME_FROM_ID" value, found := u.cache.Get(prefix + clusterId) if found { return value.(string), nil } - cluster, err := u.clusterRepo.Get(domain.ClusterId(clusterId)) + cluster, err := u.clusterRepo.Get(ctx, domain.ClusterId(clusterId)) if err != nil { return clusterName, errors.Wrap(err, "Failed to get cluster") } diff --git a/internal/usecase/organization.go b/internal/usecase/organization.go index 7dafe447..67fa317a 100644 --- a/internal/usecase/organization.go +++ b/internal/usecase/organization.go @@ -22,12 +22,12 @@ import ( type IOrganizationUsecase interface { 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) - ChangeAdminId(organizationId string, adminId uuid.UUID) error - Delete(organizationId string, accessToken string) error + Fetch(ctx context.Context, pg *pagination.Pagination) (*[]model.Organization, error) + Get(ctx context.Context, organizationId string) (model.Organization, error) + Update(ctx context.Context, organizationId string, in domain.UpdateOrganizationRequest) (model.Organization, error) + UpdatePrimaryClusterId(ctx context.Context, organizationId string, clusterId string) (err error) + ChangeAdminId(ctx context.Context, organizationId string, adminId uuid.UUID) error + Delete(ctx context.Context, organizationId string, accessToken string) error } type OrganizationUsecase struct { @@ -63,7 +63,7 @@ func (u *OrganizationUsecase) Create(ctx context.Context, in *model.Organization in.ID = organizationId // Create organization in DB - _, err = u.repo.Create(in) + _, err = u.repo.Create(ctx, in) if err != nil { return "", err } @@ -83,26 +83,26 @@ func (u *OrganizationUsecase) Create(ctx context.Context, in *model.Organization } log.InfoWithContext(ctx, "submited workflow :", workflowId) - if err := u.repo.InitWorkflow(organizationId, workflowId, domain.OrganizationStatus_CREATING); err != nil { + if err := u.repo.InitWorkflow(ctx, organizationId, workflowId, domain.OrganizationStatus_CREATING); err != nil { return "", errors.Wrap(err, "Failed to init workflow") } return organizationId, nil } -func (u *OrganizationUsecase) Fetch(pg *pagination.Pagination) (out *[]model.Organization, err error) { - organizations, err := u.repo.Fetch(pg) +func (u *OrganizationUsecase) Fetch(ctx context.Context, pg *pagination.Pagination) (out *[]model.Organization, err error) { + organizations, err := u.repo.Fetch(ctx, pg) if err != nil { return nil, err } return organizations, nil } -func (u *OrganizationUsecase) Get(organizationId string) (out model.Organization, err error) { - out, err = u.repo.Get(organizationId) +func (u *OrganizationUsecase) Get(ctx context.Context, organizationId string) (out model.Organization, err error) { + out, err = u.repo.Get(ctx, organizationId) if err != nil { return model.Organization{}, httpErrors.NewNotFoundError(err, "", "") } - clusters, err := u.clusterRepo.FetchByOrganizationId(organizationId, uuid.Nil, nil) + clusters, err := u.clusterRepo.FetchByOrganizationId(ctx, organizationId, uuid.Nil, nil) if err != nil { log.Info(err) out.ClusterCount = 0 @@ -112,8 +112,8 @@ func (u *OrganizationUsecase) Get(organizationId string) (out model.Organization } -func (u *OrganizationUsecase) Delete(organizationId string, accessToken string) (err error) { - _, err = u.Get(organizationId) +func (u *OrganizationUsecase) Delete(ctx context.Context, organizationId string, accessToken string) (err error) { + _, err = u.Get(ctx, organizationId) if err != nil { return err } @@ -124,18 +124,18 @@ func (u *OrganizationUsecase) Delete(organizationId string, accessToken string) } // delete roles in DB - roles, err := u.roleRepo.ListTksRoles(organizationId, nil) + roles, err := u.roleRepo.ListTksRoles(ctx, organizationId, nil) if err != nil { return err } for _, role := range roles { - if err := u.roleRepo.Delete(role.ID); err != nil { + if err := u.roleRepo.Delete(ctx, role.ID); err != nil { return err } } // delete organization in DB - err = u.repo.Delete(organizationId) + err = u.repo.Delete(ctx, organizationId) if err != nil { return err } @@ -143,13 +143,13 @@ func (u *OrganizationUsecase) Delete(organizationId string, accessToken string) return nil } -func (u *OrganizationUsecase) Update(organizationId string, in domain.UpdateOrganizationRequest) (model.Organization, error) { - _, err := u.Get(organizationId) +func (u *OrganizationUsecase) Update(ctx context.Context, organizationId string, in domain.UpdateOrganizationRequest) (model.Organization, error) { + _, err := u.Get(ctx, organizationId) if err != nil { return model.Organization{}, httpErrors.NewNotFoundError(err, "", "") } - res, err := u.repo.Update(organizationId, in) + res, err := u.repo.Update(ctx, organizationId, in) if err != nil { return model.Organization{}, err } @@ -157,30 +157,30 @@ func (u *OrganizationUsecase) Update(organizationId string, in domain.UpdateOrga return res, nil } -func (u *OrganizationUsecase) UpdatePrimaryClusterId(organizationId string, clusterId string) (err error) { +func (u *OrganizationUsecase) UpdatePrimaryClusterId(ctx context.Context, organizationId string, clusterId string) (err error) { if clusterId != "" && !helper.ValidateClusterId(clusterId) { return httpErrors.NewBadRequestError(fmt.Errorf("Invalid clusterId"), "", "") } - _, err = u.Get(organizationId) + _, err = u.Get(ctx, organizationId) if err != nil { return httpErrors.NewNotFoundError(err, "", "") } - err = u.repo.UpdatePrimaryClusterId(organizationId, clusterId) + err = u.repo.UpdatePrimaryClusterId(ctx, organizationId, clusterId) if err != nil { return err } return nil } -func (u *OrganizationUsecase) ChangeAdminId(organizationId string, adminId uuid.UUID) error { - _, err := u.Get(organizationId) +func (u *OrganizationUsecase) ChangeAdminId(ctx context.Context, organizationId string, adminId uuid.UUID) error { + _, err := u.Get(ctx, organizationId) if err != nil { return httpErrors.NewNotFoundError(err, "", "") } - err = u.repo.UpdateAdminId(organizationId, adminId) + err = u.repo.UpdateAdminId(ctx, organizationId, adminId) if err != nil { return err } diff --git a/internal/usecase/permission.go b/internal/usecase/permission.go index bcce7e95..32b6bf0d 100644 --- a/internal/usecase/permission.go +++ b/internal/usecase/permission.go @@ -1,22 +1,20 @@ package usecase import ( + "context" "github.com/google/uuid" "github.com/openinfradev/tks-api/internal/model" "github.com/openinfradev/tks-api/internal/repository" ) type IPermissionUsecase interface { - 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 *model.Permission) error - SetRoleIdToPermissionSet(roleId string, permissionSet *model.PermissionSet) - GetAllowedPermissionSet() *model.PermissionSet - GetUserPermissionSet() *model.PermissionSet - UpdatePermission(permission *model.Permission) error + CreatePermissionSet(ctx context.Context, permissionSet *model.PermissionSet) error + GetPermissionSetByRoleId(ctx context.Context, roleId string) (*model.PermissionSet, error) + ListPermissions(ctx context.Context, roleId string) ([]*model.Permission, error) + SetRoleIdToPermissionSet(ctx context.Context, roleId string, permissionSet *model.PermissionSet) + GetAllowedPermissionSet(ctx context.Context) *model.PermissionSet + GetUserPermissionSet(ctx context.Context) *model.PermissionSet + UpdatePermission(ctx context.Context, permission *model.Permission) error } type PermissionUsecase struct { @@ -29,30 +27,30 @@ func NewPermissionUsecase(repo repository.Repository) *PermissionUsecase { } } -func (p PermissionUsecase) CreatePermissionSet(permissionSet *model.PermissionSet) error { +func (p PermissionUsecase) CreatePermissionSet(ctx context.Context, permissionSet *model.PermissionSet) error { var err error - if err = p.repo.Create(permissionSet.Dashboard); err != nil { + if err = p.repo.Create(ctx, permissionSet.Dashboard); err != nil { return err } - if err = p.repo.Create(permissionSet.Stack); err != nil { + if err = p.repo.Create(ctx, permissionSet.Stack); err != nil { return err } - if err = p.repo.Create(permissionSet.SecurityPolicy); err != nil { + if err = p.repo.Create(ctx, permissionSet.SecurityPolicy); err != nil { return err } - if err = p.repo.Create(permissionSet.ProjectManagement); err != nil { + if err = p.repo.Create(ctx, permissionSet.ProjectManagement); err != nil { return err } - if err = p.repo.Create(permissionSet.Notification); err != nil { + if err = p.repo.Create(ctx, permissionSet.Notification); err != nil { return err } - if err = p.repo.Create(permissionSet.Configuration); err != nil { + if err = p.repo.Create(ctx, permissionSet.Configuration); err != nil { return err } return nil } -func (p PermissionUsecase) GetPermissionSetByRoleId(roleId string) (*model.PermissionSet, error) { +func (p PermissionUsecase) GetPermissionSetByRoleId(ctx context.Context, roleId string) (*model.PermissionSet, error) { permissionSet := &model.PermissionSet{ Dashboard: nil, Stack: nil, @@ -62,7 +60,7 @@ func (p PermissionUsecase) GetPermissionSetByRoleId(roleId string) (*model.Permi Configuration: nil, } - permissionList, err := p.repo.List(roleId) + permissionList, err := p.repo.List(ctx, roleId) if err != nil { return nil, err } @@ -86,33 +84,33 @@ func (p PermissionUsecase) GetPermissionSetByRoleId(roleId string) (*model.Permi return permissionSet, nil } -func (p PermissionUsecase) ListPermissions(roleId string) ([]*model.Permission, error) { - return p.repo.List(roleId) +func (p PermissionUsecase) ListPermissions(ctx context.Context, roleId string) ([]*model.Permission, error) { + return p.repo.List(ctx, roleId) } -func (p PermissionUsecase) GetPermission(id uuid.UUID) (*model.Permission, error) { - return p.repo.Get(id) +func (p PermissionUsecase) GetPermission(ctx context.Context, id uuid.UUID) (*model.Permission, error) { + return p.repo.Get(ctx, id) } -func (p PermissionUsecase) DeletePermission(id uuid.UUID) error { - return p.repo.Delete(id) +func (p PermissionUsecase) DeletePermission(ctx context.Context, id uuid.UUID) error { + return p.repo.Delete(ctx, id) } -func (p PermissionUsecase) UpdatePermission(permission *model.Permission) error { - return p.repo.Update(permission) +func (p PermissionUsecase) UpdatePermission(ctx context.Context, permission *model.Permission) error { + return p.repo.Update(ctx, permission) } -func (p PermissionUsecase) SetRoleIdToPermissionSet(roleId string, permissionSet *model.PermissionSet) { +func (p PermissionUsecase) SetRoleIdToPermissionSet(ctx context.Context, roleId string, permissionSet *model.PermissionSet) { permissionSet.SetRoleId(roleId) } -func (p PermissionUsecase) GetAllowedPermissionSet() *model.PermissionSet { +func (p PermissionUsecase) GetAllowedPermissionSet(ctx context.Context) *model.PermissionSet { permissionSet := model.NewDefaultPermissionSet() permissionSet.SetAllowedPermissionSet() return permissionSet } -func (p PermissionUsecase) GetUserPermissionSet() *model.PermissionSet { +func (p PermissionUsecase) GetUserPermissionSet(ctx context.Context) *model.PermissionSet { permissionSet := model.NewDefaultPermissionSet() permissionSet.SetUserPermissionSet() return permissionSet diff --git a/internal/usecase/project.go b/internal/usecase/project.go index 756692a9..8422338a 100644 --- a/internal/usecase/project.go +++ b/internal/usecase/project.go @@ -87,7 +87,7 @@ func NewProjectUsecase(r repository.Repository, kc keycloak.IKeycloak, argoClien } func (u *ProjectUsecase) CreateProject(ctx context.Context, p *model.Project) (string, error) { - projectId, err := u.projectRepo.CreateProject(p) + projectId, err := u.projectRepo.CreateProject(ctx, p) if err != nil { log.ErrorWithContext(ctx, err) return "", errors.Wrap(err, "Failed to create project.") @@ -98,7 +98,7 @@ func (u *ProjectUsecase) CreateProject(ctx context.Context, p *model.Project) (s func (u *ProjectUsecase) GetProjects(ctx context.Context, organizationId string, userId string, onlyMyProject bool, pg *pagination.Pagination) (pr []domain.ProjectResponse, err error) { if userId == "" { - pr, err = u.projectRepo.GetAllProjects(organizationId, pg) + pr, err = u.projectRepo.GetAllProjects(ctx, organizationId, pg) } else { userUuid, err := uuid.Parse(userId) if err != nil { @@ -106,9 +106,9 @@ func (u *ProjectUsecase) GetProjects(ctx context.Context, organizationId string, return nil, errors.Wrap(err, "Failed to parse uuid to string") } if onlyMyProject == false { - pr, err = u.projectRepo.GetProjects(organizationId, userUuid, pg) + pr, err = u.projectRepo.GetProjects(ctx, organizationId, userUuid, pg) } else { - pr, err = u.projectRepo.GetProjectsByUserId(organizationId, userUuid, pg) + pr, err = u.projectRepo.GetProjectsByUserId(ctx, organizationId, userUuid, pg) } } if err != nil { @@ -120,7 +120,7 @@ func (u *ProjectUsecase) GetProjects(ctx context.Context, organizationId string, } func (u *ProjectUsecase) GetProject(ctx context.Context, organizationId string, projectId string) (*model.Project, error) { - p, err := u.projectRepo.GetProjectById(organizationId, projectId) + p, err := u.projectRepo.GetProjectById(ctx, organizationId, projectId) if err != nil { log.ErrorWithContext(ctx, err) return nil, errors.Wrap(err, "Failed to get projects.") @@ -129,7 +129,7 @@ func (u *ProjectUsecase) GetProject(ctx context.Context, organizationId string, } func (u *ProjectUsecase) GetProjectWithLeader(ctx context.Context, organizationId string, projectId string) (*model.Project, error) { - p, err := u.projectRepo.GetProjectByIdAndLeader(organizationId, projectId) + p, err := u.projectRepo.GetProjectByIdAndLeader(ctx, organizationId, projectId) if err != nil { log.ErrorWithContext(ctx, err) return nil, errors.Wrap(err, "Failed to get projects.") @@ -139,7 +139,7 @@ func (u *ProjectUsecase) GetProjectWithLeader(ctx context.Context, organizationI func (u *ProjectUsecase) IsProjectNameExist(ctx context.Context, organizationId string, projectName string) (bool, error) { exist := true - p, err := u.projectRepo.GetProjectByName(organizationId, projectName) + p, err := u.projectRepo.GetProjectByName(ctx, organizationId, projectName) if err != nil { log.ErrorWithContext(ctx, err) exist = false @@ -162,7 +162,7 @@ func (u *ProjectUsecase) UpdateProject(ctx context.Context, p *model.Project, ne p.ProjectNamespaces = nil p.ProjectMembers = nil - if err := u.projectRepo.UpdateProject(p); err != nil { + if err := u.projectRepo.UpdateProject(ctx, p); err != nil { log.ErrorWithContext(ctx, err) return errors.Wrap(err, "Failed to update project.") } @@ -181,7 +181,7 @@ func (u *ProjectUsecase) UpdateProject(ctx context.Context, p *model.Project, ne return errors.Wrap(err, "No userid") } - pm, err := u.projectRepo.GetProjectMemberByUserId(p.ID, newLeaderId) + pm, err := u.projectRepo.GetProjectMemberByUserId(ctx, p.ID, newLeaderId) if err != nil { return err } @@ -218,7 +218,7 @@ func (u *ProjectUsecase) UpdateProject(ctx context.Context, p *model.Project, ne } func (u *ProjectUsecase) GetProjectRole(ctx context.Context, id string) (*model.ProjectRole, error) { - pr, err := u.projectRepo.GetProjectRoleById(id) + pr, err := u.projectRepo.GetProjectRoleById(ctx, id) if err != nil { log.ErrorWithContext(ctx, err) return nil, errors.Wrap(err, "Failed to get project roles.") @@ -231,13 +231,13 @@ func (u *ProjectUsecase) GetProjectRoles(ctx context.Context, query int) (prs [] var pr *model.ProjectRole if query == ProjectLeader { - pr, err = u.projectRepo.GetProjectRoleByName("project-leader") + pr, err = u.projectRepo.GetProjectRoleByName(ctx, "project-leader") } else if query == ProjectMember { - pr, err = u.projectRepo.GetProjectRoleByName("project-member") + pr, err = u.projectRepo.GetProjectRoleByName(ctx, "project-member") } else if query == ProjectViewer { - pr, err = u.projectRepo.GetProjectRoleByName("project-viewer") + pr, err = u.projectRepo.GetProjectRoleByName(ctx, "project-viewer") } else { - prs, err = u.projectRepo.GetAllProjectRoles() + prs, err = u.projectRepo.GetAllProjectRoles(ctx) } if err != nil { log.ErrorWithContext(ctx, err) @@ -252,7 +252,7 @@ func (u *ProjectUsecase) GetProjectRoles(ctx context.Context, query int) (prs [] } func (u *ProjectUsecase) AddProjectMember(ctx context.Context, pm *model.ProjectMember) (string, error) { - projectMemberId, err := u.projectRepo.AddProjectMember(pm) + projectMemberId, err := u.projectRepo.AddProjectMember(ctx, pm) if err != nil { log.ErrorWithContext(ctx, err) return "", errors.Wrap(err, "Failed to add project member to project.") @@ -268,7 +268,7 @@ func (u *ProjectUsecase) GetProjectUser(ctx context.Context, projectUserId strin return nil, errors.Wrap(err, "Failed to parse uuid to string") } - user, err := u.userRepository.GetByUuid(uid) + user, err := u.userRepository.GetByUuid(ctx, uid) if err != nil { log.ErrorWithContext(ctx, err) return nil, errors.Wrap(err, "Failed to retrieve user by id") @@ -282,7 +282,7 @@ func (u *ProjectUsecase) GetProjectUser(ctx context.Context, projectUserId strin } func (u *ProjectUsecase) GetProjectMember(ctx context.Context, projectMemberId string) (pm *model.ProjectMember, err error) { - pm, err = u.projectRepo.GetProjectMemberById(projectMemberId) + pm, err = u.projectRepo.GetProjectMemberById(ctx, projectMemberId) if err != nil { log.ErrorWithContext(ctx, err) return pm, errors.Wrap(err, "Failed to get project member.") @@ -293,13 +293,13 @@ func (u *ProjectUsecase) GetProjectMember(ctx context.Context, projectMemberId s func (u *ProjectUsecase) GetProjectMembers(ctx context.Context, projectId string, query int, pg *pagination.Pagination) (pms []model.ProjectMember, err error) { if query == ProjectLeader { - pms, err = u.projectRepo.GetProjectMembersByProjectIdAndRoleName(projectId, "project-leader", pg) + pms, err = u.projectRepo.GetProjectMembersByProjectIdAndRoleName(ctx, projectId, "project-leader", pg) } else if query == ProjectMember { - pms, err = u.projectRepo.GetProjectMembersByProjectIdAndRoleName(projectId, "project-member", pg) + pms, err = u.projectRepo.GetProjectMembersByProjectIdAndRoleName(ctx, projectId, "project-member", pg) } else if query == ProjectViewer { - pms, err = u.projectRepo.GetProjectMembersByProjectIdAndRoleName(projectId, "project-viewer", pg) + pms, err = u.projectRepo.GetProjectMembersByProjectIdAndRoleName(ctx, projectId, "project-viewer", pg) } else { - pms, err = u.projectRepo.GetProjectMembersByProjectId(projectId, pg) + pms, err = u.projectRepo.GetProjectMembersByProjectId(ctx, projectId, pg) } if err != nil { log.ErrorWithContext(ctx, err) @@ -310,7 +310,7 @@ func (u *ProjectUsecase) GetProjectMembers(ctx context.Context, projectId string } func (u *ProjectUsecase) GetProjectMemberCount(ctx context.Context, projectMemberId string) (pmcr *domain.GetProjectMemberCountResponse, err error) { - pmcr, err = u.projectRepo.GetProjectMemberCountByProjectId(projectMemberId) + pmcr, err = u.projectRepo.GetProjectMemberCountByProjectId(ctx, projectMemberId) if err != nil { log.ErrorWithContext(ctx, err) return pmcr, errors.Wrap(err, "Failed to get project member count.") @@ -320,7 +320,7 @@ func (u *ProjectUsecase) GetProjectMemberCount(ctx context.Context, projectMembe } func (u *ProjectUsecase) RemoveProjectMember(ctx context.Context, projectMemberId string) error { - if err := u.projectRepo.RemoveProjectMember(projectMemberId); err != nil { + if err := u.projectRepo.RemoveProjectMember(ctx, projectMemberId); err != nil { log.ErrorWithContext(ctx, err) return errors.Wrap(err, "Failed to remove project member to project.") } @@ -329,7 +329,7 @@ func (u *ProjectUsecase) RemoveProjectMember(ctx context.Context, projectMemberI func (u *ProjectUsecase) UpdateProjectMemberRole(ctx context.Context, pm *model.ProjectMember) error { - if err := u.projectRepo.UpdateProjectMemberRole(pm); err != nil { + if err := u.projectRepo.UpdateProjectMemberRole(ctx, pm); err != nil { log.ErrorWithContext(ctx, err) return errors.Wrap(err, "Failed to remove project member to project.") } @@ -337,7 +337,7 @@ func (u *ProjectUsecase) UpdateProjectMemberRole(ctx context.Context, pm *model. } func (u *ProjectUsecase) CreateProjectNamespace(ctx context.Context, organizationId string, pn *model.ProjectNamespace) error { - if err := u.projectRepo.CreateProjectNamespace(organizationId, pn); err != nil { + if err := u.projectRepo.CreateProjectNamespace(ctx, organizationId, pn); err != nil { log.ErrorWithContext(ctx, err) return errors.Wrap(err, "Failed to create project namespace.") } @@ -346,7 +346,7 @@ func (u *ProjectUsecase) CreateProjectNamespace(ctx context.Context, organizatio func (u *ProjectUsecase) IsProjectNamespaceExist(ctx context.Context, organizationId string, projectId string, stackId string, projectNamespace string) (bool, error) { exist := true - pn, err := u.projectRepo.GetProjectNamespaceByName(organizationId, projectId, stackId, projectNamespace) + pn, err := u.projectRepo.GetProjectNamespaceByName(ctx, organizationId, projectId, stackId, projectNamespace) if err != nil { log.ErrorWithContext(ctx, err) exist = false @@ -359,7 +359,7 @@ func (u *ProjectUsecase) IsProjectNamespaceExist(ctx context.Context, organizati } func (u *ProjectUsecase) GetProjectNamespaces(ctx context.Context, organizationId string, projectId string, pg *pagination.Pagination) ([]model.ProjectNamespace, error) { - pns, err := u.projectRepo.GetProjectNamespaces(organizationId, projectId, pg) + pns, err := u.projectRepo.GetProjectNamespaces(ctx, organizationId, projectId, pg) if err != nil { log.ErrorWithContext(ctx, err) return nil, errors.Wrap(err, "Failed to retrieve project namespaces.") @@ -369,7 +369,7 @@ func (u *ProjectUsecase) GetProjectNamespaces(ctx context.Context, organizationI } func (u *ProjectUsecase) GetProjectNamespace(ctx context.Context, organizationId string, projectId string, projectNamespace string, stackId string) (*model.ProjectNamespace, error) { - pn, err := u.projectRepo.GetProjectNamespaceByPrimaryKey(organizationId, projectId, projectNamespace, stackId) + pn, err := u.projectRepo.GetProjectNamespaceByPrimaryKey(ctx, organizationId, projectId, projectNamespace, stackId) if err != nil { log.ErrorWithContext(ctx, err) return nil, errors.Wrap(err, "Failed to retrieve project namespace.") @@ -379,7 +379,7 @@ func (u *ProjectUsecase) GetProjectNamespace(ctx context.Context, organizationId } func (u *ProjectUsecase) UpdateProjectNamespace(ctx context.Context, pn *model.ProjectNamespace) error { - if err := u.projectRepo.UpdateProjectNamespace(pn); err != nil { + if err := u.projectRepo.UpdateProjectNamespace(ctx, pn); err != nil { log.ErrorWithContext(ctx, err) return errors.Wrap(err, "Failed to update project namespace") } @@ -388,7 +388,7 @@ func (u *ProjectUsecase) UpdateProjectNamespace(ctx context.Context, pn *model.P func (u *ProjectUsecase) DeleteProjectNamespace(ctx context.Context, organizationId string, projectId string, stackId string, projectNamespace string) error { - if err := u.projectRepo.DeleteProjectNamespace(organizationId, projectId, projectNamespace, stackId); err != nil { + if err := u.projectRepo.DeleteProjectNamespace(ctx, organizationId, projectId, projectNamespace, stackId); err != nil { log.ErrorWithContext(ctx, err) return errors.Wrap(err, "Failed to delete project namespace.") } @@ -397,9 +397,9 @@ func (u *ProjectUsecase) DeleteProjectNamespace(ctx context.Context, organizatio func (u *ProjectUsecase) GetAppCount(ctx context.Context, organizationId string, projectId string, namespace string) (appCount int, err error) { if namespace == "" { - appCount, err = u.projectRepo.GetAppCountByProjectId(organizationId, projectId) + appCount, err = u.projectRepo.GetAppCountByProjectId(ctx, organizationId, projectId) } else { - appCount, err = u.projectRepo.GetAppCountByNamespace(organizationId, projectId, namespace) + appCount, err = u.projectRepo.GetAppCountByNamespace(ctx, organizationId, projectId, namespace) } if err != nil { log.ErrorWithContext(ctx, err) @@ -410,7 +410,7 @@ func (u *ProjectUsecase) GetAppCount(ctx context.Context, organizationId string, } func (u *ProjectUsecase) EnsureRequiredSetupForCluster(ctx context.Context, organizationId string, projectId string, stackId string) error { - pns, err := u.projectRepo.GetProjectNamespaces(organizationId, projectId, nil) + pns, err := u.projectRepo.GetProjectNamespaces(ctx, organizationId, projectId, nil) if err != nil { log.ErrorWithContext(ctx, err) return errors.Wrap(err, "Failed to create project namespace.") @@ -455,7 +455,7 @@ func (u *ProjectUsecase) EnsureRequiredSetupForCluster(ctx context.Context, orga return nil } func (u *ProjectUsecase) MayRemoveRequiredSetupForCluster(ctx context.Context, organizationId string, projectId string, stackId string) error { - pns, err := u.projectRepo.GetProjectNamespaces(organizationId, projectId, nil) + pns, err := u.projectRepo.GetProjectNamespaces(ctx, organizationId, projectId, nil) if err != nil { log.ErrorWithContext(ctx, err) return errors.Wrap(err, "Failed to create project namespace.") @@ -652,7 +652,7 @@ func (u *ProjectUsecase) unassignKeycloakClientRoleToMember(ctx context.Context, } func (u *ProjectUsecase) GetProjectKubeconfig(ctx context.Context, organizationId string, projectId string) (string, error) { - projectNamespaces, err := u.projectRepo.GetProjectNamespaces(organizationId, projectId, nil) + projectNamespaces, err := u.projectRepo.GetProjectNamespaces(ctx, organizationId, projectId, nil) if err != nil { log.ErrorWithContext(ctx, err) return "", errors.Wrap(err, "Failed to retrieve project namespaces.") @@ -709,7 +709,7 @@ func (u *ProjectUsecase) GetProjectKubeconfig(ctx context.Context, organizationI } func (u *ProjectUsecase) GetK8sResources(ctx context.Context, organizationId string, projectId string, namespace string, stackId domain.StackId) (out domain.ProjectNamespaceK8sResources, err error) { - _, err = u.clusterRepository.Get(domain.ClusterId(stackId)) + _, err = u.clusterRepository.Get(ctx, domain.ClusterId(stackId)) if err != nil { return out, errors.Wrap(err, fmt.Sprintf("Failed to get cluster : stackId %s", stackId)) } @@ -781,7 +781,7 @@ func (u *ProjectUsecase) GetK8sResources(ctx context.Context, organizationId str } func (u *ProjectUsecase) GetResourcesUsage(ctx context.Context, organizationId string, projectId string, namespace string, stackId domain.StackId) (out domain.ProjectNamespaceResourcesUsage, err error) { - _, err = u.clusterRepository.Get(domain.ClusterId(stackId)) + _, err = u.clusterRepository.Get(ctx, domain.ClusterId(stackId)) if err != nil { return out, errors.Wrap(err, fmt.Sprintf("Failed to get cluster : stackId %s", stackId)) } diff --git a/internal/usecase/role.go b/internal/usecase/role.go index bc5d3734..63121e04 100644 --- a/internal/usecase/role.go +++ b/internal/usecase/role.go @@ -2,17 +2,17 @@ package usecase import ( "github.com/openinfradev/tks-api/internal/model" + "context" "github.com/openinfradev/tks-api/internal/pagination" "github.com/openinfradev/tks-api/internal/repository" ) type IRoleUsecase interface { - 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 *model.Role) error + CreateTksRole(ctx context.Context, role *model.Role) (string, error) + ListTksRoles(ctx context.Context, organizationId string, pg *pagination.Pagination) ([]*model.Role, error) + GetTksRole(ctx context.Context, id string) (*model.Role, error) + DeleteTksRole(ctx context.Context, id string) error + UpdateTksRole(ctx context.Context, role *model.Role) error } type RoleUsecase struct { @@ -25,12 +25,12 @@ func NewRoleUsecase(repo repository.Repository) *RoleUsecase { } } -func (r RoleUsecase) CreateTksRole(role *model.Role) (string, error) { - return r.repo.Create(role) +func (r RoleUsecase) CreateTksRole(ctx context.Context, role *model.Role) (string, error) { + return r.repo.Create(ctx, role) } -func (r RoleUsecase) ListTksRoles(organizationId string, pg *pagination.Pagination) ([]*model.Role, error) { - roles, err := r.repo.ListTksRoles(organizationId, pg) +func (r RoleUsecase) ListTksRoles(ctx context.Context, organizationId string, pg *pagination.Pagination) ([]*model.Role, error) { + roles, err := r.repo.ListTksRoles(ctx, organizationId, pg) if err != nil { return nil, err } @@ -38,12 +38,8 @@ func (r RoleUsecase) ListTksRoles(organizationId string, pg *pagination.Paginati return roles, nil } -func (r RoleUsecase) ListRoles(pg *pagination.Pagination) ([]*model.Role, error) { - return r.repo.List(nil) -} - -func (r RoleUsecase) GetTksRole(id string) (*model.Role, error) { - role, err := r.repo.GetTksRole(id) +func (r RoleUsecase) GetTksRole(ctx context.Context, id string) (*model.Role, error) { + role, err := r.repo.GetTksRole(ctx, id) if err != nil { return nil, err } @@ -51,12 +47,12 @@ func (r RoleUsecase) GetTksRole(id string) (*model.Role, error) { return role, nil } -func (r RoleUsecase) DeleteTksRole(id string) error { - return r.repo.Delete(id) +func (r RoleUsecase) DeleteTksRole(ctx context.Context, id string) error { + return r.repo.Delete(ctx, id) } -func (r RoleUsecase) UpdateTksRole(role *model.Role) error { - err := r.repo.Update(role) +func (r RoleUsecase) UpdateTksRole(ctx context.Context, role *model.Role) error { + err := r.repo.Update(ctx, role) if err != nil { return err } diff --git a/internal/usecase/stack-template.go b/internal/usecase/stack-template.go index 58edef83..cfc042f9 100644 --- a/internal/usecase/stack-template.go +++ b/internal/usecase/stack-template.go @@ -66,7 +66,7 @@ func (u *StackTemplateUsecase) Create(ctx context.Context, dto model.StackTempla services = services + "]" dto.Services = []byte(services) - stackTemplateId, err = u.repo.Create(dto) + stackTemplateId, err = u.repo.Create(ctx, dto) if err != nil { return uuid.Nil, httpErrors.NewInternalServerError(err, "", "") } @@ -82,12 +82,12 @@ func (u *StackTemplateUsecase) Create(ctx context.Context, dto model.StackTempla } func (u *StackTemplateUsecase) Update(ctx context.Context, dto model.StackTemplate) error { - _, err := u.repo.Get(dto.ID) + _, err := u.repo.Get(ctx, dto.ID) if err != nil { return httpErrors.NewBadRequestError(err, "ST_NOT_EXISTED_STACK_TEMPLATE", "") } - err = u.repo.Update(dto) + err = u.repo.Update(ctx, dto) if err != nil { return err } @@ -95,7 +95,7 @@ func (u *StackTemplateUsecase) Update(ctx context.Context, dto model.StackTempla } func (u *StackTemplateUsecase) Get(ctx context.Context, stackTemplateId uuid.UUID) (res model.StackTemplate, err error) { - res, err = u.repo.Get(stackTemplateId) + res, err = u.repo.Get(ctx, stackTemplateId) if err != nil { return res, err } @@ -103,7 +103,7 @@ func (u *StackTemplateUsecase) Get(ctx context.Context, stackTemplateId uuid.UUI } func (u *StackTemplateUsecase) GetByName(ctx context.Context, name string) (out model.StackTemplate, err error) { - out, err = u.repo.GetByName(name) + out, err = u.repo.GetByName(ctx, name) if err != nil { if errors.Is(err, gorm.ErrRecordNotFound) { return out, httpErrors.NewNotFoundError(err, "ST_FAILED_FETCH_STACK_TEMPLATE", "") @@ -115,7 +115,7 @@ func (u *StackTemplateUsecase) GetByName(ctx context.Context, name string) (out } func (u *StackTemplateUsecase) Fetch(ctx context.Context, pg *pagination.Pagination) (res []model.StackTemplate, err error) { - res, err = u.repo.Fetch(pg) + res, err = u.repo.Fetch(ctx, pg) if err != nil { return nil, err } @@ -123,7 +123,7 @@ func (u *StackTemplateUsecase) Fetch(ctx context.Context, pg *pagination.Paginat } func (u *StackTemplateUsecase) FetchWithOrganization(ctx context.Context, organizationId string, pg *pagination.Pagination) (res []model.StackTemplate, err error) { - res, err = u.repo.FetchWithOrganization(organizationId, pg) + res, err = u.repo.FetchWithOrganization(ctx, organizationId, pg) if err != nil { return nil, err } @@ -135,20 +135,20 @@ func (u *StackTemplateUsecase) Delete(ctx context.Context, dto model.StackTempla } func (u *StackTemplateUsecase) UpdateOrganizations(ctx context.Context, dto model.StackTemplate) error { - _, err := u.repo.Get(dto.ID) + _, err := u.repo.Get(ctx, dto.ID) if err != nil { return httpErrors.NewBadRequestError(err, "ST_NOT_EXISTED_STACK_TEMPLATE", "") } organizations := make([]model.Organization, 0) for _, organizationId := range dto.OrganizationIds { - organization, err := u.organizationRepo.Get(organizationId) + organization, err := u.organizationRepo.Get(ctx, organizationId) if err == nil { organizations = append(organizations, organization) } } - err = u.repo.UpdateOrganizations(dto.ID, organizations) + err = u.repo.UpdateOrganizations(ctx, dto.ID, organizations) if err != nil { return httpErrors.NewBadRequestError(err, "ST_FAILED_UPDATE_ORGANIZATION", "") } diff --git a/internal/usecase/stack.go b/internal/usecase/stack.go index 9daeea2a..906aa322 100644 --- a/internal/usecase/stack.go +++ b/internal/usecase/stack.go @@ -73,12 +73,12 @@ func (u *StackUsecase) Create(ctx context.Context, dto model.Stack) (stackId dom return "", httpErrors.NewBadRequestError(httpErrors.DuplicateResource, "S_CREATE_ALREADY_EXISTED_NAME", "") } - stackTemplate, err := u.stackTemplateRepo.Get(dto.StackTemplateId) + stackTemplate, err := u.stackTemplateRepo.Get(ctx, dto.StackTemplateId) if err != nil { return "", httpErrors.NewInternalServerError(errors.Wrap(err, "Invalid stackTemplateId"), "S_INVALID_STACK_TEMPLATE", "") } - clusters, err := u.clusterRepo.FetchByOrganizationId(dto.OrganizationId, user.GetUserId(), nil) + clusters, err := u.clusterRepo.FetchByOrganizationId(ctx, dto.OrganizationId, user.GetUserId(), nil) if err != nil { return "", httpErrors.NewInternalServerError(errors.Wrap(err, "Failed to get clusters"), "S_FAILED_GET_CLUSTERS", "") } @@ -97,7 +97,7 @@ func (u *StackUsecase) Create(ctx context.Context, dto model.Stack) (stackId dom return "", httpErrors.NewBadRequestError(fmt.Errorf("Invalid clusterEndpoint"), "S_INVALID_ADMINCLUSTER_URL", "") } } else { - if _, err = u.cloudAccountRepo.Get(dto.CloudAccountId); err != nil { + if _, err = u.cloudAccountRepo.Get(ctx, dto.CloudAccountId); err != nil { return "", httpErrors.NewInternalServerError(errors.Wrap(err, "Invalid cloudAccountId"), "S_INVALID_CLOUD_ACCOUNT", "") } } @@ -157,7 +157,7 @@ func (u *StackUsecase) Create(ctx context.Context, dto model.Stack) (stackId dom return "", fmt.Errorf("Invalid workflow status [%s]", workflow.Status.Phase) } - cluster, err := u.clusterRepo.GetByName(dto.OrganizationId, dto.Name) + cluster, err := u.clusterRepo.GetByName(ctx, dto.OrganizationId, dto.Name) if err != nil { continue } @@ -176,12 +176,12 @@ func (u *StackUsecase) Install(ctx context.Context, stackId domain.StackId) (err return httpErrors.NewBadRequestError(fmt.Errorf("Invalid stackId"), "S_INVALID_STACK_ID", "") } - _, err = u.stackTemplateRepo.Get(cluster.StackTemplateId) + _, err = u.stackTemplateRepo.Get(ctx, cluster.StackTemplateId) if err != nil { return httpErrors.NewInternalServerError(errors.Wrap(err, "Invalid stackTemplateId"), "S_INVALID_STACK_TEMPLATE", "") } - clusters, err := u.clusterRepo.FetchByOrganizationId(cluster.OrganizationId, uuid.Nil, nil) + clusters, err := u.clusterRepo.FetchByOrganizationId(ctx, cluster.OrganizationId, uuid.Nil, nil) if err != nil { return httpErrors.NewInternalServerError(errors.Wrap(err, "Failed to get clusters"), "S_FAILED_GET_CLUSTERS", "") } @@ -223,7 +223,7 @@ func (u *StackUsecase) Install(ctx context.Context, stackId domain.StackId) (err } func (u *StackUsecase) Get(ctx context.Context, stackId domain.StackId) (out model.Stack, err error) { - cluster, err := u.clusterRepo.Get(domain.ClusterId(stackId)) + cluster, err := u.clusterRepo.Get(ctx, domain.ClusterId(stackId)) if err != nil { if errors.Is(err, gorm.ErrRecordNotFound) { return out, httpErrors.NewNotFoundError(err, "S_FAILED_FETCH_CLUSTER", "") @@ -231,12 +231,12 @@ func (u *StackUsecase) Get(ctx context.Context, stackId domain.StackId) (out mod return out, err } - organization, err := u.organizationRepo.Get(cluster.OrganizationId) + organization, err := u.organizationRepo.Get(ctx, cluster.OrganizationId) if err != nil { return out, httpErrors.NewInternalServerError(errors.Wrap(err, fmt.Sprintf("Failed to get organization for clusterId %s", domain.ClusterId(stackId))), "S_FAILED_FETCH_ORGANIZATION", "") } - appGroups, err := u.appGroupRepo.Fetch(domain.ClusterId(stackId), nil) + appGroups, err := u.appGroupRepo.Fetch(ctx, domain.ClusterId(stackId), nil) if err != nil { return out, err } @@ -256,14 +256,14 @@ func (u *StackUsecase) Get(ctx context.Context, stackId domain.StackId) (out mod } } - appGroupsInPrimaryCluster, err := u.appGroupRepo.Fetch(domain.ClusterId(organization.PrimaryClusterId), nil) + appGroupsInPrimaryCluster, err := u.appGroupRepo.Fetch(ctx, domain.ClusterId(organization.PrimaryClusterId), nil) if err != nil { return out, err } for _, appGroup := range appGroupsInPrimaryCluster { if appGroup.AppGroupType == domain.AppGroupType_LMA { - applications, err := u.appGroupRepo.GetApplications(appGroup.ID, domain.ApplicationType_GRAFANA) + applications, err := u.appGroupRepo.GetApplications(ctx, appGroup.ID, domain.ApplicationType_GRAFANA) if err != nil { return out, err } @@ -277,7 +277,7 @@ func (u *StackUsecase) Get(ctx context.Context, stackId domain.StackId) (out mod } func (u *StackUsecase) GetByName(ctx context.Context, organizationId string, name string) (out model.Stack, err error) { - cluster, err := u.clusterRepo.GetByName(organizationId, name) + cluster, err := u.clusterRepo.GetByName(ctx, organizationId, name) if err != nil { if errors.Is(err, gorm.ErrRecordNotFound) { return out, httpErrors.NewNotFoundError(err, "S_FAILED_FETCH_CLUSTER", "") @@ -285,7 +285,7 @@ func (u *StackUsecase) GetByName(ctx context.Context, organizationId string, nam return out, err } - appGroups, err := u.appGroupRepo.Fetch(cluster.ID, nil) + appGroups, err := u.appGroupRepo.Fetch(ctx, cluster.ID, nil) if err != nil { return out, err } @@ -300,12 +300,12 @@ func (u *StackUsecase) Fetch(ctx context.Context, organizationId string, pg *pag return out, httpErrors.NewUnauthorizedError(fmt.Errorf("Invalid token"), "A_INVALID_TOKEN", "") } - organization, err := u.organizationRepo.Get(organizationId) + organization, err := u.organizationRepo.Get(ctx, organizationId) if err != nil { return out, httpErrors.NewInternalServerError(errors.Wrap(err, fmt.Sprintf("Failed to get organization for clusterId %s", organizationId)), "S_FAILED_FETCH_ORGANIZATION", "") } - clusters, err := u.clusterRepo.FetchByOrganizationId(organizationId, user.GetUserId(), pg) + clusters, err := u.clusterRepo.FetchByOrganizationId(ctx, organizationId, user.GetUserId(), pg) if err != nil { return out, err } @@ -313,7 +313,7 @@ func (u *StackUsecase) Fetch(ctx context.Context, organizationId string, pg *pag stackResources, _ := u.dashbordUsecase.GetStacks(ctx, organizationId) for _, cluster := range clusters { - appGroups, err := u.appGroupRepo.Fetch(cluster.ID, nil) + appGroups, err := u.appGroupRepo.Fetch(ctx, cluster.ID, nil) if err != nil { return nil, err } @@ -325,7 +325,7 @@ func (u *StackUsecase) Fetch(ctx context.Context, organizationId string, pg *pag for _, appGroup := range appGroups { if appGroup.AppGroupType == domain.AppGroupType_LMA { - applications, err := u.appGroupRepo.GetApplications(appGroup.ID, domain.ApplicationType_GRAFANA) + applications, err := u.appGroupRepo.GetApplications(ctx, appGroup.ID, domain.ApplicationType_GRAFANA) if err != nil { return nil, err } @@ -359,7 +359,7 @@ func (u *StackUsecase) Update(ctx context.Context, dto model.Stack) (err error) return httpErrors.NewBadRequestError(fmt.Errorf("Invalid token"), "", "") } - _, err = u.clusterRepo.Get(domain.ClusterId(dto.ID)) + _, err = u.clusterRepo.Get(ctx, domain.ClusterId(dto.ID)) if err != nil { return httpErrors.NewNotFoundError(err, "S_FAILED_FETCH_CLUSTER", "") } @@ -371,7 +371,7 @@ func (u *StackUsecase) Update(ctx context.Context, dto model.Stack) (err error) UpdatorId: &updatorId, } - err = u.clusterRepo.Update(dtoCluster) + err = u.clusterRepo.Update(ctx, dtoCluster) if err != nil { return err } @@ -385,13 +385,13 @@ func (u *StackUsecase) Delete(ctx context.Context, dto model.Stack) (err error) return httpErrors.NewBadRequestError(fmt.Errorf("Invalid token"), "", "") } - cluster, err := u.clusterRepo.Get(domain.ClusterId(dto.ID)) + cluster, err := u.clusterRepo.Get(ctx, domain.ClusterId(dto.ID)) if err != nil { return httpErrors.NewBadRequestError(errors.Wrap(err, "Failed to get cluster"), "S_FAILED_FETCH_CLUSTER", "") } // 지우려고 하는 stack 이 primary cluster 라면, organization 내에 cluster 가 자기 자신만 남아있을 경우이다. - organizations, err := u.organizationRepo.Fetch(nil) + organizations, err := u.organizationRepo.Fetch(ctx, nil) if err != nil { return errors.Wrap(err, "Failed to get organizations") } @@ -399,7 +399,7 @@ func (u *StackUsecase) Delete(ctx context.Context, dto model.Stack) (err error) for _, organization := range *organizations { if organization.PrimaryClusterId == cluster.ID.String() { - clusters, err := u.clusterRepo.FetchByOrganizationId(organization.ID, user.GetUserId(), nil) + clusters, err := u.clusterRepo.FetchByOrganizationId(ctx, organization.ID, user.GetUserId(), nil) if err != nil { return errors.Wrap(err, "Failed to get organizations") } @@ -414,7 +414,7 @@ func (u *StackUsecase) Delete(ctx context.Context, dto model.Stack) (err error) break } } - appGroups, err := u.appGroupRepo.Fetch(domain.ClusterId(dto.ID), nil) + appGroups, err := u.appGroupRepo.Fetch(ctx, domain.ClusterId(dto.ID), nil) if err != nil { return errors.Wrap(err, "Failed to get appGroups") } @@ -426,7 +426,7 @@ func (u *StackUsecase) Delete(ctx context.Context, dto model.Stack) (err error) } } - appsCnt, err := u.appServeAppRepo.GetNumOfAppsOnStack(dto.OrganizationId, dto.ID.String()) + appsCnt, err := u.appServeAppRepo.GetNumOfAppsOnStack(ctx, dto.OrganizationId, dto.ID.String()) if err != nil { return errors.Wrap(err, "Failed to get numOfAppsOnStack") } @@ -453,10 +453,10 @@ func (u *StackUsecase) Delete(ctx context.Context, dto model.Stack) (err error) log.DebugWithContext(ctx, "Submitted workflow: ", workflowId) // Remove Cluster & AppGroup status description - if err := u.appGroupRepo.InitWorkflowDescription(cluster.ID); err != nil { + if err := u.appGroupRepo.InitWorkflowDescription(ctx, cluster.ID); err != nil { log.ErrorWithContext(ctx, err) } - if err := u.clusterRepo.InitWorkflowDescription(cluster.ID); err != nil { + if err := u.clusterRepo.InitWorkflowDescription(ctx, cluster.ID); err != nil { log.ErrorWithContext(ctx, err) } @@ -493,12 +493,12 @@ func (u *StackUsecase) GetKubeConfig(ctx context.Context, stackId domain.StackId // [TODO] need more pretty... func (u *StackUsecase) GetStepStatus(ctx context.Context, stackId domain.StackId) (out []domain.StackStepStatus, stackStatus string, err error) { - cluster, err := u.clusterRepo.Get(domain.ClusterId(stackId)) + cluster, err := u.clusterRepo.Get(ctx, domain.ClusterId(stackId)) if err != nil { return out, "", err } - organization, err := u.organizationRepo.Get(cluster.OrganizationId) + organization, err := u.organizationRepo.Get(ctx, cluster.OrganizationId) if err != nil { return out, "", err } @@ -541,7 +541,7 @@ func (u *StackUsecase) GetStepStatus(ctx context.Context, stackId domain.StackId }) } - appGroups, err := u.appGroupRepo.Fetch(domain.ClusterId(stackId), nil) + appGroups, err := u.appGroupRepo.Fetch(ctx, domain.ClusterId(stackId), nil) for _, appGroup := range appGroups { for i, step := range out { if step.Stage == appGroup.AppGroupType.String() { @@ -596,7 +596,7 @@ func (u *StackUsecase) SetFavorite(ctx context.Context, stackId domain.StackId) return httpErrors.NewUnauthorizedError(fmt.Errorf("Invalid token"), "A_INVALID_TOKEN", "") } - err := u.clusterRepo.SetFavorite(domain.ClusterId(stackId), user.GetUserId()) + err := u.clusterRepo.SetFavorite(ctx, domain.ClusterId(stackId), user.GetUserId()) if err != nil { return err } @@ -610,7 +610,7 @@ func (u *StackUsecase) DeleteFavorite(ctx context.Context, stackId domain.StackI return httpErrors.NewUnauthorizedError(fmt.Errorf("Invalid token"), "A_INVALID_TOKEN", "") } - err := u.clusterRepo.DeleteFavorite(domain.ClusterId(stackId), user.GetUserId()) + err := u.clusterRepo.DeleteFavorite(ctx, domain.ClusterId(stackId), user.GetUserId()) if err != nil { return err } diff --git a/internal/usecase/user.go b/internal/usecase/user.go index b3ebef7d..92cb6fe4 100644 --- a/internal/usecase/user.go +++ b/internal/usecase/user.go @@ -19,18 +19,18 @@ import ( ) type IUserUsecase interface { - CreateAdmin(organizationId string, accountId string, accountName string, email string) (*model.User, error) - DeleteAdmin(organizationId string) error + CreateAdmin(ctx context.Context, organizationId string, accountId string, accountName string, email string) (*model.User, error) + DeleteAdmin(ctx context.Context, organizationId string) error DeleteAll(ctx context.Context, organizationId string) 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) + Get(ctx context.Context, 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 + ResetPassword(ctx context.Context, userId uuid.UUID) error + ResetPasswordByAccountId(ctx context.Context, accountId string, organizationId string) error + GenerateRandomPassword(ctx context.Context, ) string + Delete(ctx context.Context, userId uuid.UUID, organizationId string) 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 @@ -40,8 +40,8 @@ type IUserUsecase interface { RenewalPasswordExpiredTime(ctx context.Context, userId uuid.UUID) error RenewalPasswordExpiredTimeByAccountId(ctx context.Context, accountId string, organizationId string) error DeleteByAccountId(ctx context.Context, accountId string, organizationId string) error - ValidateAccount(userId uuid.UUID, password string, organizationId string) error - ValidateAccountByAccountId(accountId string, password string, organizationId string) error + ValidateAccount(ctx context.Context, userId uuid.UUID, password string, organizationId string) error + ValidateAccountByAccountId(ctx context.Context, accountId string, password string, organizationId string) error UpdateByAccountIdByAdmin(ctx context.Context, accountId string, user *model.User) (*model.User, error) } @@ -54,7 +54,7 @@ type UserUsecase struct { } func (u *UserUsecase) RenewalPasswordExpiredTime(ctx context.Context, userId uuid.UUID) error { - user, err := u.userRepository.GetByUuid(userId) + user, err := u.userRepository.GetByUuid(ctx, userId) if err != nil { if _, status := httpErrors.ErrorResponse(err); status != http.StatusNotFound { return httpErrors.NewBadRequestError(fmt.Errorf("user not found"), "U_NO_USER", "") @@ -62,7 +62,7 @@ func (u *UserUsecase) RenewalPasswordExpiredTime(ctx context.Context, userId uui return httpErrors.NewInternalServerError(err, "", "") } - err = u.userRepository.UpdatePasswordAt(userId, user.Organization.ID, false) + err = u.userRepository.UpdatePasswordAt(ctx, userId, user.Organization.ID, false) if err != nil { log.ErrorfWithContext(ctx, "failed to update password expired time: %v", err) return httpErrors.NewInternalServerError(err, "", "") @@ -72,7 +72,7 @@ func (u *UserUsecase) RenewalPasswordExpiredTime(ctx context.Context, userId uui } func (u *UserUsecase) RenewalPasswordExpiredTimeByAccountId(ctx context.Context, accountId string, organizationId string) error { - user, err := u.userRepository.Get(accountId, organizationId) + user, err := u.userRepository.Get(ctx, accountId, organizationId) if err != nil { if _, status := httpErrors.ErrorResponse(err); status != http.StatusNotFound { return httpErrors.NewBadRequestError(fmt.Errorf("user not found"), "U_NO_USER", "") @@ -82,8 +82,8 @@ func (u *UserUsecase) RenewalPasswordExpiredTimeByAccountId(ctx context.Context, return u.RenewalPasswordExpiredTime(ctx, user.ID) } -func (u *UserUsecase) ResetPassword(userId uuid.UUID) error { - user, err := u.userRepository.GetByUuid(userId) +func (u *UserUsecase) ResetPassword(ctx context.Context, userId uuid.UUID) error { + user, err := u.userRepository.GetByUuid(ctx, userId) if err != nil { if _, status := httpErrors.ErrorResponse(err); status == http.StatusNotFound { return httpErrors.NewBadRequestError(fmt.Errorf("user not found"), "U_NO_USER", "") @@ -109,7 +109,7 @@ func (u *UserUsecase) ResetPassword(userId uuid.UUID) error { return httpErrors.NewInternalServerError(err, "", "") } - if err = u.userRepository.UpdatePasswordAt(userId, user.Organization.ID, true); err != nil { + if err = u.userRepository.UpdatePasswordAt(ctx, userId, user.Organization.ID, true); err != nil { return httpErrors.NewInternalServerError(err, "", "") } @@ -128,23 +128,23 @@ func (u *UserUsecase) ResetPassword(userId uuid.UUID) error { return nil } -func (u *UserUsecase) ResetPasswordByAccountId(accountId string, organizationId string) error { - user, err := u.userRepository.Get(accountId, organizationId) +func (u *UserUsecase) ResetPasswordByAccountId(ctx context.Context, accountId string, organizationId string) error { + user, err := u.userRepository.Get(ctx, accountId, organizationId) if err != nil { if _, status := httpErrors.ErrorResponse(err); status == http.StatusNotFound { return httpErrors.NewBadRequestError(fmt.Errorf("user not found"), "U_NO_USER", "") } return httpErrors.NewInternalServerError(err, "", "") } - return u.ResetPassword(user.ID) + return u.ResetPassword(ctx, user.ID) } -func (u *UserUsecase) GenerateRandomPassword() string { +func (u *UserUsecase) GenerateRandomPassword(ctx context.Context) string { return helper.GenerateRandomString(passwordLength) } -func (u *UserUsecase) ValidateAccount(userId uuid.UUID, password string, organizationId string) error { - user, err := u.userRepository.GetByUuid(userId) +func (u *UserUsecase) ValidateAccount(ctx context.Context, userId uuid.UUID, password string, organizationId string) error { + user, err := u.userRepository.GetByUuid(ctx, userId) if err != nil { return httpErrors.NewBadRequestError(fmt.Errorf("user not found"), "U_NO_USER", "") } @@ -155,7 +155,7 @@ func (u *UserUsecase) ValidateAccount(userId uuid.UUID, password string, organiz return nil } -func (u *UserUsecase) ValidateAccountByAccountId(accountId string, password string, organizationId string) error { +func (u *UserUsecase) ValidateAccountByAccountId(ctx context.Context, accountId string, password string, organizationId string) error { _, err := u.kc.Login(organizationId, accountId, password) return err } @@ -164,7 +164,7 @@ func (u *UserUsecase) DeleteAll(ctx context.Context, organizationId string) erro // TODO: implement me as transaction // TODO: clean users in keycloak - err := u.userRepository.Flush(organizationId) + err := u.userRepository.Flush(ctx, organizationId) if err != nil { return err } @@ -172,7 +172,7 @@ func (u *UserUsecase) DeleteAll(ctx context.Context, organizationId string) erro return nil } -func (u *UserUsecase) DeleteAdmin(organizationId string) error { +func (u *UserUsecase) DeleteAdmin(ctx context.Context, organizationId string) error { user, err := u.kc.GetUser(organizationId, "admin") if err != nil { return errors.Wrap(err, "get user failed") @@ -188,7 +188,7 @@ func (u *UserUsecase) DeleteAdmin(organizationId string) error { return errors.Wrap(err, "parse user id failed") } - err = u.userRepository.DeleteWithUuid(userUuid) + err = u.userRepository.DeleteWithUuid(ctx, userUuid) if err != nil { return errors.Wrap(err, "delete user failed") } @@ -196,7 +196,7 @@ func (u *UserUsecase) DeleteAdmin(organizationId string) error { return nil } -func (u *UserUsecase) CreateAdmin(organizationId string, accountId string, accountName string, email string) (*model.User, error) { +func (u *UserUsecase) CreateAdmin(ctx context.Context, organizationId string, accountId string, accountName string, email string) (*model.User, error) { // Generate Admin user object randomPassword := helper.GenerateRandomString(passwordLength) user := model.User{ @@ -219,7 +219,7 @@ func (u *UserUsecase) CreateAdmin(organizationId string, accountId string, accou } // Send mail of temporary password - organizationInfo, err := u.organizationRepository.Get(organizationId) + organizationInfo, err := u.organizationRepository.Get(ctx, organizationId) if err != nil { return nil, err } @@ -236,7 +236,7 @@ func (u *UserUsecase) CreateAdmin(organizationId string, accountId string, accou } func (u *UserUsecase) SendEmailForTemporaryPassword(ctx context.Context, accountId string, organizationId string, password string) error { - user, err := u.userRepository.Get(accountId, organizationId) + user, err := u.userRepository.Get(ctx, accountId, organizationId) if err != nil { return err } @@ -282,12 +282,12 @@ func (u *UserUsecase) UpdatePasswordByAccountId(ctx context.Context, accountId s } // update password UpdateAt in DB - user, err := u.userRepository.Get(accountId, organizationId) + user, err := u.userRepository.Get(ctx, accountId, organizationId) if err != nil { return errors.Wrap(err, "getting user from repository failed") } - err = u.userRepository.UpdatePasswordAt(user.ID, organizationId, false) + err = u.userRepository.UpdatePasswordAt(ctx, user.ID, organizationId, false) if err != nil { return errors.Wrap(err, "updating user in repository failed") } @@ -296,7 +296,7 @@ func (u *UserUsecase) UpdatePasswordByAccountId(ctx context.Context, accountId s } func (u *UserUsecase) List(ctx context.Context, organizationId string) (users *[]model.User, err error) { - users, err = u.userRepository.List(u.userRepository.OrganizationFilter(organizationId)) + users, err = u.userRepository.List(ctx, u.userRepository.OrganizationFilter(organizationId)) if err != nil { return nil, err } @@ -305,7 +305,7 @@ func (u *UserUsecase) List(ctx context.Context, organizationId string) (users *[ } func (u *UserUsecase) ListWithPagination(ctx context.Context, organizationId string, pg *pagination.Pagination) (users *[]model.User, err error) { - users, err = u.userRepository.ListWithPagination(pg, organizationId) + users, err = u.userRepository.ListWithPagination(ctx, pg, organizationId) if err != nil { return nil, err } @@ -313,8 +313,8 @@ func (u *UserUsecase) ListWithPagination(ctx context.Context, organizationId str return } -func (u *UserUsecase) Get(userId uuid.UUID) (*model.User, error) { - user, err := u.userRepository.GetByUuid(userId) +func (u *UserUsecase) Get(ctx context.Context, userId uuid.UUID) (*model.User, error) { + user, err := u.userRepository.GetByUuid(ctx, userId) if err != nil { if _, status := httpErrors.ErrorResponse(err); status == http.StatusNotFound { return nil, httpErrors.NewBadRequestError(fmt.Errorf("user not found"), "U_NO_USER", "") @@ -326,7 +326,7 @@ func (u *UserUsecase) Get(userId uuid.UUID) (*model.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), + users, err := u.userRepository.List(ctx, u.userRepository.OrganizationFilter(organizationId), u.userRepository.AccountIdFilter(accountId)) if err != nil { return nil, err @@ -336,7 +336,7 @@ func (u *UserUsecase) GetByAccountId(ctx context.Context, accountId string, orga } func (u *UserUsecase) GetByEmail(ctx context.Context, email string, organizationId string) (*model.User, error) { - users, err := u.userRepository.List(u.userRepository.OrganizationFilter(organizationId), + users, err := u.userRepository.List(ctx, u.userRepository.OrganizationFilter(organizationId), u.userRepository.EmailFilter(email)) if err != nil { return nil, err @@ -346,7 +346,7 @@ func (u *UserUsecase) GetByEmail(ctx context.Context, email string, organization } func (u *UserUsecase) Update(ctx context.Context, userId uuid.UUID, user *model.User) (*model.User, error) { - storedUser, err := u.Get(userId) + storedUser, err := u.Get(ctx, userId) if err != nil { return nil, err } @@ -372,7 +372,7 @@ func (u *UserUsecase) UpdateByAccountId(ctx context.Context, accountId string, u } } - users, err := u.userRepository.List(u.userRepository.OrganizationFilter(user.Organization.ID), + users, err := u.userRepository.List(ctx, u.userRepository.OrganizationFilter(user.Organization.ID), u.userRepository.AccountIdFilter(accountId)) if err != nil { if _, code := httpErrors.ErrorResponse(err); code == http.StatusNotFound { @@ -391,7 +391,7 @@ func (u *UserUsecase) UpdateByAccountId(ctx context.Context, accountId string, u return nil, err } - out, err = u.userRepository.UpdateWithUuid((*users)[0].ID, user.AccountId, user.Name, roleUuid, user.Email, user.Department, user.Description) + out, err = u.userRepository.UpdateWithUuid(ctx, (*users)[0].ID, user.AccountId, user.Name, roleUuid, user.Email, user.Department, user.Description) if err != nil { return nil, errors.Wrap(err, "updating user in repository failed") } @@ -399,13 +399,13 @@ func (u *UserUsecase) UpdateByAccountId(ctx context.Context, accountId string, u return &out, nil } -func (u *UserUsecase) Delete(userId uuid.UUID, organizationId string) error { - user, err := u.userRepository.GetByUuid(userId) +func (u *UserUsecase) Delete(ctx context.Context, userId uuid.UUID, organizationId string) error { + user, err := u.userRepository.GetByUuid(ctx, userId) if err != nil { return httpErrors.NewBadRequestError(fmt.Errorf("not found user"), "", "") } - err = u.userRepository.DeleteWithUuid(userId) + err = u.userRepository.DeleteWithUuid(ctx, userId) if err != nil { return err } @@ -419,12 +419,12 @@ func (u *UserUsecase) Delete(userId uuid.UUID, organizationId string) error { return nil } func (u *UserUsecase) DeleteByAccountId(ctx context.Context, accountId string, organizationId string) error { - user, err := u.userRepository.Get(accountId, organizationId) + user, err := u.userRepository.Get(ctx, accountId, organizationId) if err != nil { return err } - err = u.userRepository.DeleteWithUuid(user.ID) + err = u.userRepository.DeleteWithUuid(ctx, user.ID) if err != nil { return err } @@ -460,7 +460,7 @@ func (u *UserUsecase) Create(ctx context.Context, user *model.User) (*model.User // Get user role var roleUuid string - roles, err := u.roleRepository.ListTksRoles(user.Organization.ID, nil) + roles, err := u.roleRepository.ListTksRoles(ctx, user.Organization.ID, nil) if err != nil { return nil, err } @@ -483,7 +483,7 @@ func (u *UserUsecase) Create(ctx context.Context, user *model.User) (*model.User } // Create user in DB - resUser, err := u.userRepository.CreateWithUuid(userUuid, user.AccountId, user.Name, user.Email, + resUser, err := u.userRepository.CreateWithUuid(ctx, userUuid, user.AccountId, user.Name, user.Email, user.Department, user.Description, user.Organization.ID, roleUuid) if err != nil { return nil, err @@ -512,7 +512,7 @@ func (u *UserUsecase) UpdateByAccountIdByAdmin(ctx context.Context, accountId st } } - *user, err = u.userRepository.UpdateWithUuid(user.ID, user.AccountId, user.Name, newUser.Role.ID, user.Email, + *user, err = u.userRepository.UpdateWithUuid(ctx, user.ID, user.AccountId, user.Name, newUser.Role.ID, user.Email, user.Department, user.Description) if err != nil { return nil, errors.Wrap(err, "updating user in repository failed") From 649e139690f0796f2884204ecf922ce5e61795cd Mon Sep 17 00:00:00 2001 From: donggyu Date: Tue, 12 Mar 2024 17:48:30 +0900 Subject: [PATCH 04/11] Remove logWithContext, Make context as default parameter in logs(info,warn,...) --- pkg/log/log.go | 184 +++++++++++++++++++++++++++---------------------- 1 file changed, 100 insertions(+), 84 deletions(-) diff --git a/pkg/log/log.go b/pkg/log/log.go index a88eac18..1c532e15 100644 --- a/pkg/log/log.go +++ b/pkg/log/log.go @@ -103,133 +103,149 @@ func (f *CustomFormatter) Format(entry *logrus.Entry) ([]byte, error) { } // [TODO] more pretty -func Info(v ...interface{}) { +func Info(ctx context.Context, v ...interface{}) { + fields := logrus.Fields{} + if _, file, line, ok := runtime.Caller(1); ok { relativePath := getRelativeFilePath(file) - logger.WithFields(logrus.Fields{ - "file": relativePath + ":" + strconv.Itoa(line), - }).Info(v...) - } else { - logger.Info(v...) + fields["file"] = relativePath + ":" + strconv.Itoa(line) + } + + if ctx != nil { + fields[string(internal.ContextKeyRequestID)] = ctx.Value(internal.ContextKeyRequestID) } + + logger.WithFields(fields).Info(v...) } -func Infof(format string, v ...interface{}) { +func Infof(ctx context.Context, format string, v ...interface{}) { + fields := logrus.Fields{} + if _, file, line, ok := runtime.Caller(1); ok { relativePath := getRelativeFilePath(file) - logger.WithFields(logrus.Fields{ - "file": relativePath + ":" + strconv.Itoa(line), - }).Infof(format, v...) - } else { - logger.Infof(format, v...) + fields["file"] = relativePath + ":" + strconv.Itoa(line) } -} -func InfoWithContext(ctx context.Context, v ...interface{}) { - logger.WithField(string(internal.ContextKeyRequestID), ctx.Value(internal.ContextKeyRequestID)).Info(v...) -} -func InfofWithContext(ctx context.Context, format string, v ...interface{}) { - logger.WithField(string(internal.ContextKeyRequestID), ctx.Value(internal.ContextKeyRequestID)).Infof(format, v...) + + if ctx != nil { + fields[string(internal.ContextKeyRequestID)] = ctx.Value(internal.ContextKeyRequestID) + } + + logger.WithFields(fields).Infof(format, v...) } -func Warn(v ...interface{}) { +func Warn(ctx context.Context, v ...interface{}) { + fields := logrus.Fields{} + if _, file, line, ok := runtime.Caller(1); ok { relativePath := getRelativeFilePath(file) - logger.WithFields(logrus.Fields{ - "file": relativePath + ":" + strconv.Itoa(line), - }).Warn(v...) - } else { - logger.Warn(v...) + fields["file"] = relativePath + ":" + strconv.Itoa(line) } + + if ctx != nil { + fields[string(internal.ContextKeyRequestID)] = ctx.Value(internal.ContextKeyRequestID) + } + + logger.WithFields(fields).Warn(v...) } -func Warnf(format string, v ...interface{}) { +func Warnf(ctx context.Context, format string, v ...interface{}) { + fields := logrus.Fields{} + if _, file, line, ok := runtime.Caller(1); ok { relativePath := getRelativeFilePath(file) - logger.WithFields(logrus.Fields{ - "file": relativePath + ":" + strconv.Itoa(line), - }).Warnf(format, v...) - } else { - logger.Warnf(format, v...) + fields["file"] = relativePath + ":" + strconv.Itoa(line) } -} -func WarnWithContext(ctx context.Context, v ...interface{}) { - logger.WithField(string(internal.ContextKeyRequestID), ctx.Value(internal.ContextKeyRequestID)).Warn(v...) -} -func WarnfWithContext(ctx context.Context, format string, v ...interface{}) { - logger.WithField(string(internal.ContextKeyRequestID), ctx.Value(internal.ContextKeyRequestID)).Warnf(format, v...) + + if ctx != nil { + fields[string(internal.ContextKeyRequestID)] = ctx.Value(internal.ContextKeyRequestID) + } + + logger.WithFields(fields).Warnf(format, v...) } -func Debug(v ...interface{}) { +func Debug(ctx context.Context, v ...interface{}) { + fields := logrus.Fields{} + if _, file, line, ok := runtime.Caller(1); ok { relativePath := getRelativeFilePath(file) - logger.WithFields(logrus.Fields{ - "file": relativePath + ":" + strconv.Itoa(line), - }).Debug(v...) - } else { - logger.Debug(v...) + fields["file"] = relativePath + ":" + strconv.Itoa(line) } + + if ctx != nil { + fields[string(internal.ContextKeyRequestID)] = ctx.Value(internal.ContextKeyRequestID) + } + + logger.WithFields(fields).Debug(v...) } -func Debugf(format string, v ...interface{}) { +func Debugf(ctx context.Context, format string, v ...interface{}) { + fields := logrus.Fields{} + if _, file, line, ok := runtime.Caller(1); ok { relativePath := getRelativeFilePath(file) - logger.WithFields(logrus.Fields{ - "file": relativePath + ":" + strconv.Itoa(line), - }).Debugf(format, v...) - } else { - logger.Debugf(format, v...) + fields["file"] = relativePath + ":" + strconv.Itoa(line) } + + if ctx != nil { + fields[string(internal.ContextKeyRequestID)] = ctx.Value(internal.ContextKeyRequestID) + } + + logger.WithFields(fields).Debugf(format, v...) } -func DebugWithContext(ctx context.Context, v ...interface{}) { - logger.WithField(string(internal.ContextKeyRequestID), ctx.Value(internal.ContextKeyRequestID)).Debug(v...) -} -func DebugfWithContext(ctx context.Context, format string, v ...interface{}) { - logger.WithField(string(internal.ContextKeyRequestID), ctx.Value(internal.ContextKeyRequestID)).Debugf(format, v...) -} -func Error(v ...interface{}) { +func Error(ctx context.Context, v ...interface{}) { + fields := logrus.Fields{} + if _, file, line, ok := runtime.Caller(1); ok { relativePath := getRelativeFilePath(file) - logger.WithFields(logrus.Fields{ - "file": relativePath + ":" + strconv.Itoa(line), - }).Error(v...) - } else { - logger.Error(v...) + fields["file"] = relativePath + ":" + strconv.Itoa(line) + } + + if ctx != nil { + fields[string(internal.ContextKeyRequestID)] = ctx.Value(internal.ContextKeyRequestID) } + + logger.WithFields(fields).Error(v...) } -func Errorf(format string, v ...interface{}) { +func Errorf(ctx context.Context, format string, v ...interface{}) { + fields := logrus.Fields{} + if _, file, line, ok := runtime.Caller(1); ok { relativePath := getRelativeFilePath(file) - logger.WithFields(logrus.Fields{ - "file": relativePath + ":" + strconv.Itoa(line), - }).Errorf(format, v...) - } else { - logger.Errorf(format, v...) + fields["file"] = relativePath + ":" + strconv.Itoa(line) } -} -func ErrorWithContext(ctx context.Context, v ...interface{}) { - logger.WithField(string(internal.ContextKeyRequestID), ctx.Value(internal.ContextKeyRequestID)).Error(v...) -} -func ErrorfWithContext(ctx context.Context, format string, v ...interface{}) { - logger.WithField(string(internal.ContextKeyRequestID), ctx.Value(internal.ContextKeyRequestID)).Errorf(format, v...) + + if ctx != nil { + fields[string(internal.ContextKeyRequestID)] = ctx.Value(internal.ContextKeyRequestID) + } + + logger.WithFields(fields).Errorf(format, v...) } -func Fatal(v ...interface{}) { +func Fatal(ctx context.Context, v ...interface{}) { + fields := logrus.Fields{} + if _, file, line, ok := runtime.Caller(1); ok { relativePath := getRelativeFilePath(file) - logger.WithFields(logrus.Fields{ - "file": relativePath + ":" + strconv.Itoa(line), - }).Fatal(v...) - } else { - logger.Fatal(v...) + fields["file"] = relativePath + ":" + strconv.Itoa(line) + } + + if ctx != nil { + fields[string(internal.ContextKeyRequestID)] = ctx.Value(internal.ContextKeyRequestID) } + + logger.WithFields(fields).Fatal(v...) } -func Fatalf(format string, v ...interface{}) { +func Fatalf(ctx context.Context, format string, v ...interface{}) { + fields := logrus.Fields{} + if _, file, line, ok := runtime.Caller(1); ok { relativePath := getRelativeFilePath(file) - logger.WithFields(logrus.Fields{ - "file": relativePath + ":" + strconv.Itoa(line), - }).Fatalf(format, v...) - } else { - logger.Fatalf(format, v...) + fields["file"] = relativePath + ":" + strconv.Itoa(line) } + + if ctx != nil { + fields[string(internal.ContextKeyRequestID)] = ctx.Value(internal.ContextKeyRequestID) + } + + logger.WithFields(fields).Fatalf(format, v...) } func Disable() { From 575e15f02838a113020f6bcff0c4354002504f40 Mon Sep 17 00:00:00 2001 From: donggyu Date: Tue, 12 Mar 2024 17:49:49 +0900 Subject: [PATCH 05/11] fix conflict during rebase --- internal/delivery/http/alert.go | 18 +++++++++--------- internal/delivery/http/app-group.go | 12 ++++++------ internal/delivery/http/app-serve-app.go | 4 ++-- internal/delivery/http/audit.go | 6 +++--- internal/delivery/http/cloud-account.go | 14 +++++++------- internal/delivery/http/cluster.go | 12 ++++++------ internal/delivery/http/dashboard.go | 8 ++++---- internal/delivery/http/organization.go | 4 ++-- internal/delivery/http/project.go | 6 +++--- internal/delivery/http/role.go | 4 ++-- internal/delivery/http/stack-template.go | 16 ++++++++-------- internal/delivery/http/stack.go | 18 +++++++++--------- internal/delivery/http/user.go | 4 ++-- internal/middleware/logging/logging.go | 4 ++-- internal/usecase/alert.go | 2 +- internal/usecase/cloud-account.go | 8 ++++---- internal/usecase/cluster.go | 12 ++++++------ internal/usecase/dashboard.go | 2 +- internal/usecase/organization.go | 2 +- internal/usecase/stack-template.go | 2 +- internal/usecase/stack.go | 4 ++-- 21 files changed, 81 insertions(+), 81 deletions(-) diff --git a/internal/delivery/http/alert.go b/internal/delivery/http/alert.go index bf878aef..3cc24e7a 100644 --- a/internal/delivery/http/alert.go +++ b/internal/delivery/http/alert.go @@ -53,7 +53,7 @@ func (h *AlertHandler) CreateAlert(w http.ResponseWriter, r *http.Request) { log.ErrorWithContext(r.Context(),err) } bodyString := string(bodyBytes) - log.InfoWithContext(r.Context(),bodyString) + log.Info(r.Context(),bodyString) */ // 외부로부터(alert manager) 오는 데이터이므로, dto 변환없이 by-pass 처리한다. @@ -127,13 +127,13 @@ func (h *AlertHandler) GetAlerts(w http.ResponseWriter, r *http.Request) { out.Alerts = make([]domain.AlertResponse, len(alerts)) for i, alert := range alerts { if err := serializer.Map(alert, &out.Alerts[i]); err != nil { - log.InfoWithContext(r.Context(), err) + log.Info(r.Context(), err) } outAlertActions := make([]domain.AlertActionResponse, len(alert.AlertActions)) for j, alertAction := range alert.AlertActions { if err := serializer.Map(alertAction, &outAlertActions[j]); err != nil { - log.InfoWithContext(r.Context(), err) + log.Info(r.Context(), err) } } out.Alerts[i].AlertActions = outAlertActions @@ -143,7 +143,7 @@ func (h *AlertHandler) GetAlerts(w http.ResponseWriter, r *http.Request) { } if out.Pagination, err = pg.Response(); err != nil { - log.InfoWithContext(r.Context(), err) + log.Info(r.Context(), err) } ResponseJSON(w, r, http.StatusOK, out) @@ -183,12 +183,12 @@ func (h *AlertHandler) GetAlert(w http.ResponseWriter, r *http.Request) { var out domain.GetAlertResponse if err := serializer.Map(alert, &out.Alert); err != nil { - log.InfoWithContext(r.Context(), err) + log.Info(r.Context(), err) } outAlertActions := make([]domain.AlertActionResponse, len(alert.AlertActions)) for j, alertAction := range alert.AlertActions { if err := serializer.Map(alertAction, &outAlertActions[j]); err != nil { - log.InfoWithContext(r.Context(), err) + log.Info(r.Context(), err) continue } } @@ -236,7 +236,7 @@ func (h *AlertHandler) AlertTest(w http.ResponseWriter, r *http.Request) { return } - log.InfoWithContext(r.Context(), "TEST ", body) + log.Info(r.Context(), "TEST ", body) } // CreateAlertAction godoc @@ -271,11 +271,11 @@ func (h *AlertHandler) CreateAlertAction(w http.ResponseWriter, r *http.Request) return } - log.InfoWithContext(r.Context(), "alert : ", helper.ModelToJson(input)) + log.Info(r.Context(), "alert : ", helper.ModelToJson(input)) var dto model.AlertAction if err = serializer.Map(input, &dto); err != nil { - log.InfoWithContext(r.Context(), err) + log.Info(r.Context(), err) } dto.AlertId = alertId diff --git a/internal/delivery/http/app-group.go b/internal/delivery/http/app-group.go index 27543035..180da7be 100644 --- a/internal/delivery/http/app-group.go +++ b/internal/delivery/http/app-group.go @@ -46,7 +46,7 @@ func (h *AppGroupHandler) CreateAppGroup(w http.ResponseWriter, r *http.Request) var dto model.AppGroup if err = serializer.Map(input, &dto); err != nil { - log.InfoWithContext(r.Context(), err) + log.Info(r.Context(), err) } appGroupId, err := h.usecase.Create(r.Context(), dto) @@ -97,13 +97,13 @@ func (h *AppGroupHandler) GetAppGroups(w http.ResponseWriter, r *http.Request) { out.AppGroups = make([]domain.AppGroupResponse, len(appGroups)) for i, appGroup := range appGroups { if err := serializer.Map(appGroup, &out.AppGroups[i]); err != nil { - log.InfoWithContext(r.Context(), err) + log.Info(r.Context(), err) continue } } if out.Pagination, err = pg.Response(); err != nil { - log.InfoWithContext(r.Context(), err) + log.Info(r.Context(), err) } ResponseJSON(w, r, http.StatusOK, out) @@ -140,7 +140,7 @@ func (h *AppGroupHandler) GetAppGroup(w http.ResponseWriter, r *http.Request) { var out domain.GetAppGroupResponse if err := serializer.Map(appGroup, &out.AppGroup); err != nil { - log.InfoWithContext(r.Context(), err) + log.Info(r.Context(), err) } ResponseJSON(w, r, http.StatusOK, out) @@ -226,7 +226,7 @@ func (h *AppGroupHandler) GetApplications(w http.ResponseWriter, r *http.Request out.Applications = make([]domain.ApplicationResponse, len(applications)) for i, application := range applications { if err := serializer.Map(application, &out.Applications[i]); err != nil { - log.InfoWithContext(r.Context(), err) + log.Info(r.Context(), err) continue } } @@ -267,7 +267,7 @@ func (h *AppGroupHandler) CreateApplication(w http.ResponseWriter, r *http.Reque var dto model.Application if err := serializer.Map(input, &dto); err != nil { - log.InfoWithContext(r.Context(), err) + log.Info(r.Context(), err) } dto.AppGroupId = appGroupId diff --git a/internal/delivery/http/app-serve-app.go b/internal/delivery/http/app-serve-app.go index de7cbe7f..d19bcb51 100644 --- a/internal/delivery/http/app-serve-app.go +++ b/internal/delivery/http/app-serve-app.go @@ -274,7 +274,7 @@ func (h *AppServeAppHandler) GetAppServeApps(w http.ResponseWriter, r *http.Requ } if out.Pagination, err = pg.Response(); err != nil { - log.InfoWithContext(r.Context(), err) + log.Info(r.Context(), err) } ResponseJSON(w, r, http.StatusOK, out) @@ -484,7 +484,7 @@ func (h *AppServeAppHandler) GetAppServeAppTasksByAppId(w http.ResponseWriter, r } if out.Pagination, err = pg.Response(); err != nil { - log.InfoWithContext(r.Context(), err) + log.Info(r.Context(), err) } ResponseJSON(w, r, http.StatusOK, out) diff --git a/internal/delivery/http/audit.go b/internal/delivery/http/audit.go index 2a7b2b99..c04b46ea 100644 --- a/internal/delivery/http/audit.go +++ b/internal/delivery/http/audit.go @@ -69,12 +69,12 @@ func (h *AuditHandler) GetAudits(w http.ResponseWriter, r *http.Request) { out.Audits = make([]domain.AuditResponse, len(audits)) for i, audit := range audits { if err := serializer.Map(audit, &out.Audits[i]); err != nil { - log.InfoWithContext(r.Context(), err) + log.Info(r.Context(), err) } } if out.Pagination, err = pg.Response(); err != nil { - log.InfoWithContext(r.Context(), err) + log.Info(r.Context(), err) } ResponseJSON(w, r, http.StatusOK, out) @@ -114,7 +114,7 @@ func (h *AuditHandler) GetAudit(w http.ResponseWriter, r *http.Request) { var out domain.GetAuditResponse if err := serializer.Map(audit, &out.Audit); err != nil { - log.InfoWithContext(r.Context(), err) + log.Info(r.Context(), err) } ResponseJSON(w, r, http.StatusOK, out) diff --git a/internal/delivery/http/cloud-account.go b/internal/delivery/http/cloud-account.go index 5c29a04d..b4a78d3f 100644 --- a/internal/delivery/http/cloud-account.go +++ b/internal/delivery/http/cloud-account.go @@ -56,7 +56,7 @@ func (h *CloudAccountHandler) CreateCloudAccount(w http.ResponseWriter, r *http. var dto model.CloudAccount if err = serializer.Map(input, &dto); err != nil { - log.InfoWithContext(r.Context(), err) + log.Info(r.Context(), err) } dto.OrganizationId = organizationId @@ -108,13 +108,13 @@ func (h *CloudAccountHandler) GetCloudAccounts(w http.ResponseWriter, r *http.Re out.CloudAccounts = make([]domain.CloudAccountResponse, len(cloudAccounts)) for i, cloudAccount := range cloudAccounts { if err := serializer.Map(cloudAccount, &out.CloudAccounts[i]); err != nil { - log.InfoWithContext(r.Context(), err) + log.Info(r.Context(), err) continue } } if out.Pagination, err = pg.Response(); err != nil { - log.InfoWithContext(r.Context(), err) + log.Info(r.Context(), err) } ResponseJSON(w, r, http.StatusOK, out) @@ -154,7 +154,7 @@ func (h *CloudAccountHandler) GetCloudAccount(w http.ResponseWriter, r *http.Req var out domain.GetCloudAccountResponse if err := serializer.Map(cloudAccount, &out.CloudAccount); err != nil { - log.InfoWithContext(r.Context(), err) + log.Info(r.Context(), err) } ResponseJSON(w, r, http.StatusOK, out) @@ -201,7 +201,7 @@ func (h *CloudAccountHandler) UpdateCloudAccount(w http.ResponseWriter, r *http. var dto model.CloudAccount if err = serializer.Map(input, &dto); err != nil { - log.InfoWithContext(r.Context(), err) + log.Info(r.Context(), err) } dto.ID = cloudAccountId dto.OrganizationId = organizationId @@ -251,7 +251,7 @@ func (h *CloudAccountHandler) DeleteCloudAccount(w http.ResponseWriter, r *http. var dto model.CloudAccount if err = serializer.Map(input, &dto); err != nil { - log.InfoWithContext(r.Context(), err) + log.Info(r.Context(), err) } dto.ID = parsedId @@ -417,7 +417,7 @@ func (h *CloudAccountHandler) GetResourceQuota(w http.ResponseWriter, r *http.Re var out domain.GetCloudAccountResourceQuotaResponse if err := serializer.Map(resourceQuota, &out.ResourceQuota); err != nil { - log.InfoWithContext(r.Context(), err) + log.Info(r.Context(), err) } out.Available = available diff --git a/internal/delivery/http/cluster.go b/internal/delivery/http/cluster.go index d0811b04..70cd3d7f 100644 --- a/internal/delivery/http/cluster.go +++ b/internal/delivery/http/cluster.go @@ -55,7 +55,7 @@ func (h *ClusterHandler) GetClusters(w http.ResponseWriter, r *http.Request) { out.Clusters = make([]domain.ClusterResponse, len(clusters)) for i, cluster := range clusters { if err := serializer.Map(cluster, &out.Clusters[i]); err != nil { - log.InfoWithContext(r.Context(), err) + log.Info(r.Context(), err) continue } @@ -68,7 +68,7 @@ func (h *ClusterHandler) GetClusters(w http.ResponseWriter, r *http.Request) { } if out.Pagination, err = pg.Response(); err != nil { - log.InfoWithContext(r.Context(), err) + log.Info(r.Context(), err) } ResponseJSON(w, r, http.StatusOK, out) @@ -101,7 +101,7 @@ func (h *ClusterHandler) GetCluster(w http.ResponseWriter, r *http.Request) { var out domain.GetClusterResponse if err := serializer.Map(cluster, &out.Cluster); err != nil { - log.InfoWithContext(r.Context(), err) + log.Info(r.Context(), err) } ResponseJSON(w, r, http.StatusOK, out) @@ -159,7 +159,7 @@ func (h *ClusterHandler) CreateCluster(w http.ResponseWriter, r *http.Request) { var dto model.Cluster if err = serializer.Map(input, &dto); err != nil { - log.InfoWithContext(r.Context(), err) + log.Info(r.Context(), err) } dto.ClusterType = domain.ClusterType_USER @@ -213,7 +213,7 @@ func (h *ClusterHandler) ImportCluster(w http.ResponseWriter, r *http.Request) { var dto model.Cluster if err = serializer.Map(input, &dto); err != nil { - log.InfoWithContext(r.Context(), err) + log.Info(r.Context(), err) } dto.SetDefaultConf() @@ -872,7 +872,7 @@ func (h *ClusterHandler) SetIstioLabel(w http.ResponseWriter, r *http.Request) { return } - log.InfoWithContext(r.Context(),input) + log.Info(r.Context(),input) if input.Value != "enabled" && input.Value != "disabled" { ErrorJSON(w, r, "invalid value", http.StatusBadRequest) diff --git a/internal/delivery/http/dashboard.go b/internal/delivery/http/dashboard.go index 5a5bdbd1..55c75cd5 100644 --- a/internal/delivery/http/dashboard.go +++ b/internal/delivery/http/dashboard.go @@ -75,7 +75,7 @@ func (h *DashboardHandler) GetCharts(w http.ResponseWriter, r *http.Request) { out.Charts = make([]domain.DashboardChartResponse, len(charts)) for i, chart := range charts { if err := serializer.Map(chart, &out.Charts[i]); err != nil { - log.InfoWithContext(r.Context(), err) + log.Info(r.Context(), err) continue } } @@ -154,7 +154,7 @@ func (h *DashboardHandler) GetChart(w http.ResponseWriter, r *http.Request) { var out domain.DashboardChartResponse if err := serializer.Map(charts[0], &out); err != nil { - log.InfoWithContext(r.Context(), err) + log.Info(r.Context(), err) } ResponseJSON(w, r, http.StatusOK, out) @@ -194,7 +194,7 @@ func (h *DashboardHandler) GetStacks(w http.ResponseWriter, r *http.Request) { out.Stacks = make([]domain.DashboardStackResponse, len(stacks)) for i, stack := range stacks { if err := serializer.Map(stack, &out.Stacks[i]); err != nil { - log.InfoWithContext(r.Context(), err) + log.Info(r.Context(), err) continue } } @@ -232,7 +232,7 @@ func (h *DashboardHandler) GetResources(w http.ResponseWriter, r *http.Request) } var out domain.GetDashboardResourcesResponse if err := serializer.Map(resources, &out.Resources); err != nil { - log.InfoWithContext(r.Context(), err) + log.Info(r.Context(), err) } ResponseJSON(w, r, http.StatusOK, out) diff --git a/internal/delivery/http/organization.go b/internal/delivery/http/organization.go index 77f77841..7433c12c 100644 --- a/internal/delivery/http/organization.go +++ b/internal/delivery/http/organization.go @@ -170,11 +170,11 @@ func (h *OrganizationHandler) GetOrganizations(w http.ResponseWriter, r *http.Re log.ErrorWithContext(r.Context(), err) } - log.InfoWithContext(r.Context(), organization) + log.Info(r.Context(), organization) } if out.Pagination, err = pg.Response(); err != nil { - log.InfoWithContext(r.Context(), err) + log.Info(r.Context(), err) } ResponseJSON(w, r, http.StatusOK, out) diff --git a/internal/delivery/http/project.go b/internal/delivery/http/project.go index 74e0d1f1..5913602b 100644 --- a/internal/delivery/http/project.go +++ b/internal/delivery/http/project.go @@ -190,7 +190,7 @@ func (p ProjectHandler) GetProjects(w http.ResponseWriter, r *http.Request) { var out domain.GetProjectsResponse out.Projects = pr if out.Pagination, err = pg.Response(); err != nil { - log.InfoWithContext(r.Context(), err) + log.Info(r.Context(), err) } if pr == nil { @@ -232,7 +232,7 @@ func (p ProjectHandler) Admin_GetProjects(w http.ResponseWriter, r *http.Request var out domain.GetProjectsResponse out.Projects = pr if out.Pagination, err = pg.Response(); err != nil { - log.InfoWithContext(r.Context(), err) + log.Info(r.Context(), err) } if pr == nil { @@ -765,7 +765,7 @@ func (p ProjectHandler) GetProjectMembers(w http.ResponseWriter, r *http.Request out = domain.GetProjectMembersResponse{ProjectMembers: pmrs} if out.Pagination, err = pg.Response(); err != nil { - log.InfoWithContext(r.Context(), err) + log.Info(r.Context(), err) } ResponseJSON(w, r, http.StatusOK, out) diff --git a/internal/delivery/http/role.go b/internal/delivery/http/role.go index 3ada3dc3..c760b9d2 100644 --- a/internal/delivery/http/role.go +++ b/internal/delivery/http/role.go @@ -144,7 +144,7 @@ func (h RoleHandler) ListTksRoles(w http.ResponseWriter, r *http.Request) { } if err := serializer.Map(*pg, &out.Pagination); err != nil { - log.InfoWithContext(r.Context(), err) + log.Info(r.Context(), err) } // response @@ -321,7 +321,7 @@ func (h RoleHandler) Admin_ListTksRoles(w http.ResponseWriter, r *http.Request) } if err := serializer.Map(*pg, &out.Pagination); err != nil { - log.InfoWithContext(r.Context(), err) + log.Info(r.Context(), err) } // response diff --git a/internal/delivery/http/stack-template.go b/internal/delivery/http/stack-template.go index 724f9907..5eab00fe 100644 --- a/internal/delivery/http/stack-template.go +++ b/internal/delivery/http/stack-template.go @@ -49,7 +49,7 @@ func (h *StackTemplateHandler) CreateStackTemplate(w http.ResponseWriter, r *htt var dto model.StackTemplate if err = serializer.Map(input, &dto); err != nil { - log.InfoWithContext(r.Context(), err) + log.Info(r.Context(), err) } id, err := h.usecase.Create(r.Context(), dto) @@ -92,13 +92,13 @@ func (h *StackTemplateHandler) GetStackTemplates(w http.ResponseWriter, r *http. 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) + log.Info(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) + log.Info(r.Context(), err) continue } } @@ -110,7 +110,7 @@ func (h *StackTemplateHandler) GetStackTemplates(w http.ResponseWriter, r *http. } if out.Pagination, err = pg.Response(); err != nil { - log.InfoWithContext(r.Context(), err) + log.Info(r.Context(), err) } ResponseJSON(w, r, http.StatusOK, out) @@ -149,13 +149,13 @@ func (h *StackTemplateHandler) GetStackTemplate(w http.ResponseWriter, r *http.R var out domain.GetStackTemplateResponse if err := serializer.Map(stackTemplate, &out.StackTemplate); err != nil { - log.InfoWithContext(r.Context(), err) + log.Info(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) + log.Info(r.Context(), err) continue } } @@ -195,7 +195,7 @@ func (h *StackTemplateHandler) UpdateStackTemplate(w http.ResponseWriter, r *htt var dto model.StackTemplate if err := serializer.Map(r, &dto); err != nil { - log.InfoWithContext(r.Context(), err) + log.Info(r.Context(), err) } dto.ID = stackTemplateId @@ -290,7 +290,7 @@ func (h *StackTemplateHandler) UpdateStackTemplateOrganizations(w http.ResponseW var dto model.StackTemplate if err := serializer.Map(input, &dto); err != nil { - log.InfoWithContext(r.Context(), err) + log.Info(r.Context(), err) } dto.ID = stackTemplateId diff --git a/internal/delivery/http/stack.go b/internal/delivery/http/stack.go index 9a40cf22..be985e76 100644 --- a/internal/delivery/http/stack.go +++ b/internal/delivery/http/stack.go @@ -54,7 +54,7 @@ func (h *StackHandler) CreateStack(w http.ResponseWriter, r *http.Request) { var dto model.Stack if err = serializer.Map(input, &dto); err != nil { - log.InfoWithContext(r.Context(), err) + log.Info(r.Context(), err) } dto.OrganizationId = organizationId stackId, err := h.usecase.Create(r.Context(), dto) @@ -123,21 +123,21 @@ func (h *StackHandler) GetStacks(w http.ResponseWriter, r *http.Request) { out.Stacks = make([]domain.StackResponse, len(stacks)) for i, stack := range stacks { if err := serializer.Map(stack, &out.Stacks[i]); err != nil { - log.InfoWithContext(r.Context(), err) + log.Info(r.Context(), err) } if err := serializer.Map(stack.CreatedAt, &out.Stacks[i].CreatedAt); err != nil { - log.InfoWithContext(r.Context(), err) + log.Info(r.Context(), err) } err = json.Unmarshal(stack.StackTemplate.Services, &out.Stacks[i].StackTemplate.Services) if err != nil { - log.InfoWithContext(r.Context(), err) + log.Info(r.Context(), err) } } if out.Pagination, err = pg.Response(); err != nil { - log.InfoWithContext(r.Context(), err) + log.Info(r.Context(), err) } ResponseJSON(w, r, http.StatusOK, out) @@ -171,12 +171,12 @@ func (h *StackHandler) GetStack(w http.ResponseWriter, r *http.Request) { var out domain.GetStackResponse if err := serializer.Map(stack, &out.Stack); err != nil { - log.InfoWithContext(r.Context(), err) + log.Info(r.Context(), err) } err = json.Unmarshal(stack.StackTemplate.Services, &out.Stack.StackTemplate.Services) if err != nil { - log.InfoWithContext(r.Context(), err) + log.Info(r.Context(), err) } ResponseJSON(w, r, http.StatusOK, out) @@ -213,7 +213,7 @@ func (h *StackHandler) GetStackStatus(w http.ResponseWriter, r *http.Request) { out.StepStatus = make([]domain.StackStepStatus, len(steps)) for i, step := range steps { if err := serializer.Map(step, &out.StepStatus[i]); err != nil { - log.InfoWithContext(r.Context(), err) + log.Info(r.Context(), err) } } out.StackStatus = status @@ -262,7 +262,7 @@ func (h *StackHandler) UpdateStack(w http.ResponseWriter, r *http.Request) { var dto model.Stack if err = serializer.Map(input, &dto); err != nil { - log.InfoWithContext(r.Context(), err) + log.Info(r.Context(), err) } dto.ID = stackId dto.OrganizationId = organizationId diff --git a/internal/delivery/http/user.go b/internal/delivery/http/user.go index f7ca4fce..d4c78d14 100644 --- a/internal/delivery/http/user.go +++ b/internal/delivery/http/user.go @@ -217,7 +217,7 @@ func (u UserHandler) List(w http.ResponseWriter, r *http.Request) { } if out.Pagination, err = pg.Response(); err != nil { - log.InfoWithContext(r.Context(), err) + log.Info(r.Context(), err) } ResponseJSON(w, r, http.StatusOK, out) @@ -807,7 +807,7 @@ func (u UserHandler) Admin_List(w http.ResponseWriter, r *http.Request) { } if out.Pagination, err = pg.Response(); err != nil { - log.InfoWithContext(r.Context(), err) + log.Info(r.Context(), err) } ResponseJSON(w, r, http.StatusOK, out) diff --git a/internal/middleware/logging/logging.go b/internal/middleware/logging/logging.go index 3bda0874..da5fcc35 100644 --- a/internal/middleware/logging/logging.go +++ b/internal/middleware/logging/logging.go @@ -17,11 +17,11 @@ func LoggingMiddleware(next http.Handler) http.Handler { ctx := r.Context() r = r.WithContext(context.WithValue(ctx, internal.ContextKeyRequestID, uuid.New().String())) - log.InfoWithContext(r.Context(), fmt.Sprintf("***** START [%s %s] ***** ", r.Method, r.RequestURI)) + log.Infof(r.Context(), fmt.Sprintf("***** START [%s %s] ***** ", r.Method, r.RequestURI)) body, err := io.ReadAll(r.Body) if err == nil { - log.InfoWithContext(r.Context(), fmt.Sprintf("REQUEST BODY : %s", bytes.NewBuffer(body).String())) + log.Infof(r.Context(), fmt.Sprintf("REQUEST BODY : %s", bytes.NewBuffer(body).String())) } r.Body = io.NopCloser(bytes.NewBuffer(body)) lrw := NewLoggingResponseWriter(w) diff --git a/internal/usecase/alert.go b/internal/usecase/alert.go index 01e6929b..f79d7572 100644 --- a/internal/usecase/alert.go +++ b/internal/usecase/alert.go @@ -201,7 +201,7 @@ func (u *AlertUsecase) CreateAlertAction(ctx context.Context, dto model.AlertAct if err != nil { return uuid.Nil, err } - log.InfoWithContext(ctx, "newly created alertActionId:", alertActionId) + log.Info(ctx, "newly created alertActionId:", alertActionId) return } diff --git a/internal/usecase/cloud-account.go b/internal/usecase/cloud-account.go index 26e948e9..484b224a 100644 --- a/internal/usecase/cloud-account.go +++ b/internal/usecase/cloud-account.go @@ -80,7 +80,7 @@ func (u *CloudAccountUsecase) Create(ctx context.Context, dto model.CloudAccount if err != nil { return uuid.Nil, httpErrors.NewInternalServerError(err, "", "") } - log.InfoWithContext(ctx, "newly created CloudAccount ID:", cloudAccountId) + log.Info(ctx, "newly created CloudAccount ID:", cloudAccountId) // FOR TEST. ADD MAGIC KEYWORD if strings.Contains(dto.Name, domain.CLOUD_ACCOUNT_INCLUSTER) { @@ -106,7 +106,7 @@ func (u *CloudAccountUsecase) Create(ctx context.Context, dto model.CloudAccount log.ErrorWithContext(ctx, "failed to submit argo workflow template. err : ", err) return uuid.Nil, fmt.Errorf("Failed to call argo workflow : %s", err) } - log.InfoWithContext(ctx, "submited workflow :", workflowId) + log.Info(ctx, "submited workflow :", workflowId) if err := u.repo.InitWorkflow(ctx, cloudAccountId, workflowId, domain.CloudAccountStatus_CREATING); err != nil { return uuid.Nil, errors.Wrap(err, "Failed to initialize status") @@ -211,7 +211,7 @@ func (u *CloudAccountUsecase) Delete(ctx context.Context, dto model.CloudAccount log.ErrorWithContext(ctx, "failed to submit argo workflow template. err : ", err) return fmt.Errorf("Failed to call argo workflow : %s", err) } - log.InfoWithContext(ctx, "submited workflow :", workflowId) + log.Info(ctx, "submited workflow :", workflowId) if err := u.repo.InitWorkflow(ctx, dto.ID, workflowId, domain.CloudAccountStatus_DELETING); err != nil { return errors.Wrap(err, "Failed to initialize status") @@ -268,7 +268,7 @@ func (u *CloudAccountUsecase) GetResourceQuota(ctx context.Context, cloudAccount stsSvc := sts.NewFromConfig(cfg) if !strings.Contains(cloudAccount.Name, domain.CLOUD_ACCOUNT_INCLUSTER) { - log.InfoWithContext(ctx, "Use assume role. awsAccountId : ", cloudAccount.AwsAccountId) + log.Info(ctx, "Use assume role. awsAccountId : ", cloudAccount.AwsAccountId) creds := stscreds.NewAssumeRoleProvider(stsSvc, "arn:aws:iam::"+cloudAccount.AwsAccountId+":role/controllers.cluster-api-provider-aws.sigs.k8s.io") cfg.Credentials = aws.NewCredentialsCache(creds) } diff --git a/internal/usecase/cluster.go b/internal/usecase/cluster.go index b7f3df01..e0941c2b 100644 --- a/internal/usecase/cluster.go +++ b/internal/usecase/cluster.go @@ -204,7 +204,7 @@ func (u *ClusterUsecase) Create(ctx context.Context, dto model.Cluster) (cluster log.ErrorWithContext(ctx, "failed to submit argo workflow template. err : ", err) return "", err } - log.InfoWithContext(ctx, "Successfully submited workflow: ", workflowId) + log.Info(ctx, "Successfully submited workflow: ", workflowId) if err := u.repo.InitWorkflow(ctx, clusterId, workflowId, domain.ClusterStatus_INSTALLING); err != nil { return "", errors.Wrap(err, "Failed to initialize status") @@ -266,7 +266,7 @@ func (u *ClusterUsecase) Import(ctx context.Context, dto model.Cluster) (cluster log.ErrorWithContext(ctx, "failed to submit argo workflow template. err : ", err) return "", err } - log.InfoWithContext(ctx, "Successfully submited workflow: ", workflowId) + log.Info(ctx, "Successfully submited workflow: ", workflowId) if err := u.repo.InitWorkflow(ctx, clusterId, workflowId, domain.ClusterStatus_INSTALLING); err != nil { return "", errors.Wrap(err, "Failed to initialize status") @@ -313,7 +313,7 @@ func (u *ClusterUsecase) Bootstrap(ctx context.Context, dto model.Cluster) (clus log.ErrorWithContext(ctx, "failed to submit argo workflow template. err : ", err) return "", err } - log.InfoWithContext(ctx, "Successfully submited workflow: ", workflowId) + log.Info(ctx, "Successfully submited workflow: ", workflowId) if err := u.repo.InitWorkflow(ctx, clusterId, workflowId, domain.ClusterStatus_BOOTSTRAPPING); err != nil { return "", errors.Wrap(err, "Failed to initialize status") @@ -365,7 +365,7 @@ func (u *ClusterUsecase) Install(ctx context.Context, clusterId domain.ClusterId log.ErrorWithContext(ctx, "failed to submit argo workflow template. err : ", err) return err } - log.InfoWithContext(ctx, "Successfully submited workflow: ", workflowId) + log.Info(ctx, "Successfully submited workflow: ", workflowId) if err := u.repo.InitWorkflow(ctx, cluster.ID, workflowId, domain.ClusterStatus_INSTALLING); err != nil { return errors.Wrap(err, "Failed to initialize status") @@ -572,7 +572,7 @@ func (u *ClusterUsecase) GetBootstrapKubeconfig(ctx context.Context, clusterId d } token := kubeconfigData.Users[0].User.Token[:6] - log.InfoWithContext(ctx, "token : ", token) + log.Info(ctx, "token : ", token) secrets, err := client.CoreV1().Secrets("kube-system").Get(context.TODO(), "bootstrap-token-"+token, metav1.GetOptions{}) if err != nil { @@ -651,7 +651,7 @@ func (u *ClusterUsecase) GetNodes(ctx context.Context, clusterId domain.ClusterI tksUserNodeRegistered, tksUserNodeRegistering, tksUserHosts := 0, 0, make([]domain.ClusterHost, 0) for _, host := range hosts.Items { label := host.Labels["role"] - log.InfoWithContext(ctx, "label : ", label) + log.Info(ctx, "label : ", label) if len(label) < 12 { continue } diff --git a/internal/usecase/dashboard.go b/internal/usecase/dashboard.go index 99ce9329..dbbbe3af 100644 --- a/internal/usecase/dashboard.go +++ b/internal/usecase/dashboard.go @@ -106,7 +106,7 @@ func (u *DashboardUsecase) GetStacks(ctx context.Context, organizationId string) stack := reflectClusterToStack(cluster, appGroups) dashboardStack := domain.DashboardStack{} if err := serializer.Map(stack, &dashboardStack); err != nil { - log.InfoWithContext(ctx, err) + log.Info(ctx, err) } memory, disk := u.getStackMemoryDisk(stackMemoryDisk.Data.Result, cluster.ID.String()) diff --git a/internal/usecase/organization.go b/internal/usecase/organization.go index 67fa317a..d4096f73 100644 --- a/internal/usecase/organization.go +++ b/internal/usecase/organization.go @@ -81,7 +81,7 @@ func (u *OrganizationUsecase) Create(ctx context.Context, in *model.Organization log.ErrorWithContext(ctx, "failed to submit argo workflow template. err : ", err) return "", errors.Wrap(err, "Failed to call argo workflow") } - log.InfoWithContext(ctx, "submited workflow :", workflowId) + log.Info(ctx, "submited workflow :", workflowId) if err := u.repo.InitWorkflow(ctx, organizationId, workflowId, domain.OrganizationStatus_CREATING); err != nil { return "", errors.Wrap(err, "Failed to init workflow") diff --git a/internal/usecase/stack-template.go b/internal/usecase/stack-template.go index cfc042f9..33dae263 100644 --- a/internal/usecase/stack-template.go +++ b/internal/usecase/stack-template.go @@ -70,7 +70,7 @@ func (u *StackTemplateUsecase) Create(ctx context.Context, dto model.StackTempla if err != nil { return uuid.Nil, httpErrors.NewInternalServerError(err, "", "") } - log.InfoWithContext(ctx, "newly created StackTemplate ID:", stackTemplateId) + log.Info(ctx, "newly created StackTemplate ID:", stackTemplateId) dto.ID = stackTemplateId err = u.UpdateOrganizations(ctx, dto) diff --git a/internal/usecase/stack.go b/internal/usecase/stack.go index 906aa322..ef37b438 100644 --- a/internal/usecase/stack.go +++ b/internal/usecase/stack.go @@ -105,7 +105,7 @@ func (u *StackUsecase) Create(ctx context.Context, dto model.Stack) (stackId dom // Make stack nodes var stackConf domain.StackConfResponse if err = serializer.Map(dto, &stackConf); err != nil { - log.InfoWithContext(ctx, err) + log.Info(ctx, err) } if stackTemplate.CloudService == "AWS" && stackTemplate.KubeType == "AWS" { if stackConf.TksCpNode == 0 { @@ -198,7 +198,7 @@ func (u *StackUsecase) Install(ctx context.Context, stackId domain.StackId) (err // Make stack nodes var stackConf domain.StackConfResponse if err = serializer.Map(cluster, &stackConf); err != nil { - log.InfoWithContext(ctx, err) + log.Info(ctx, err) } workflow := "tks-stack-install" From 08681489e798fa64363c0e519f20d70ba8629bef Mon Sep 17 00:00:00 2001 From: donggyu Date: Tue, 12 Mar 2024 17:50:52 +0900 Subject: [PATCH 06/11] fix conflict during rebase --- internal/delivery/http/alert.go | 2 +- internal/delivery/http/app-group.go | 6 +- internal/delivery/http/app-serve-app.go | 8 +- internal/delivery/http/auth.go | 2 +- internal/delivery/http/cluster.go | 54 ++++----- internal/delivery/http/handler.go | 4 +- internal/delivery/http/organization.go | 10 +- internal/delivery/http/project.go | 38 +++---- internal/delivery/http/stack-template.go | 8 +- internal/delivery/http/user.go | 22 ++-- internal/usecase/alert.go | 6 +- internal/usecase/app-group.go | 4 +- internal/usecase/cloud-account.go | 10 +- internal/usecase/cluster.go | 26 ++--- internal/usecase/dashboard.go | 4 +- internal/usecase/organization.go | 2 +- internal/usecase/project.go | 134 +++++++++++------------ internal/usecase/stack.go | 10 +- 18 files changed, 175 insertions(+), 175 deletions(-) diff --git a/internal/delivery/http/alert.go b/internal/delivery/http/alert.go index 3cc24e7a..4829e8d3 100644 --- a/internal/delivery/http/alert.go +++ b/internal/delivery/http/alert.go @@ -50,7 +50,7 @@ func (h *AlertHandler) CreateAlert(w http.ResponseWriter, r *http.Request) { // webhook 으로 부터 받은 body parse bodyBytes, err := io.ReadAll(r.Body) if err != nil { - log.ErrorWithContext(r.Context(),err) + log.Error(r.Context(),err) } bodyString := string(bodyBytes) log.Info(r.Context(),bodyString) diff --git a/internal/delivery/http/app-group.go b/internal/delivery/http/app-group.go index 180da7be..dd7142a3 100644 --- a/internal/delivery/http/app-group.go +++ b/internal/delivery/http/app-group.go @@ -173,7 +173,7 @@ func (h *AppGroupHandler) DeleteAppGroup(w http.ResponseWriter, r *http.Request) err := h.usecase.Delete(r.Context(), appGroupId) if err != nil { - log.ErrorWithContext(r.Context(), "Failed to delete appGroup err : ", err) + log.Error(r.Context(), "Failed to delete appGroup err : ", err) ErrorJSON(w, r, err) return } @@ -217,7 +217,7 @@ func (h *AppGroupHandler) GetApplications(w http.ResponseWriter, r *http.Request applications, err := h.usecase.GetApplications(r.Context(), appGroupId, applicationType) if err != nil { - log.ErrorWithContext(r.Context(), "Failed to get applications err : ", err) + log.Error(r.Context(), "Failed to get applications err : ", err) ErrorJSON(w, r, err) return } @@ -273,7 +273,7 @@ func (h *AppGroupHandler) CreateApplication(w http.ResponseWriter, r *http.Reque err = h.usecase.UpdateApplication(r.Context(), dto) if err != nil { - log.ErrorWithContext(r.Context(), "Failed to update application err : ", err) + log.Error(r.Context(), "Failed to update application err : ", err) ErrorJSON(w, r, err) return } diff --git a/internal/delivery/http/app-serve-app.go b/internal/delivery/http/app-serve-app.go index d19bcb51..1d66ebf7 100644 --- a/internal/delivery/http/app-serve-app.go +++ b/internal/delivery/http/app-serve-app.go @@ -252,14 +252,14 @@ func (h *AppServeAppHandler) GetAppServeApps(w http.ResponseWriter, r *http.Requ showAll, err := strconv.ParseBool(showAllParam) if err != nil { - log.ErrorWithContext(r.Context(), "Failed to convert showAll params. Err: ", err) + log.Error(r.Context(), "Failed to convert showAll params. Err: ", err) ErrorJSON(w, r, err) return } pg := pagination.NewPagination(&urlParams) apps, err := h.usecase.GetAppServeApps(r.Context(), organizationId, showAll, pg) if err != nil { - log.ErrorWithContext(r.Context(), "Failed to get Failed to get app-serve-apps ", err) + log.Error(r.Context(), "Failed to get Failed to get app-serve-apps ", err) ErrorJSON(w, r, err) return } @@ -469,7 +469,7 @@ func (h *AppServeAppHandler) GetAppServeAppTasksByAppId(w http.ResponseWriter, r tasks, err := h.usecase.GetAppServeAppTasks(r.Context(), appId, pg) if err != nil { - log.ErrorWithContext(r.Context(), "Failed to get app-serve-app-tasks ", err) + log.Error(r.Context(), "Failed to get app-serve-app-tasks ", err) ErrorJSON(w, r, err) return } @@ -984,7 +984,7 @@ func (h *AppServeAppHandler) DeleteAppServeApp(w http.ResponseWriter, r *http.Re res, err := h.usecase.DeleteAppServeApp(r.Context(), appId) if err != nil { - log.ErrorWithContext(r.Context(), "Failed to delete appId err : ", err) + log.Error(r.Context(), "Failed to delete appId err : ", err) ErrorJSON(w, r, err) return } diff --git a/internal/delivery/http/auth.go b/internal/delivery/http/auth.go index 36359785..801c9ec2 100644 --- a/internal/delivery/http/auth.go +++ b/internal/delivery/http/auth.go @@ -98,7 +98,7 @@ func (h *AuthHandler) Login(w http.ResponseWriter, r *http.Request) { var out domain.LoginResponse if err = serializer.Map(user, &out.User); err != nil { - log.ErrorWithContext(r.Context(), err) + log.Error(r.Context(), err) } ResponseJSON(w, r, http.StatusOK, out) diff --git a/internal/delivery/http/cluster.go b/internal/delivery/http/cluster.go index 70cd3d7f..7dea7c9e 100644 --- a/internal/delivery/http/cluster.go +++ b/internal/delivery/http/cluster.go @@ -395,12 +395,12 @@ func (h *ClusterHandler) GetKubernetesInfo(w http.ResponseWriter, r *http.Reques vars := mux.Vars(r) clusterId, ok := vars["clusterId"] if !ok { - log.ErrorWithContext(r.Context(),"Failed to get clusterId") + log.Error(r.Context(),"Failed to get clusterId") } clientset_user, err := h.GetClientFromClusterId(clusterId) if err != nil { - log.ErrorWithContext(r.Context(),"Failed to get clientset for clusterId ", clusterId) + log.Error(r.Context(),"Failed to get clientset for clusterId ", clusterId) InternalServerError(w) return } @@ -414,21 +414,21 @@ func (h *ClusterHandler) GetKubernetesInfo(w http.ResponseWriter, r *http.Reques if err == nil { out.KubeInfo.Pods = len(pods.Items) } else { - log.ErrorWithContext(r.Context(),"Failed to get pods. err : ", err) + log.Error(r.Context(),"Failed to get pods. err : ", err) } nodes, err := clientset_user.CoreV1().Nodes().List(context.TODO(), metav1.ListOptions{}) if err == nil { out.KubeInfo.Nodes = len(nodes.Items) } else { - log.ErrorWithContext(r.Context(),"Failed to get nodes. err : ", err) + log.Error(r.Context(),"Failed to get nodes. err : ", err) } services, err := clientset_user.CoreV1().Services("").List(context.TODO(), metav1.ListOptions{}) if err == nil { out.KubeInfo.Services = len(services.Items) } else { - log.ErrorWithContext(r.Context(),"Failed to get services. err : ", err) + log.Error(r.Context(),"Failed to get services. err : ", err) } @@ -436,7 +436,7 @@ func (h *ClusterHandler) GetKubernetesInfo(w http.ResponseWriter, r *http.Reques if err == nil { out.KubeInfo.Namespaces = len(namespaces.Items) } else { - log.ErrorWithContext(r.Context(),"Failed to get namespaces. err : ", err) + log.Error(r.Context(),"Failed to get namespaces. err : ", err) } @@ -444,7 +444,7 @@ func (h *ClusterHandler) GetKubernetesInfo(w http.ResponseWriter, r *http.Reques if err == nil { out.KubeInfo.Version = version } else { - log.ErrorWithContext(r.Context(),"Failed to get kubernetes version. err : ", err) + log.Error(r.Context(),"Failed to get kubernetes version. err : ", err) } ResponseJSON(w, r, http.StatusOK, out) @@ -465,14 +465,14 @@ func (h *ClusterHandler) GetClusterApplications(w http.ResponseWriter, r *http.R vars := mux.Vars(r) clusterId, ok := vars["clusterId"] if !ok { - log.ErrorWithContext(r.Context(),"Failed to get clusterId") + log.Error(r.Context(),"Failed to get clusterId") ErrorJSON(w, r, "invalid clusterId", http.StatusBadRequest) } var applications = []*pb.AppGroup{} res, err := appInfoClient.GetAppGroupsByClusterID(context.TODO(), &pb.IDRequest{ID: clusterId}) if err != nil { - log.ErrorWithContext(r.Context(),"Failed to get appgroups err : ", err) + log.Error(r.Context(),"Failed to get appgroups err : ", err) InternalServerError(w) return } @@ -497,7 +497,7 @@ func (h *ClusterHandler) GetClusterApplicationsKubeInfo(w http.ResponseWriter, r vars := mux.Vars(r) clusterId, ok := vars["clusterId"] if !ok { - log.ErrorWithContext(r.Context(),"Failed to get clusterId") + log.Error(r.Context(),"Failed to get clusterId") ErrorJSON(w, r, "invalid clusterId", http.StatusBadRequest) } @@ -508,7 +508,7 @@ func (h *ClusterHandler) GetClusterApplicationsKubeInfo(w http.ResponseWriter, r res, err := appInfoClient.GetAppGroupsByClusterID(context.TODO(), &pb.IDRequest{Id: clusterId}) if err != nil { - log.ErrorWithContext(r.Context(),"Failed to get appgroups err : ", err) + log.Error(r.Context(),"Failed to get appgroups err : ", err) InternalServerError(w) return } @@ -525,19 +525,19 @@ func (h *ClusterHandler) GetClusterApplicationsKubeInfo(w http.ResponseWriter, r clientset, err := h.GetClientFromClusterId(appGroup.GetClusterId()) if err != nil { - log.ErrorWithContext(r.Context(),"Failed to get clientset for clusterId", appGroup.GetClusterId()) + log.Error(r.Context(),"Failed to get clientset for clusterId", appGroup.GetClusterId()) continue } pods, err := clientset.CoreV1().Pods(namespace).List(context.TODO(), metav1.ListOptions{}) if err != nil { - log.ErrorWithContext(r.Context(),"Failed to get pods. ", err) + log.Error(r.Context(),"Failed to get pods. ", err) continue } services, err := clientset.CoreV1().Services(namespace).List(context.TODO(), metav1.ListOptions{}) if err != nil { - log.ErrorWithContext(r.Context(),"Failed to get service. ", err) + log.Error(r.Context(),"Failed to get service. ", err) continue } @@ -614,7 +614,7 @@ func (h *ClusterHandler) GetClusterKubeConfig(w http.ResponseWriter, r *http.Req vars := mux.Vars(r) clusterId, ok := vars["clusterId"] if !ok { - log.ErrorWithContext(r.Context(),"Failed to get clusterId") + log.Error(r.Context(),"Failed to get clusterId") ErrorJSON(w, r, "invalid clusterId", http.StatusBadRequest) return } @@ -653,48 +653,48 @@ func (h *ClusterHandler) GetClusterKubeResources(w http.ResponseWriter, r *http. vars := mux.Vars(r) clusterId, ok := vars["clusterId"] if !ok { - log.ErrorWithContext(r.Context(),"Failed to get clusterId") + log.Error(r.Context(),"Failed to get clusterId") ErrorJSON(w, r, "Invalid clusterId", http.StatusBadRequest) } clientset, err := h.GetClientFromClusterId(clusterId) if err != nil { - log.ErrorWithContext(r.Context(),"Failed to get clientset for clusterId", clusterId) + log.Error(r.Context(),"Failed to get clientset for clusterId", clusterId) InternalServerError(w) return } pods, err := clientset.CoreV1().Pods("").List(context.TODO(), metav1.ListOptions{}) if err != nil { - log.ErrorWithContext(r.Context(),"Failed to get pods", err) + log.Error(r.Context(),"Failed to get pods", err) InternalServerError(w) return } services, err := clientset.CoreV1().Services("").List(context.TODO(), metav1.ListOptions{}) if err != nil { - log.ErrorWithContext(r.Context(),"Failed to get services", err) + log.Error(r.Context(),"Failed to get services", err) InternalServerError(w) return } namespaces, err := clientset.CoreV1().Namespaces().List(context.TODO(), metav1.ListOptions{}) if err != nil { - log.ErrorWithContext(r.Context(),"Failed to get namespaces", err) + log.Error(r.Context(),"Failed to get namespaces", err) InternalServerError(w) return } events, err := clientset.CoreV1().Events("").List(context.TODO(), metav1.ListOptions{}) if err != nil { - log.ErrorWithContext(r.Context(),"Failed to get events", err) + log.Error(r.Context(),"Failed to get events", err) InternalServerError(w) return } nodes, err := clientset.CoreV1().Nodes().List(context.TODO(), metav1.ListOptions{}) if err != nil { - log.ErrorWithContext(r.Context(),"Failed to get events", err) + log.Error(r.Context(),"Failed to get events", err) InternalServerError(w) return } @@ -846,13 +846,13 @@ func (h *ClusterHandler) SetIstioLabel(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) clusterId, ok := vars["clusterId"] if !ok { - log.ErrorWithContext(r.Context(),"Failed to get clusterId") + log.Error(r.Context(),"Failed to get clusterId") ErrorJSON(w, r, "invalid clusterId", http.StatusBadRequest) return } namespace, ok := vars["namespace"] if !ok { - log.ErrorWithContext(r.Context(),"Failed to get namespace") + log.Error(r.Context(),"Failed to get namespace") ErrorJSON(w, r, "invalid namespace", http.StatusBadRequest) return } @@ -862,12 +862,12 @@ func (h *ClusterHandler) SetIstioLabel(w http.ResponseWriter, r *http.Request) { } body, err := io.ReadAll(r.Body) if err != nil { - log.ErrorWithContext(r.Context(),err) + log.Error(r.Context(),err) return } err = json.Unmarshal(body, &input) if err != nil { - log.ErrorWithContext(r.Context(),err) + log.Error(r.Context(),err) ErrorJSON(w, r, "invalid json", http.StatusBadRequest) return } @@ -883,7 +883,7 @@ func (h *ClusterHandler) SetIstioLabel(w http.ResponseWriter, r *http.Request) { clientset, err := h.GetClientFromClusterId(clusterId) if err != nil { - log.ErrorWithContext(r.Context(),"Failed to get clientset for clusterId", clusterId) + log.Error(r.Context(),"Failed to get clientset for clusterId", clusterId) InternalServerError(w) return } diff --git a/internal/delivery/http/handler.go b/internal/delivery/http/handler.go index d2b6e180..1fc7de9f 100644 --- a/internal/delivery/http/handler.go +++ b/internal/delivery/http/handler.go @@ -41,7 +41,7 @@ func ResponseJSON(w http.ResponseWriter, r *http.Request, httpStatus int, data i w.WriteHeader(httpStatus) if err := json.NewEncoder(w).Encode(out); err != nil { - log.ErrorWithContext(r.Context(), err) + log.Error(r.Context(), err) } } @@ -110,7 +110,7 @@ func (h *APIHandler) AddHistory(r *http.Request, projectId string, historyType s err := h.Repository.AddHistory(userId, projectId, historyType, description) if err != nil { - log.ErrorWithContext(r.Context(),err) + log.Error(r.Context(),err) return err } diff --git a/internal/delivery/http/organization.go b/internal/delivery/http/organization.go index 7433c12c..69face7e 100644 --- a/internal/delivery/http/organization.go +++ b/internal/delivery/http/organization.go @@ -56,7 +56,7 @@ func (h *OrganizationHandler) CreateOrganization(w http.ResponseWriter, r *http. ctx := r.Context() var organization model.Organization if err = serializer.Map(input, &organization); err != nil { - log.ErrorWithContext(r.Context(), err) + log.Error(r.Context(), err) } organizationId, err := h.usecase.Create(ctx, &organization) @@ -130,7 +130,7 @@ func (h *OrganizationHandler) CreateOrganization(w http.ResponseWriter, r *http. var out domain.CreateOrganizationResponse if err = serializer.Map(organization, &out); err != nil { - log.ErrorWithContext(r.Context(), err) + log.Error(r.Context(), err) } ResponseJSON(w, r, http.StatusOK, out) @@ -167,7 +167,7 @@ func (h *OrganizationHandler) GetOrganizations(w http.ResponseWriter, r *http.Re for i, organization := range *organizations { if err = serializer.Map(organization, &out.Organizations[i]); err != nil { - log.ErrorWithContext(r.Context(), err) + log.Error(r.Context(), err) } log.Info(r.Context(), organization) @@ -212,7 +212,7 @@ func (h *OrganizationHandler) GetOrganization(w http.ResponseWriter, r *http.Req } var out domain.GetOrganizationResponse if err = serializer.Map(organization, &out.Organization); err != nil { - log.ErrorWithContext(r.Context(), err) + log.Error(r.Context(), err) } out.Organization.StackTemplates = make([]domain.SimpleStackTemplateResponse, len(organization.StackTemplates)) @@ -326,7 +326,7 @@ func (h *OrganizationHandler) UpdateOrganization(w http.ResponseWriter, r *http. var out domain.UpdateOrganizationResponse if err = serializer.Map(organization, &out); err != nil { - log.ErrorWithContext(r.Context(), err) + log.Error(r.Context(), err) } ResponseJSON(w, r, http.StatusOK, out) diff --git a/internal/delivery/http/project.go b/internal/delivery/http/project.go index 5913602b..d9215d42 100644 --- a/internal/delivery/http/project.go +++ b/internal/delivery/http/project.go @@ -182,7 +182,7 @@ func (p ProjectHandler) GetProjects(w http.ResponseWriter, r *http.Request) { myUserId := requestUserInfo.GetUserId().String() pr, err := p.usecase.GetProjects(r.Context(), organizationId, myUserId, onlyMyProject, pg) if err != nil { - log.ErrorWithContext(r.Context(), "Failed to retrieve projects ", err) + log.Error(r.Context(), "Failed to retrieve projects ", err) ErrorJSON(w, r, err) return } @@ -224,7 +224,7 @@ func (p ProjectHandler) Admin_GetProjects(w http.ResponseWriter, r *http.Request pg := pagination.NewPagination(&urlParams) pr, err := p.usecase.GetProjects(r.Context(), organizationId, "", false, pg) if err != nil { - log.ErrorWithContext(r.Context(), "Failed to retrieve projects ", err) + log.Error(r.Context(), "Failed to retrieve projects ", err) ErrorJSON(w, r, err) return } @@ -271,14 +271,14 @@ func (p ProjectHandler) GetProject(w http.ResponseWriter, r *http.Request) { project, err := p.usecase.GetProjectWithLeader(r.Context(), organizationId, projectId) if err != nil { - log.ErrorWithContext(r.Context(), "Failed to retrieve project", err) + log.Error(r.Context(), "Failed to retrieve project", err) ErrorJSON(w, r, err) return } //appCount, err := p.usecase.GetAppCount(organizationId, projectId) //if err != nil { - // log.ErrorWithContext(r.Context(), "Failed to retrieve app count", err) + // log.Error(r.Context(), "Failed to retrieve app count", err) // ErrorJSON(w, r, err) // return //} @@ -455,7 +455,7 @@ func (p ProjectHandler) GetProjectRole(w http.ResponseWriter, r *http.Request) { pr, err := p.usecase.GetProjectRole(r.Context(), projectRoleId) if err != nil { - log.ErrorWithContext(r.Context(), "Failed to get project roles ", err) + log.Error(r.Context(), "Failed to get project roles ", err) ErrorJSON(w, r, err) return } @@ -492,7 +492,7 @@ func (p ProjectHandler) GetProjectRoles(w http.ResponseWriter, r *http.Request) } else if strings.EqualFold(queryParam, "viewer") { query = usecase.ProjectViewer } else { - log.ErrorWithContext(r.Context(), "Invalid query params. Err: ") + log.Error(r.Context(), "Invalid query params. Err: ") ErrorJSON(w, r, httpErrors.NewBadRequestError(fmt.Errorf("invalid query params"), "C_INVALID_QUERY_PARAM", "")) return @@ -500,7 +500,7 @@ func (p ProjectHandler) GetProjectRoles(w http.ResponseWriter, r *http.Request) prs, err := p.usecase.GetProjectRoles(r.Context(), query) if err != nil { - log.ErrorWithContext(r.Context(), "Failed to get project roles ", err) + log.Error(r.Context(), "Failed to get project roles ", err) ErrorJSON(w, r, err) return } @@ -653,7 +653,7 @@ func (p ProjectHandler) GetProjectMember(w http.ResponseWriter, r *http.Request) pm, err := p.usecase.GetProjectMember(r.Context(), projectMemberId) if err != nil { - log.ErrorWithContext(r.Context(), "Failed to get project member ", err) + log.Error(r.Context(), "Failed to get project member ", err) ErrorJSON(w, r, err) return } @@ -725,7 +725,7 @@ func (p ProjectHandler) GetProjectMembers(w http.ResponseWriter, r *http.Request } else if strings.EqualFold(queryParam, "viewer") { query = usecase.ProjectViewer } else { - log.ErrorWithContext(r.Context(), "Invalid query params. Err: ") + log.Error(r.Context(), "Invalid query params. Err: ") ErrorJSON(w, r, httpErrors.NewBadRequestError(fmt.Errorf("invalid query params"), "C_INVALID_QUERY_PARAM", "")) return @@ -734,7 +734,7 @@ func (p ProjectHandler) GetProjectMembers(w http.ResponseWriter, r *http.Request pg := pagination.NewPagination(&urlParams) pms, err := p.usecase.GetProjectMembers(r.Context(), projectId, query, pg) if err != nil { - log.ErrorWithContext(r.Context(), "Failed to get project members ", err) + log.Error(r.Context(), "Failed to get project members ", err) ErrorJSON(w, r, err) return } @@ -802,7 +802,7 @@ func (p ProjectHandler) GetProjectMemberCount(w http.ResponseWriter, r *http.Req pmcr, err := p.usecase.GetProjectMemberCount(r.Context(), projectId) if err != nil { - log.ErrorWithContext(r.Context(), "Failed to get project member count", err) + log.Error(r.Context(), "Failed to get project member count", err) ErrorJSON(w, r, err) return } @@ -1285,7 +1285,7 @@ func (p ProjectHandler) GetProjectNamespaces(w http.ResponseWriter, r *http.Requ pg := pagination.NewPagination(&urlParams) pns, err := p.usecase.GetProjectNamespaces(r.Context(), organizationId, projectId, pg) if err != nil { - log.ErrorWithContext(r.Context(), "Failed to get project namespaces.", err) + log.Error(r.Context(), "Failed to get project namespaces.", err) ErrorJSON(w, r, err) return } @@ -1305,7 +1305,7 @@ func (p ProjectHandler) GetProjectNamespaces(w http.ResponseWriter, r *http.Requ } appCount, err := p.usecase.GetAppCount(r.Context(), organizationId, projectId, pn.Namespace) if err != nil { - log.ErrorWithContext(r.Context(), "Failed to retrieve app count", err) + log.Error(r.Context(), "Failed to retrieve app count", err) ErrorJSON(w, r, err) return } @@ -1363,14 +1363,14 @@ func (p ProjectHandler) GetProjectNamespace(w http.ResponseWriter, r *http.Reque pn, err := p.usecase.GetProjectNamespace(r.Context(), organizationId, projectId, projectNamespace, stackId) if err != nil { - log.ErrorWithContext(r.Context(), "Failed to get project namespace.", err) + log.Error(r.Context(), "Failed to get project namespace.", err) ErrorJSON(w, r, err) return } appCount, err := p.usecase.GetAppCount(r.Context(), organizationId, projectId, projectNamespace) if err != nil { - log.ErrorWithContext(r.Context(), "Failed to retrieve app count", err) + log.Error(r.Context(), "Failed to retrieve app count", err) ErrorJSON(w, r, err) return } @@ -1447,7 +1447,7 @@ func (p ProjectHandler) UpdateProjectNamespace(w http.ResponseWriter, r *http.Re now := time.Now() pn, err := p.usecase.GetProjectNamespace(r.Context(), organizationId, projectId, projectNamespace, stackId) if err != nil { - log.ErrorWithContext(r.Context(), "Failed to get project namespace.", err) + log.Error(r.Context(), "Failed to get project namespace.", err) ErrorJSON(w, r, err) return } @@ -1572,7 +1572,7 @@ func (p ProjectHandler) GetProjectKubeconfig(w http.ResponseWriter, r *http.Requ kubeconfig, err := p.usecase.GetProjectKubeconfig(r.Context(), organizationId, projectId) if err != nil { - log.ErrorWithContext(r.Context(), "Failed to get project kubeconfig.", err) + log.Error(r.Context(), "Failed to get project kubeconfig.", err) ErrorJSON(w, r, err) return } @@ -1625,7 +1625,7 @@ func (p ProjectHandler) GetProjectNamespaceK8sResources(w http.ResponseWriter, r k8sResources, err := p.usecase.GetK8sResources(r.Context(), organizationId, projectId, projectNamespace, domain.StackId(stackId)) if err != nil { - log.ErrorWithContext(r.Context(), "Failed to get project resources.", err) + log.Error(r.Context(), "Failed to get project resources.", err) ErrorJSON(w, r, err) return } @@ -1678,7 +1678,7 @@ func (p ProjectHandler) GetProjectNamespaceResourcesUsage(w http.ResponseWriter, resourcesUsage, err := p.usecase.GetResourcesUsage(r.Context(), organizationId, projectId, projectNamespace, domain.StackId(stackId)) if err != nil { - log.ErrorWithContext(r.Context(), "Failed to get project resources.", err) + log.Error(r.Context(), "Failed to get project resources.", err) ErrorJSON(w, r, err) return } diff --git a/internal/delivery/http/stack-template.go b/internal/delivery/http/stack-template.go index 5eab00fe..a03b41fd 100644 --- a/internal/delivery/http/stack-template.go +++ b/internal/delivery/http/stack-template.go @@ -105,7 +105,7 @@ func (h *StackTemplateHandler) GetStackTemplates(w http.ResponseWriter, r *http. err := json.Unmarshal(stackTemplate.Services, &out.StackTemplates[i].Services) if err != nil { - log.ErrorWithContext(r.Context(), err) + log.Error(r.Context(), err) } } @@ -162,7 +162,7 @@ func (h *StackTemplateHandler) GetStackTemplate(w http.ResponseWriter, r *http.R err = json.Unmarshal(stackTemplate.Services, &out.StackTemplate.Services) if err != nil { - log.ErrorWithContext(r.Context(), err) + log.Error(r.Context(), err) } ResponseJSON(w, r, http.StatusOK, out) @@ -245,12 +245,12 @@ func (h *StackTemplateHandler) GetStackTemplateServices(w http.ResponseWriter, r out.Services = make([]domain.StackTemplateServiceResponse, 2) err := json.Unmarshal([]byte(internal.SERVICE_LMA), &out.Services[0]) if err != nil { - log.ErrorWithContext(r.Context(), err) + log.Error(r.Context(), err) } err = json.Unmarshal([]byte(internal.SERVICE_SERVICE_MESH), &out.Services[1]) if err != nil { - log.ErrorWithContext(r.Context(), err) + log.Error(r.Context(), err) } ResponseJSON(w, r, http.StatusOK, out) diff --git a/internal/delivery/http/user.go b/internal/delivery/http/user.go index d4c78d14..bfe4d048 100644 --- a/internal/delivery/http/user.go +++ b/internal/delivery/http/user.go @@ -89,7 +89,7 @@ func (u UserHandler) Create(w http.ResponseWriter, r *http.Request) { ctx := r.Context() var user model.User if err = serializer.Map(input, &user); err != nil { - log.ErrorWithContext(r.Context(), err) + log.Error(r.Context(), err) } user.Organization = model.Organization{ ID: organizationId, @@ -122,7 +122,7 @@ func (u UserHandler) Create(w http.ResponseWriter, r *http.Request) { var out domain.CreateUserResponse if err = serializer.Map(*resUser, &out.User); err != nil { - log.ErrorWithContext(r.Context(), err) + log.Error(r.Context(), err) } ResponseJSON(w, r, http.StatusCreated, out) @@ -169,7 +169,7 @@ func (u UserHandler) Get(w http.ResponseWriter, r *http.Request) { var out domain.GetUserResponse if err = serializer.Map(*user, &out.User); err != nil { - log.ErrorWithContext(r.Context(), err) + log.Error(r.Context(), err) } ResponseJSON(w, r, http.StatusOK, out) @@ -212,7 +212,7 @@ func (u UserHandler) List(w http.ResponseWriter, r *http.Request) { out.Users = make([]domain.ListUserBody, len(*users)) for i, user := range *users { if err = serializer.Map(user, &out.Users[i]); err != nil { - log.ErrorWithContext(r.Context(), err) + log.Error(r.Context(), err) } } @@ -335,7 +335,7 @@ func (u UserHandler) Update(w http.ResponseWriter, r *http.Request) { var out domain.UpdateUserResponse if err = serializer.Map(*resUser, &out.User); err != nil { - log.ErrorWithContext(r.Context(), err) + log.Error(r.Context(), err) ErrorJSON(w, r, err) return } @@ -402,7 +402,7 @@ func (u UserHandler) GetMyProfile(w http.ResponseWriter, r *http.Request) { var out domain.GetMyProfileResponse if err = serializer.Map(*user, &out.User); err != nil { - log.ErrorWithContext(r.Context(), err) + log.Error(r.Context(), err) ErrorJSON(w, r, err) return } @@ -454,7 +454,7 @@ func (u UserHandler) UpdateMyProfile(w http.ResponseWriter, r *http.Request) { ctx := r.Context() var user model.User if err = serializer.Map(input, &user); err != nil { - log.ErrorWithContext(r.Context(), err) + log.Error(r.Context(), err) ErrorJSON(w, r, err) return } @@ -472,7 +472,7 @@ func (u UserHandler) UpdateMyProfile(w http.ResponseWriter, r *http.Request) { var out domain.UpdateMyProfileResponse if err = serializer.Map(*resUser, &out.User); err != nil { - log.ErrorWithContext(r.Context(), err) + log.Error(r.Context(), err) ErrorJSON(w, r, err) return } @@ -802,7 +802,7 @@ func (u UserHandler) Admin_List(w http.ResponseWriter, r *http.Request) { out.Users = make([]domain.ListUserBody, len(*users)) for i, user := range *users { if err = serializer.Map(user, &out.Users[i]); err != nil { - log.ErrorWithContext(r.Context(), err) + log.Error(r.Context(), err) } } @@ -852,7 +852,7 @@ func (u UserHandler) Admin_Get(w http.ResponseWriter, r *http.Request) { var out admin_domain.GetUserResponse if err = serializer.Map(*user, &out.User); err != nil { - log.ErrorWithContext(r.Context(), err) + log.Error(r.Context(), err) } ResponseJSON(w, r, http.StatusOK, out) @@ -1011,7 +1011,7 @@ func (u UserHandler) Admin_Update(w http.ResponseWriter, r *http.Request) { var out admin_domain.UpdateUserResponse if err = serializer.Map(*resUser, &out.User); err != nil { - log.ErrorWithContext(r.Context(), err) + log.Error(r.Context(), err) ErrorJSON(w, r, err) return } diff --git a/internal/usecase/alert.go b/internal/usecase/alert.go index f79d7572..c8397d07 100644 --- a/internal/usecase/alert.go +++ b/internal/usecase/alert.go @@ -60,18 +60,18 @@ func (u *AlertUsecase) Create(ctx context.Context, input domain.CreateAlertReque clusterId := alert.Labels.TacoCluster organizationId, err := u.getOrganizationFromCluster(&allClusters, clusterId) if err != nil { - log.ErrorWithContext(ctx, err) + log.Error(ctx, err) continue } organization, err := u.organizationRepo.Get(ctx, organizationId) if err != nil { - log.ErrorWithContext(ctx, err) + log.Error(ctx, err) continue } primaryCluster, err := u.clusterRepo.Get(ctx, domain.ClusterId(organization.PrimaryClusterId)) if err != nil { - log.ErrorWithContext(ctx, err) + log.Error(ctx, err) continue } diff --git a/internal/usecase/app-group.go b/internal/usecase/app-group.go index d492128d..8bf631ab 100644 --- a/internal/usecase/app-group.go +++ b/internal/usecase/app-group.go @@ -142,13 +142,13 @@ func (u *AppGroupUsecase) Create(ctx context.Context, dto model.AppGroup) (id do workflowTemplate = "tks-service-mesh" default: - log.ErrorWithContext(ctx, "invalid appGroup type ", dto.AppGroupType.String()) + log.Error(ctx, "invalid appGroup type ", dto.AppGroupType.String()) return "", errors.Wrap(err, fmt.Sprintf("Invalid appGroup type. %s", dto.AppGroupType.String())) } workflowId, err := u.argo.SumbitWorkflowFromWftpl(workflowTemplate, opts) if err != nil { - log.ErrorWithContext(ctx, "failed to submit argo workflow template. err : ", err) + log.Error(ctx, "failed to submit argo workflow template. err : ", err) return "", httpErrors.NewInternalServerError(err, "AG_FAILED_TO_CALL_WORKFLOW", "") } diff --git a/internal/usecase/cloud-account.go b/internal/usecase/cloud-account.go index 484b224a..9763c2bd 100644 --- a/internal/usecase/cloud-account.go +++ b/internal/usecase/cloud-account.go @@ -103,7 +103,7 @@ func (u *CloudAccountUsecase) Create(ctx context.Context, dto model.CloudAccount }, }) if err != nil { - log.ErrorWithContext(ctx, "failed to submit argo workflow template. err : ", err) + log.Error(ctx, "failed to submit argo workflow template. err : ", err) return uuid.Nil, fmt.Errorf("Failed to call argo workflow : %s", err) } log.Info(ctx, "submited workflow :", workflowId) @@ -208,7 +208,7 @@ func (u *CloudAccountUsecase) Delete(ctx context.Context, dto model.CloudAccount }, }) if err != nil { - log.ErrorWithContext(ctx, "failed to submit argo workflow template. err : ", err) + log.Error(ctx, "failed to submit argo workflow template. err : ", err) return fmt.Errorf("Failed to call argo workflow : %s", err) } log.Info(ctx, "submited workflow :", workflowId) @@ -251,7 +251,7 @@ func (u *CloudAccountUsecase) GetResourceQuota(ctx context.Context, cloudAccount awsAccessKeyId, awsSecretAccessKey, _ := kubernetes.GetAwsSecret() if err != nil || awsAccessKeyId == "" || awsSecretAccessKey == "" { - log.ErrorWithContext(ctx, err) + log.Error(ctx, err) return false, out, httpErrors.NewInternalServerError(fmt.Errorf("Invalid aws secret."), "", "") } @@ -262,7 +262,7 @@ func (u *CloudAccountUsecase) GetResourceQuota(ctx context.Context, cloudAccount }, })) if err != nil { - log.ErrorWithContext(ctx, err) + log.Error(ctx, err) } stsSvc := sts.NewFromConfig(cfg) @@ -357,7 +357,7 @@ func (u *CloudAccountUsecase) GetResourceQuota(ctx context.Context, cloudAccount o.Region = "ap-northeast-2" }) if err != nil { - log.ErrorWithContext(ctx, err) + log.Error(ctx, err) return false, out, err } currentUsage.EIP = len(res.Addresses) diff --git a/internal/usecase/cluster.go b/internal/usecase/cluster.go index e0941c2b..4fdb01b5 100644 --- a/internal/usecase/cluster.go +++ b/internal/usecase/cluster.go @@ -201,7 +201,7 @@ func (u *ClusterUsecase) Create(ctx context.Context, dto model.Cluster) (cluster }, }) if err != nil { - log.ErrorWithContext(ctx, "failed to submit argo workflow template. err : ", err) + log.Error(ctx, "failed to submit argo workflow template. err : ", err) return "", err } log.Info(ctx, "Successfully submited workflow: ", workflowId) @@ -263,7 +263,7 @@ func (u *ClusterUsecase) Import(ctx context.Context, dto model.Cluster) (cluster }, }) if err != nil { - log.ErrorWithContext(ctx, "failed to submit argo workflow template. err : ", err) + log.Error(ctx, "failed to submit argo workflow template. err : ", err) return "", err } log.Info(ctx, "Successfully submited workflow: ", workflowId) @@ -310,7 +310,7 @@ func (u *ClusterUsecase) Bootstrap(ctx context.Context, dto model.Cluster) (clus }, }) if err != nil { - log.ErrorWithContext(ctx, "failed to submit argo workflow template. err : ", err) + log.Error(ctx, "failed to submit argo workflow template. err : ", err) return "", err } log.Info(ctx, "Successfully submited workflow: ", workflowId) @@ -362,7 +362,7 @@ func (u *ClusterUsecase) Install(ctx context.Context, clusterId domain.ClusterId }, }) if err != nil { - log.ErrorWithContext(ctx, "failed to submit argo workflow template. err : ", err) + log.Error(ctx, "failed to submit argo workflow template. err : ", err) return err } log.Info(ctx, "Successfully submited workflow: ", workflowId) @@ -431,7 +431,7 @@ func (u *ClusterUsecase) Delete(ctx context.Context, clusterId domain.ClusterId) }, }) if err != nil { - log.ErrorWithContext(ctx, "failed to submit argo workflow template. err : ", err) + log.Error(ctx, "failed to submit argo workflow template. err : ", err) return errors.Wrap(err, "Failed to call argo workflow") } @@ -454,7 +454,7 @@ func (u *ClusterUsecase) GetClusterSiteValues(ctx context.Context, clusterId dom out.ClusterRegion = "ap-northeast-2" if err := serializer.Map(cluster, &out); err != nil { - log.ErrorWithContext(ctx, err) + log.Error(ctx, err) } if cluster.StackTemplate.CloudService == "AWS" && cluster.StackTemplate.KubeType == "AWS" { @@ -463,7 +463,7 @@ func (u *ClusterUsecase) GetClusterSiteValues(ctx context.Context, clusterId dom } if err := serializer.Map(cluster, &out); err != nil { - log.ErrorWithContext(ctx, err) + log.Error(ctx, err) } /* @@ -496,7 +496,7 @@ func (u *ClusterUsecase) CreateBootstrapKubeconfig(ctx context.Context, clusterI }, }) if err != nil { - log.ErrorWithContext(ctx, err) + log.Error(ctx, err) return out, httpErrors.NewInternalServerError(err, "S_FAILED_TO_CALL_WORKFLOW", "") } log.DebugWithContext(ctx, "Submitted workflow: ", workflowId) @@ -576,7 +576,7 @@ func (u *ClusterUsecase) GetBootstrapKubeconfig(ctx context.Context, clusterId d secrets, err := client.CoreV1().Secrets("kube-system").Get(context.TODO(), "bootstrap-token-"+token, metav1.GetOptions{}) if err != nil { - log.ErrorWithContext(ctx, err) + log.Error(ctx, err) return out, err } @@ -790,7 +790,7 @@ func (u *ClusterUsecase) constructClusterConf(rawConf *model.ClusterConf) (clust numOfAz = int(rawConf.NumOfAz) if numOfAz > 3 { - log.ErrorWithContext(ctx,"Error: numOfAz cannot exceed 3.") + log.Error(ctx,"Error: numOfAz cannot exceed 3.") temp_err := fmt.Errorf("Error: numOfAz cannot exceed 3.") return nil, temp_err } @@ -823,11 +823,11 @@ func (u *ClusterUsecase) constructClusterConf(rawConf *model.ClusterConf) (clust } if !found { - log.ErrorWithContext(ctx,"Couldn't find entry for region ", region) + log.Error(ctx,"Couldn't find entry for region ", region) } if numOfAz > maxAzForSelectedRegion { - log.ErrorWithContext(ctx,"Invalid numOfAz: exceeded the number of Az in region ", region) + log.Error(ctx,"Invalid numOfAz: exceeded the number of Az in region ", region) temp_err := fmt.Errorf("Invalid numOfAz: exceeded the number of Az in region %s", region) return nil, temp_err } @@ -838,7 +838,7 @@ func (u *ClusterUsecase) constructClusterConf(rawConf *model.ClusterConf) (clust log.DebugWithContext(ctx,"No machineReplicas param. Using default values..") } else { if remainder := replicas % numOfAz; remainder != 0 { - log.ErrorWithContext(ctx,"Invalid machineReplicas: it should be multiple of numOfAz ", numOfAz) + log.Error(ctx,"Invalid machineReplicas: it should be multiple of numOfAz ", numOfAz) temp_err := fmt.Errorf("Invalid machineReplicas: it should be multiple of numOfAz %d", numOfAz) return nil, temp_err } else { diff --git a/internal/usecase/dashboard.go b/internal/usecase/dashboard.go index dbbbe3af..0e40c7d2 100644 --- a/internal/usecase/dashboard.go +++ b/internal/usecase/dashboard.go @@ -80,7 +80,7 @@ func (u *DashboardUsecase) GetStacks(ctx context.Context, organizationId string) thanosUrl, err := u.getThanosUrl(ctx, organizationId) if err != nil { - log.ErrorWithContext(ctx, err) + log.Error(ctx, err) return out, httpErrors.NewInternalServerError(err, "D_INVALID_PRIMARY_STACK", "") } address, port := helper.SplitAddress(thanosUrl) @@ -139,7 +139,7 @@ func (u *DashboardUsecase) GetStacks(ctx context.Context, organizationId string) func (u *DashboardUsecase) GetResources(ctx context.Context, organizationId string) (out domain.DashboardResource, err error) { thanosUrl, err := u.getThanosUrl(ctx, organizationId) if err != nil { - log.ErrorWithContext(ctx, err) + log.Error(ctx, err) return out, httpErrors.NewInternalServerError(err, "D_INVALID_PRIMARY_STACK", "") } address, port := helper.SplitAddress(thanosUrl) diff --git a/internal/usecase/organization.go b/internal/usecase/organization.go index d4096f73..72d30e3c 100644 --- a/internal/usecase/organization.go +++ b/internal/usecase/organization.go @@ -78,7 +78,7 @@ func (u *OrganizationUsecase) Create(ctx context.Context, in *model.Organization }, }) if err != nil { - log.ErrorWithContext(ctx, "failed to submit argo workflow template. err : ", err) + log.Error(ctx, "failed to submit argo workflow template. err : ", err) return "", errors.Wrap(err, "Failed to call argo workflow") } log.Info(ctx, "submited workflow :", workflowId) diff --git a/internal/usecase/project.go b/internal/usecase/project.go index 8422338a..b3d0e1a3 100644 --- a/internal/usecase/project.go +++ b/internal/usecase/project.go @@ -89,7 +89,7 @@ func NewProjectUsecase(r repository.Repository, kc keycloak.IKeycloak, argoClien func (u *ProjectUsecase) CreateProject(ctx context.Context, p *model.Project) (string, error) { projectId, err := u.projectRepo.CreateProject(ctx, p) if err != nil { - log.ErrorWithContext(ctx, err) + log.Error(ctx, err) return "", errors.Wrap(err, "Failed to create project.") } @@ -102,7 +102,7 @@ func (u *ProjectUsecase) GetProjects(ctx context.Context, organizationId string, } else { userUuid, err := uuid.Parse(userId) if err != nil { - log.ErrorWithContext(ctx, err) + log.Error(ctx, err) return nil, errors.Wrap(err, "Failed to parse uuid to string") } if onlyMyProject == false { @@ -112,7 +112,7 @@ func (u *ProjectUsecase) GetProjects(ctx context.Context, organizationId string, } } if err != nil { - log.ErrorWithContext(ctx, err) + log.Error(ctx, err) return nil, errors.Wrap(err, "Failed to get projects.") } @@ -122,7 +122,7 @@ func (u *ProjectUsecase) GetProjects(ctx context.Context, organizationId string, func (u *ProjectUsecase) GetProject(ctx context.Context, organizationId string, projectId string) (*model.Project, error) { p, err := u.projectRepo.GetProjectById(ctx, organizationId, projectId) if err != nil { - log.ErrorWithContext(ctx, err) + log.Error(ctx, err) return nil, errors.Wrap(err, "Failed to get projects.") } return p, err @@ -131,7 +131,7 @@ func (u *ProjectUsecase) GetProject(ctx context.Context, organizationId string, func (u *ProjectUsecase) GetProjectWithLeader(ctx context.Context, organizationId string, projectId string) (*model.Project, error) { p, err := u.projectRepo.GetProjectByIdAndLeader(ctx, organizationId, projectId) if err != nil { - log.ErrorWithContext(ctx, err) + log.Error(ctx, err) return nil, errors.Wrap(err, "Failed to get projects.") } return p, err @@ -141,7 +141,7 @@ func (u *ProjectUsecase) IsProjectNameExist(ctx context.Context, organizationId exist := true p, err := u.projectRepo.GetProjectByName(ctx, organizationId, projectName) if err != nil { - log.ErrorWithContext(ctx, err) + log.Error(ctx, err) exist = false return exist, errors.Wrap(err, "Failed to retrieve project name.") } @@ -163,13 +163,13 @@ func (u *ProjectUsecase) UpdateProject(ctx context.Context, p *model.Project, ne p.ProjectMembers = nil if err := u.projectRepo.UpdateProject(ctx, p); err != nil { - log.ErrorWithContext(ctx, err) + log.Error(ctx, err) return errors.Wrap(err, "Failed to update project.") } if newLeaderId != "" && currentLeaderId != newLeaderId { if err := u.RemoveProjectMember(ctx, currentMemberId); err != nil { - log.ErrorWithContext(ctx, err) + log.Error(ctx, err) return errors.Wrap(err, "Failed to remove project member.") } @@ -220,7 +220,7 @@ func (u *ProjectUsecase) UpdateProject(ctx context.Context, p *model.Project, ne func (u *ProjectUsecase) GetProjectRole(ctx context.Context, id string) (*model.ProjectRole, error) { pr, err := u.projectRepo.GetProjectRoleById(ctx, id) if err != nil { - log.ErrorWithContext(ctx, err) + log.Error(ctx, err) return nil, errors.Wrap(err, "Failed to get project roles.") } @@ -240,7 +240,7 @@ func (u *ProjectUsecase) GetProjectRoles(ctx context.Context, query int) (prs [] prs, err = u.projectRepo.GetAllProjectRoles(ctx) } if err != nil { - log.ErrorWithContext(ctx, err) + log.Error(ctx, err) return nil, errors.Wrap(err, "Failed to get project roles.") } @@ -254,7 +254,7 @@ func (u *ProjectUsecase) GetProjectRoles(ctx context.Context, query int) (prs [] func (u *ProjectUsecase) AddProjectMember(ctx context.Context, pm *model.ProjectMember) (string, error) { projectMemberId, err := u.projectRepo.AddProjectMember(ctx, pm) if err != nil { - log.ErrorWithContext(ctx, err) + log.Error(ctx, err) return "", errors.Wrap(err, "Failed to add project member to project.") } return projectMemberId, nil @@ -264,18 +264,18 @@ func (u *ProjectUsecase) GetProjectUser(ctx context.Context, projectUserId strin var uid uuid.UUID uid, err := uuid.Parse(projectUserId) if err != nil { - log.ErrorWithContext(ctx, err) + log.Error(ctx, err) return nil, errors.Wrap(err, "Failed to parse uuid to string") } user, err := u.userRepository.GetByUuid(ctx, uid) if err != nil { - log.ErrorWithContext(ctx, err) + log.Error(ctx, err) return nil, errors.Wrap(err, "Failed to retrieve user by id") } var pu model.ProjectUser if err = serializer.Map(user, &pu); err != nil { - log.ErrorWithContext(ctx, err) + log.Error(ctx, err) return nil, err } return &pu, nil @@ -284,7 +284,7 @@ func (u *ProjectUsecase) GetProjectUser(ctx context.Context, projectUserId strin func (u *ProjectUsecase) GetProjectMember(ctx context.Context, projectMemberId string) (pm *model.ProjectMember, err error) { pm, err = u.projectRepo.GetProjectMemberById(ctx, projectMemberId) if err != nil { - log.ErrorWithContext(ctx, err) + log.Error(ctx, err) return pm, errors.Wrap(err, "Failed to get project member.") } @@ -302,7 +302,7 @@ func (u *ProjectUsecase) GetProjectMembers(ctx context.Context, projectId string pms, err = u.projectRepo.GetProjectMembersByProjectId(ctx, projectId, pg) } if err != nil { - log.ErrorWithContext(ctx, err) + log.Error(ctx, err) return nil, errors.Wrap(err, "Failed to get project members.") } @@ -312,7 +312,7 @@ func (u *ProjectUsecase) GetProjectMembers(ctx context.Context, projectId string func (u *ProjectUsecase) GetProjectMemberCount(ctx context.Context, projectMemberId string) (pmcr *domain.GetProjectMemberCountResponse, err error) { pmcr, err = u.projectRepo.GetProjectMemberCountByProjectId(ctx, projectMemberId) if err != nil { - log.ErrorWithContext(ctx, err) + log.Error(ctx, err) return pmcr, errors.Wrap(err, "Failed to get project member count.") } @@ -321,7 +321,7 @@ func (u *ProjectUsecase) GetProjectMemberCount(ctx context.Context, projectMembe func (u *ProjectUsecase) RemoveProjectMember(ctx context.Context, projectMemberId string) error { if err := u.projectRepo.RemoveProjectMember(ctx, projectMemberId); err != nil { - log.ErrorWithContext(ctx, err) + log.Error(ctx, err) return errors.Wrap(err, "Failed to remove project member to project.") } return nil @@ -330,7 +330,7 @@ func (u *ProjectUsecase) RemoveProjectMember(ctx context.Context, projectMemberI func (u *ProjectUsecase) UpdateProjectMemberRole(ctx context.Context, pm *model.ProjectMember) error { if err := u.projectRepo.UpdateProjectMemberRole(ctx, pm); err != nil { - log.ErrorWithContext(ctx, err) + log.Error(ctx, err) return errors.Wrap(err, "Failed to remove project member to project.") } return nil @@ -338,7 +338,7 @@ func (u *ProjectUsecase) UpdateProjectMemberRole(ctx context.Context, pm *model. func (u *ProjectUsecase) CreateProjectNamespace(ctx context.Context, organizationId string, pn *model.ProjectNamespace) error { if err := u.projectRepo.CreateProjectNamespace(ctx, organizationId, pn); err != nil { - log.ErrorWithContext(ctx, err) + log.Error(ctx, err) return errors.Wrap(err, "Failed to create project namespace.") } return nil @@ -348,7 +348,7 @@ func (u *ProjectUsecase) IsProjectNamespaceExist(ctx context.Context, organizati exist := true pn, err := u.projectRepo.GetProjectNamespaceByName(ctx, organizationId, projectId, stackId, projectNamespace) if err != nil { - log.ErrorWithContext(ctx, err) + log.Error(ctx, err) exist = false return exist, errors.Wrap(err, "Failed to retrieve project namespace.") } @@ -361,7 +361,7 @@ func (u *ProjectUsecase) IsProjectNamespaceExist(ctx context.Context, organizati func (u *ProjectUsecase) GetProjectNamespaces(ctx context.Context, organizationId string, projectId string, pg *pagination.Pagination) ([]model.ProjectNamespace, error) { pns, err := u.projectRepo.GetProjectNamespaces(ctx, organizationId, projectId, pg) if err != nil { - log.ErrorWithContext(ctx, err) + log.Error(ctx, err) return nil, errors.Wrap(err, "Failed to retrieve project namespaces.") } @@ -371,7 +371,7 @@ func (u *ProjectUsecase) GetProjectNamespaces(ctx context.Context, organizationI func (u *ProjectUsecase) GetProjectNamespace(ctx context.Context, organizationId string, projectId string, projectNamespace string, stackId string) (*model.ProjectNamespace, error) { pn, err := u.projectRepo.GetProjectNamespaceByPrimaryKey(ctx, organizationId, projectId, projectNamespace, stackId) if err != nil { - log.ErrorWithContext(ctx, err) + log.Error(ctx, err) return nil, errors.Wrap(err, "Failed to retrieve project namespace.") } @@ -380,7 +380,7 @@ func (u *ProjectUsecase) GetProjectNamespace(ctx context.Context, organizationId func (u *ProjectUsecase) UpdateProjectNamespace(ctx context.Context, pn *model.ProjectNamespace) error { if err := u.projectRepo.UpdateProjectNamespace(ctx, pn); err != nil { - log.ErrorWithContext(ctx, err) + log.Error(ctx, err) return errors.Wrap(err, "Failed to update project namespace") } return nil @@ -389,7 +389,7 @@ func (u *ProjectUsecase) UpdateProjectNamespace(ctx context.Context, pn *model.P func (u *ProjectUsecase) DeleteProjectNamespace(ctx context.Context, organizationId string, projectId string, stackId string, projectNamespace string) error { if err := u.projectRepo.DeleteProjectNamespace(ctx, organizationId, projectId, projectNamespace, stackId); err != nil { - log.ErrorWithContext(ctx, err) + log.Error(ctx, err) return errors.Wrap(err, "Failed to delete project namespace.") } return nil @@ -402,7 +402,7 @@ func (u *ProjectUsecase) GetAppCount(ctx context.Context, organizationId string, appCount, err = u.projectRepo.GetAppCountByNamespace(ctx, organizationId, projectId, namespace) } if err != nil { - log.ErrorWithContext(ctx, err) + log.Error(ctx, err) return 0, errors.Wrap(err, "Failed to retrieve app count.") } @@ -412,7 +412,7 @@ func (u *ProjectUsecase) GetAppCount(ctx context.Context, organizationId string, func (u *ProjectUsecase) EnsureRequiredSetupForCluster(ctx context.Context, organizationId string, projectId string, stackId string) error { pns, err := u.projectRepo.GetProjectNamespaces(ctx, organizationId, projectId, nil) if err != nil { - log.ErrorWithContext(ctx, err) + log.Error(ctx, err) return errors.Wrap(err, "Failed to create project namespace.") } @@ -430,24 +430,24 @@ func (u *ProjectUsecase) EnsureRequiredSetupForCluster(ctx context.Context, orga } if err := u.createK8SInitialResource(ctx, organizationId, projectId, stackId); err != nil { - log.ErrorWithContext(ctx, err) + log.Error(ctx, err) return errors.Wrap(err, "Failed to create project namespace.") } if err := u.createKeycloakClientRoles(ctx, organizationId, projectId, stackId); err != nil { - log.ErrorWithContext(ctx, err) + log.Error(ctx, err) return errors.Wrap(err, "Failed to create project namespace.") } projectMembers, err := u.GetProjectMembers(ctx, projectId, ProjectAll, nil) if err != nil { - log.ErrorWithContext(ctx, err) + log.Error(ctx, err) return errors.Wrap(err, "Failed to create project namespace.") } for _, pm := range projectMembers { err = u.assignEachKeycloakClientRoleToMember(ctx, organizationId, projectId, stackId, pm.ProjectUserId.String(), pm.ProjectRole.Name) if err != nil { - log.ErrorWithContext(ctx, err) + log.Error(ctx, err) return errors.Wrap(err, "Failed to create project namespace.") } } @@ -457,7 +457,7 @@ func (u *ProjectUsecase) EnsureRequiredSetupForCluster(ctx context.Context, orga func (u *ProjectUsecase) MayRemoveRequiredSetupForCluster(ctx context.Context, organizationId string, projectId string, stackId string) error { pns, err := u.projectRepo.GetProjectNamespaces(ctx, organizationId, projectId, nil) if err != nil { - log.ErrorWithContext(ctx, err) + log.Error(ctx, err) return errors.Wrap(err, "Failed to create project namespace.") } var nsCount int @@ -473,25 +473,25 @@ func (u *ProjectUsecase) MayRemoveRequiredSetupForCluster(ctx context.Context, o } if err := u.deleteK8SInitialResource(ctx, organizationId, projectId, stackId); err != nil { - log.ErrorWithContext(ctx, err) + log.Error(ctx, err) return errors.Wrap(err, "Failed to create project namespace.") } projectMembers, err := u.GetProjectMembers(ctx, projectId, ProjectAll, nil) if err != nil { - log.ErrorWithContext(ctx, err) + log.Error(ctx, err) return errors.Wrap(err, "Failed to create project namespace.") } for _, pm := range projectMembers { err = u.unassignKeycloakClientRoleToMember(ctx, organizationId, projectId, stackId, pm.ProjectUserId.String(), pm.ProjectRole.Name) if err != nil { - log.ErrorWithContext(ctx, err) + log.Error(ctx, err) return errors.Wrap(err, "Failed to create project namespace.") } } if err := u.deleteKeycloakClientRoles(ctx, organizationId, projectId, stackId); err != nil { - log.ErrorWithContext(ctx, err) + log.Error(ctx, err) return errors.Wrap(err, "Failed to create project namespace.") } @@ -500,31 +500,31 @@ func (u *ProjectUsecase) MayRemoveRequiredSetupForCluster(ctx context.Context, o func (u *ProjectUsecase) createK8SInitialResource(ctx context.Context, organizationId string, projectId string, stackId string) error { kubeconfig, err := kubernetes.GetKubeConfig(stackId) if err != nil { - log.ErrorWithContext(ctx, err) + log.Error(ctx, err) return errors.Wrap(err, "Failed to create project namespace.") } pr, err := u.GetProject(ctx, organizationId, projectId) if err != nil { - log.ErrorWithContext(ctx, err) + log.Error(ctx, err) return errors.Wrap(err, "Failed to create project namespace.") } err = kubernetes.EnsureClusterRole(kubeconfig, pr.Name) if err != nil { - log.ErrorWithContext(ctx, err) + log.Error(ctx, err) return errors.Wrap(err, "Failed to create project namespace.") } err = kubernetes.EnsureCommonClusterRole(kubeconfig, pr.Name) if err != nil { - log.ErrorWithContext(ctx, err) + log.Error(ctx, err) return errors.Wrap(err, "Failed to create project namespace.") } err = kubernetes.EnsureCommonClusterRoleBinding(kubeconfig, pr.Name) if err != nil { - log.ErrorWithContext(ctx, err) + log.Error(ctx, err) return errors.Wrap(err, "Failed to create project namespace.") } @@ -533,31 +533,31 @@ func (u *ProjectUsecase) createK8SInitialResource(ctx context.Context, organizat func (u *ProjectUsecase) deleteK8SInitialResource(ctx context.Context, organizationId string, projectId string, stackId string) error { kubeconfig, err := kubernetes.GetKubeConfig(stackId) if err != nil { - log.ErrorWithContext(ctx, err) + log.Error(ctx, err) return errors.Wrap(err, "Failed to create project namespace.") } pr, err := u.GetProject(ctx, organizationId, projectId) if err != nil { - log.ErrorWithContext(ctx, err) + log.Error(ctx, err) return errors.Wrap(err, "Failed to create project namespace.") } err = kubernetes.RemoveClusterRole(kubeconfig, pr.Name) if err != nil { - log.ErrorWithContext(ctx, err) + log.Error(ctx, err) return errors.Wrap(err, "Failed to create project namespace.") } err = kubernetes.RemoveCommonClusterRole(kubeconfig, pr.Name) if err != nil { - log.ErrorWithContext(ctx, err) + log.Error(ctx, err) return errors.Wrap(err, "Failed to create project namespace.") } err = kubernetes.RemoveCommonClusterRoleBinding(kubeconfig, pr.Name) if err != nil { - log.ErrorWithContext(ctx, err) + log.Error(ctx, err) return errors.Wrap(err, "Failed to create project namespace.") } @@ -568,7 +568,7 @@ func (u *ProjectUsecase) createKeycloakClientRoles(ctx context.Context, organiza for _, role := range []string{strconv.Itoa(ProjectLeader), strconv.Itoa(ProjectMember), strconv.Itoa(ProjectViewer)} { err := u.kc.EnsureClientRoleWithClientName(organizationId, stackId+"-k8s-api", role+"@"+projectId) if err != nil { - log.ErrorWithContext(ctx, err) + log.Error(ctx, err) return errors.Wrap(err, "Failed to create project namespace.") } } @@ -581,7 +581,7 @@ func (u *ProjectUsecase) deleteKeycloakClientRoles(ctx context.Context, organiza for _, role := range []string{strconv.Itoa(ProjectLeader), strconv.Itoa(ProjectMember), strconv.Itoa(ProjectViewer)} { err := u.kc.DeleteClientRoleWithClientName(organizationId, stackId+"-k8s-api", role+"@"+projectId) if err != nil { - log.ErrorWithContext(ctx, err) + log.Error(ctx, err) return errors.Wrap(err, "Failed to create project namespace.") } } @@ -590,19 +590,19 @@ func (u *ProjectUsecase) deleteKeycloakClientRoles(ctx context.Context, organiza func (u *ProjectUsecase) CreateK8SNSRoleBinding(ctx context.Context, organizationId string, projectId string, stackId string, namespace string) error { kubeconfig, err := kubernetes.GetKubeConfig(stackId) if err != nil { - log.ErrorWithContext(ctx, err) + log.Error(ctx, err) return errors.Wrap(err, "Failed to create project namespace.") } pr, err := u.GetProject(ctx, organizationId, projectId) if err != nil { - log.ErrorWithContext(ctx, err) + log.Error(ctx, err) return errors.Wrap(err, "Failed to create project namespace.") } err = kubernetes.EnsureRoleBinding(kubeconfig, pr.Name, namespace) if err != nil { - log.ErrorWithContext(ctx, err) + log.Error(ctx, err) return errors.Wrap(err, "Failed to create project namespace.") } @@ -616,7 +616,7 @@ func (u *ProjectUsecase) DeleteK8SNSRoleBinding(ctx context.Context, organizatio func (u *ProjectUsecase) AssignKeycloakClientRoleToMember(ctx context.Context, organizationId string, projectId string, stackId string, projectMemberId string) error { pm, err := u.GetProjectMember(ctx, projectMemberId) if err != nil { - log.ErrorWithContext(ctx, err) + log.Error(ctx, err) return errors.Wrap(err, "Failed to create project namespace.") } err = u.assignEachKeycloakClientRoleToMember(ctx, organizationId, projectId, stackId, pm.ProjectUserId.String(), pm.ProjectRole.Name) @@ -626,7 +626,7 @@ func (u *ProjectUsecase) AssignKeycloakClientRoleToMember(ctx context.Context, o func (u *ProjectUsecase) assignEachKeycloakClientRoleToMember(ctx context.Context, organizationId string, projectId string, stackId string, userId string, roleName string) error { err := u.kc.AssignClientRoleToUser(organizationId, userId, stackId+"-k8s-api", roleName+"@"+projectId) if err != nil { - log.ErrorWithContext(ctx, err) + log.Error(ctx, err) return errors.Wrap(err, "Failed to create project namespace.") } return nil @@ -635,7 +635,7 @@ func (u *ProjectUsecase) assignEachKeycloakClientRoleToMember(ctx context.Contex func (u *ProjectUsecase) UnassignKeycloakClientRoleToMember(ctx context.Context, organizationId string, projectId string, stackId string, projectMemberId string) error { pm, err := u.GetProjectMember(ctx, projectMemberId) if err != nil { - log.ErrorWithContext(ctx, err) + log.Error(ctx, err) return errors.Wrap(err, "Failed to create project namespace.") } err = u.unassignKeycloakClientRoleToMember(ctx, organizationId, projectId, stackId, pm.ProjectUserId.String(), pm.ProjectRole.Name) @@ -645,7 +645,7 @@ func (u *ProjectUsecase) UnassignKeycloakClientRoleToMember(ctx context.Context, func (u *ProjectUsecase) unassignKeycloakClientRoleToMember(ctx context.Context, organizationId string, projectId string, stackId string, userId string, roleName string) error { err := u.kc.UnassignClientRoleToUser(organizationId, userId, stackId+"-k8s-api", roleName+"@"+projectId) if err != nil { - log.ErrorWithContext(ctx, err) + log.Error(ctx, err) return errors.Wrap(err, "Failed to create project namespace.") } return nil @@ -654,7 +654,7 @@ func (u *ProjectUsecase) unassignKeycloakClientRoleToMember(ctx context.Context, func (u *ProjectUsecase) GetProjectKubeconfig(ctx context.Context, organizationId string, projectId string) (string, error) { projectNamespaces, err := u.projectRepo.GetProjectNamespaces(ctx, organizationId, projectId, nil) if err != nil { - log.ErrorWithContext(ctx, err) + log.Error(ctx, err) return "", errors.Wrap(err, "Failed to retrieve project namespaces.") } @@ -684,21 +684,21 @@ func (u *ProjectUsecase) GetProjectKubeconfig(ctx context.Context, organizationI for _, pn := range projectNamespaces { kubeconfig, err := kubernetes.GetKubeConfig(pn.StackId) if err != nil { - log.ErrorWithContext(ctx, err) + log.Error(ctx, err) return "", errors.Wrap(err, "Failed to retrieve kubeconfig.") } var config kubeConfigType err = yaml.Unmarshal(kubeconfig, &config) if err != nil { - log.ErrorWithContext(ctx, err) + log.Error(ctx, err) return "", errors.Wrap(err, "Failed to unmarshal kubeconfig.") } config.Contexts[0].Context.Namespace = pn.Namespace kubeconfig, err = yaml.Marshal(config) if err != nil { - log.ErrorWithContext(ctx, err) + log.Error(ctx, err) return "", errors.Wrap(err, "Failed to marshal kubeconfig.") } @@ -725,56 +725,56 @@ func (u *ProjectUsecase) GetK8sResources(ctx context.Context, organizationId str if err == nil { out.Pods = len(pods.Items) } else { - log.ErrorWithContext(ctx, "Failed to get pods. err : ", err) + log.Error(ctx, "Failed to get pods. err : ", err) } pvcs, err := clientset_user.CoreV1().PersistentVolumeClaims(namespace).List(ctx, metav1.ListOptions{}) if err == nil { out.PVCs = len(pvcs.Items) } else { - log.ErrorWithContext(ctx, "Failed to get pvcs. err : ", err) + log.Error(ctx, "Failed to get pvcs. err : ", err) } services, err := clientset_user.CoreV1().Services(namespace).List(ctx, metav1.ListOptions{}) if err == nil { out.Services = len(services.Items) } else { - log.ErrorWithContext(ctx, "Failed to get services. err : ", err) + log.Error(ctx, "Failed to get services. err : ", err) } ingresses, err := clientset_user.NetworkingV1().Ingresses(namespace).List(ctx, metav1.ListOptions{}) if err == nil { out.Ingresses = len(ingresses.Items) } else { - log.ErrorWithContext(ctx, "Failed to get ingresses. err : ", err) + log.Error(ctx, "Failed to get ingresses. err : ", err) } deployments, err := clientset_user.AppsV1().Deployments(namespace).List(ctx, metav1.ListOptions{}) if err == nil { out.Deployments = len(deployments.Items) } else { - log.ErrorWithContext(ctx, "Failed to get deployments. err : ", err) + log.Error(ctx, "Failed to get deployments. err : ", err) } statefulsets, err := clientset_user.AppsV1().StatefulSets(namespace).List(ctx, metav1.ListOptions{}) if err == nil { out.Statefulsets = len(statefulsets.Items) } else { - log.ErrorWithContext(ctx, "Failed to get statefulsets. err : ", err) + log.Error(ctx, "Failed to get statefulsets. err : ", err) } daemonsets, err := clientset_user.AppsV1().DaemonSets(namespace).List(ctx, metav1.ListOptions{}) if err == nil { out.Daemonsets = len(daemonsets.Items) } else { - log.ErrorWithContext(ctx, "Failed to get daemonsets. err : ", err) + log.Error(ctx, "Failed to get daemonsets. err : ", err) } jobs, err := clientset_user.BatchV1().Jobs(namespace).List(ctx, metav1.ListOptions{}) if err == nil { out.Jobs = len(jobs.Items) } else { - log.ErrorWithContext(ctx, "Failed to get jobs. err : ", err) + log.Error(ctx, "Failed to get jobs. err : ", err) } return diff --git a/internal/usecase/stack.go b/internal/usecase/stack.go index ef37b438..e27bfd56 100644 --- a/internal/usecase/stack.go +++ b/internal/usecase/stack.go @@ -138,7 +138,7 @@ func (u *StackUsecase) Create(ctx context.Context, dto model.Stack) (stackId dom }, }) if err != nil { - log.ErrorWithContext(ctx, err) + log.Error(ctx, err) return "", httpErrors.NewInternalServerError(err, "S_FAILED_TO_CALL_WORKFLOW", "") } log.DebugWithContext(ctx, "Submitted workflow: ", workflowId) @@ -214,7 +214,7 @@ func (u *StackUsecase) Install(ctx context.Context, stackId domain.StackId) (err }, }) if err != nil { - log.ErrorWithContext(ctx, err) + log.Error(ctx, err) return httpErrors.NewInternalServerError(err, "S_FAILED_TO_CALL_WORKFLOW", "") } log.DebugWithContext(ctx, "Submitted workflow: ", workflowId) @@ -447,17 +447,17 @@ func (u *StackUsecase) Delete(ctx context.Context, dto model.Stack) (err error) }, }) if err != nil { - log.ErrorWithContext(ctx, err) + log.Error(ctx, err) return err } log.DebugWithContext(ctx, "Submitted workflow: ", workflowId) // Remove Cluster & AppGroup status description if err := u.appGroupRepo.InitWorkflowDescription(ctx, cluster.ID); err != nil { - log.ErrorWithContext(ctx, err) + log.Error(ctx, err) } if err := u.clusterRepo.InitWorkflowDescription(ctx, cluster.ID); err != nil { - log.ErrorWithContext(ctx, err) + log.Error(ctx, err) } // wait & get clusterId ( max 1min ) From d1209d35fe4f878f06e33e73e256a1ce4adef5ba Mon Sep 17 00:00:00 2001 From: donggyu Date: Wed, 13 Mar 2024 11:14:07 +0900 Subject: [PATCH 07/11] apply context to all the rest --- internal/repository/endpoint_test.go | 75 -------------------------- internal/repository/mapper_test.go | 79 ---------------------------- 2 files changed, 154 deletions(-) delete mode 100644 internal/repository/endpoint_test.go delete mode 100644 internal/repository/mapper_test.go diff --git a/internal/repository/endpoint_test.go b/internal/repository/endpoint_test.go deleted file mode 100644 index f27a9f06..00000000 --- a/internal/repository/endpoint_test.go +++ /dev/null @@ -1,75 +0,0 @@ -package repository_test - -import ( - "fmt" - myRepository "github.com/openinfradev/tks-api/internal/repository" - "github.com/openinfradev/tks-api/pkg/domain" - "gorm.io/driver/postgres" - "gorm.io/gorm" - "gorm_test/config" - "testing" -) - -func TestNewEndpointRepository(t *testing.T) { - conf := config.NewDefaultConfig() - dsn := fmt.Sprintf( - "host=%s dbname=%s user=%s password=%s port=%d sslmode=disable TimeZone=Asia/Seoul", - conf.Address, conf.Database, conf.AdminId, conf.AdminPassword, conf.Port, - ) - - t.Logf("dsn: %s", dsn) - - db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{}) - if err != nil { - panic(err) - } - - if err = db.AutoMigrate(&myRepository.Endpoint{}); err != nil { - panic(err) - } - - dbClient := myRepository.NewEndpointRepository(db) - - // create - endpoint := &domain.Endpoint{ - Name: "test", - Group: "test", - } - - if err := dbClient.Create(endpoint); err != nil { - panic(err) - } - - t.Log("list") - // list - endpoints, err := dbClient.List(nil) - if err != nil { - panic(err) - } - - for _, endpoint := range endpoints { - t.Logf("endpoint: %+v", endpoint) - } - - t.Log("get") - // get - for _, endpoint := range endpoints { - endpoint, err := dbClient.Get(endpoint.ID) - if err != nil { - panic(err) - } - t.Logf("endpoint: %+v", endpoint) - } - - t.Log("update") - // update - for _, endpoint := range endpoints { - endpoint.Name = "test2" - t.Logf("BeforeUpdate: %+v", endpoint) - if err := dbClient.Update(endpoint); err != nil { - panic(err) - } else { - t.Logf("AfterUpdate: %+v", endpoint) - } - } -} diff --git a/internal/repository/mapper_test.go b/internal/repository/mapper_test.go deleted file mode 100644 index bf040134..00000000 --- a/internal/repository/mapper_test.go +++ /dev/null @@ -1,79 +0,0 @@ -package repository - -import ( - "fmt" - "github.com/google/uuid" - "github.com/openinfradev/tks-api/pkg/domain" - "testing" - "time" -) - -// test case -func TestConvert(t *testing.T) { - genUuid, _ := uuid.NewRandom() - uuidStr := genUuid.String() - - type args struct { - src interface{} - dst interface{} - } - tests := []struct { - name string - args args - wantErr bool - }{ - { - name: "test case 1", - args: args{ - src: User{ - ID: genUuid, - AccountId: "testAccount", - Name: "testName", - Password: "testPassword", - RoleId: uuid.UUID{}, - Role: Role{}, - OrganizationId: "testOrganizationId", - Organization: Organization{}, - Creator: uuid.UUID{}, - Email: "testEmail", - Department: "testDepartment", - Description: "testDescription", - }, - dst: &domain.User{}, - }, - wantErr: false, - }, - { - name: "test case 2", - args: args{ - src: domain.User{ - ID: uuidStr, - AccountId: "testAccount", - Password: "testPassword", - Name: "testName", - Token: "testToken", - Role: domain.Role{}, - Organization: domain.Organization{}, - Creator: "testCreator", - CreatedAt: time.Time{}, - UpdatedAt: time.Time{}, - Email: "test email", - Department: "testDepartment", - Description: "testDescription", - }, - dst: &User{}, - }, - wantErr: false, - }, - } - _ = tests - 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.Println(tt.args.dst) - } - }) - } -} From edfca2c245dc40bb880457f9d758bcd3a9b1aa32 Mon Sep 17 00:00:00 2001 From: donggyu Date: Wed, 13 Mar 2024 11:14:37 +0900 Subject: [PATCH 08/11] apply context to all the rest --- cmd/server/main.go | 28 +- internal/database/database.go | 10 +- internal/delivery/http/app-serve-app.go | 45 +-- internal/delivery/http/audit.go | 2 +- internal/delivery/http/auth.go | 24 +- internal/delivery/http/cloud-account.go | 2 +- internal/delivery/http/handler.go | 2 +- internal/delivery/http/organization.go | 24 +- internal/delivery/http/permission.go | 23 +- internal/delivery/http/project.go | 94 ++--- internal/delivery/http/user.go | 42 +-- internal/gorm/gorm.go | 20 +- internal/helper/ssh.go | 18 +- internal/helper/util.go | 20 +- internal/keycloak/keycloak.go | 348 ++++++++---------- internal/kubernetes/kubernetes.go | 138 +++---- internal/mail/content.go | 18 +- internal/mail/ses.go | 8 +- internal/mail/smtp.go | 27 +- internal/middleware/audit/audit-map.go | 75 ++-- internal/middleware/audit/audit.go | 8 +- .../auth/authenticator/authenticator.go | 2 +- .../auth/authenticator/keycloak/keycloak.go | 14 +- internal/middleware/auth/authorizer/rbac.go | 4 +- internal/middleware/auth/role/default.go | 11 +- internal/middleware/logging/logging.go | 4 +- internal/repository/app-group.go | 2 +- internal/repository/app-serve-app.go | 16 +- internal/repository/cluster.go | 10 +- internal/repository/mapper.go | 3 +- internal/repository/organization.go | 16 +- internal/repository/project.go | 70 ++-- internal/repository/user.go | 20 +- internal/route/route.go | 8 +- internal/usecase/alert.go | 2 +- internal/usecase/app-group.go | 6 +- internal/usecase/app-serve-app.go | 138 +++---- internal/usecase/auth.go | 39 +- internal/usecase/cloud-account.go | 18 +- internal/usecase/cluster.go | 38 +- internal/usecase/dashboard.go | 32 +- internal/usecase/organization.go | 5 +- internal/usecase/project.go | 34 +- internal/usecase/stack.go | 38 +- internal/usecase/user.go | 52 +-- pkg/argo-client/client-mock.go | 11 +- pkg/argo-client/client.go | 43 +-- pkg/domain/mapper.go | 0 pkg/httpErrors/httpErrors.go | 2 - pkg/thanos-client/client.go | 19 +- 50 files changed, 796 insertions(+), 837 deletions(-) create mode 100644 pkg/domain/mapper.go diff --git a/cmd/server/main.go b/cmd/server/main.go index bf6926f7..34d84fab 100644 --- a/cmd/server/main.go +++ b/cmd/server/main.go @@ -1,6 +1,7 @@ package main import ( + "context" "flag" "fmt" "net/http" @@ -72,7 +73,7 @@ func init() { flag.Parse() if err := viper.BindPFlags(pflag.CommandLine); err != nil { - log.Error(err) + log.Error(context.Background(), err) } address := viper.GetString("external-address") @@ -102,11 +103,12 @@ func init() { // @host tks-api-dev.taco-cat.xyz // @BasePath /api/1.0/ func main() { - log.Info("*** Arguments *** ") + ctx := context.Background() + log.Info(ctx, "*** Arguments *** ") for i, s := range viper.AllSettings() { - log.Info(fmt.Sprintf("%s : %v", i, s)) + log.Info(ctx, fmt.Sprintf("%s : %v", i, s)) } - log.Info("****************** ") + log.Info(ctx, "****************** ") // For web service asset := route.NewAssetHandler(viper.GetString("web-root")) @@ -114,7 +116,7 @@ func main() { // Initialize database db, err := database.InitDB() if err != nil { - log.Fatal("cannot connect gormDB") + log.Fatal(ctx, "cannot connect gormDB") } // Ensure default rows in database @@ -125,12 +127,12 @@ func main() { if viper.GetString("argo-address") == "" || viper.GetInt("argo-port") == 0 { argoClient, err = argowf.NewMock() if err != nil { - log.Fatal("failed to create argowf client : ", err) + log.Fatal(ctx, "failed to create argowf client : ", err) } } else { argoClient, err = argowf.New(viper.GetString("argo-address"), viper.GetInt("argo-port"), false, "") if err != nil { - log.Fatal("failed to create argowf client : ", err) + log.Fatal(ctx, "failed to create argowf client : ", err) } } @@ -141,20 +143,20 @@ func main() { ClientSecret: viper.GetString("keycloak-client-secret"), }) - err = keycloak.InitializeKeycloak() + err = keycloak.InitializeKeycloak(ctx) if err != nil { - log.Fatal("failed to initialize keycloak : ", err) + log.Fatal(ctx, "failed to initialize keycloak : ", err) } - err = mail.Initialize() + err = mail.Initialize(ctx) if err != nil { - log.Fatal("failed to initialize ses : ", err) + log.Fatal(ctx, "failed to initialize ses : ", err) } route := route.SetupRouter(db, argoClient, keycloak, asset) - log.Info("Starting server on ", viper.GetInt("port")) + log.Info(ctx, "Starting server on ", viper.GetInt("port")) err = http.ListenAndServe("0.0.0.0:"+strconv.Itoa(viper.GetInt("port")), route) if err != nil { - log.Fatal(err) + log.Fatal(ctx, err) } } diff --git a/internal/database/database.go b/internal/database/database.go index 37485621..043bd031 100644 --- a/internal/database/database.go +++ b/internal/database/database.go @@ -3,6 +3,8 @@ package database import ( "context" "fmt" + "github.com/openinfradev/tks-api/internal/pagination" + "github.com/openinfradev/tks-api/pkg/log" "os" "strings" @@ -179,8 +181,9 @@ func EnsureDefaultRows(db *gorm.DB) error { // ctx := context.Background() - - eps, err := repoFactory.Endpoint.List(ctx, nil) + pg := pagination.NewPagination(nil) + pg.Limit = 1000 + eps, err := repoFactory.Endpoint.List(ctx, pg) if err != nil { return err } @@ -189,7 +192,10 @@ func EnsureDefaultRows(db *gorm.DB) error { for _, ep := range eps { storedEps[ep.Name] = struct{}{} } + log.Debugf(context.Background(), "storedEps: %+v", storedEps) for _, ep := range api.ApiMap { + log.Debug(context.Background(), "ep.Name", ep.Name) + log.Debug(context.Background(), "storedEps[ep.Name]", storedEps[ep.Name]) if _, ok := storedEps[ep.Name]; !ok { if err := repoFactory.Endpoint.Create(ctx, &model.Endpoint{ Name: ep.Name, diff --git a/internal/delivery/http/app-serve-app.go b/internal/delivery/http/app-serve-app.go index 1d66ebf7..f75ff95c 100644 --- a/internal/delivery/http/app-serve-app.go +++ b/internal/delivery/http/app-serve-app.go @@ -1,6 +1,7 @@ package http import ( + "context" "fmt" "math/rand" "net/http" @@ -94,14 +95,14 @@ func NewAppServeAppHandler(h usecase.Usecase) *AppServeAppHandler { func (h *AppServeAppHandler) CreateAppServeApp(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) organizationId, ok := vars["organizationId"] - log.Debugf("organizationId = [%v]\n", organizationId) + log.Debugf(r.Context(), "organizationId = [%v]\n", organizationId) if !ok { ErrorJSON(w, r, httpErrors.NewBadRequestError(fmt.Errorf("Invalid organizationId"), "C_INVALID_ORGANIZATION_ID", "")) return } projectId, ok := vars["projectId"] - log.Debugf("projectId = [%v]\n", projectId) + log.Debugf(r.Context(), "projectId = [%v]\n", projectId) if !ok { ErrorJSON(w, r, httpErrors.NewBadRequestError(fmt.Errorf("Invalid projectId"), "C_INVALID_PROJECT_ID", "")) return @@ -122,7 +123,7 @@ func (h *AppServeAppHandler) CreateAppServeApp(w http.ResponseWriter, r *http.Re return } - log.Infof("Processing CREATE request for app '%s'...", app.Name) + log.Infof(r.Context(), "Processing CREATE request for app '%s'...", app.Name) now := time.Now() app.OrganizationId = organizationId @@ -180,10 +181,10 @@ func (h *AppServeAppHandler) CreateAppServeApp(w http.ResponseWriter, r *http.Re } } - log.Infof("Created new namespace: %s", ns) + log.Infof(r.Context(), "Created new namespace: %s", ns) app.Namespace = ns } else { - log.Infof("Using existing namespace: %s", app.Namespace) + log.Infof(r.Context(), "Using existing namespace: %s", app.Namespace) } // Validate port param for springboot app @@ -268,7 +269,7 @@ func (h *AppServeAppHandler) GetAppServeApps(w http.ResponseWriter, r *http.Requ 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) + log.Info(r.Context(), err) continue } } @@ -338,7 +339,7 @@ func (h *AppServeAppHandler) GetAppServeApp(w http.ResponseWriter, r *http.Reque var out domain.GetAppServeAppResponse if err := serializer.Map(app, &out.AppServeApp); err != nil { - log.InfoWithContext(r.Context(), err) + log.Info(r.Context(), err) } // NOTE: makeStages function's been changed to use task instead of app @@ -388,7 +389,7 @@ func (h *AppServeAppHandler) GetAppServeAppLatestTask(w http.ResponseWriter, r * var out domain.GetAppServeAppTaskResponse if err := serializer.Map(task, &out.AppServeAppTask); err != nil { - log.InfoWithContext(r.Context(), err) + log.Info(r.Context(), err) } ResponseJSON(w, r, http.StatusOK, out) @@ -411,7 +412,7 @@ func (h *AppServeAppHandler) GetNumOfAppsOnStack(w http.ResponseWriter, r *http. vars := mux.Vars(r) organizationId, ok := vars["organizationId"] - log.Debugf("organizationId = [%s]\n", organizationId) + log.Debugf(r.Context(), "organizationId = [%s]\n", organizationId) if !ok { ErrorJSON(w, r, httpErrors.NewBadRequestError(fmt.Errorf("invalid organizationId"), "", "")) return @@ -478,7 +479,7 @@ func (h *AppServeAppHandler) GetAppServeAppTasksByAppId(w http.ResponseWriter, r 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) + log.Info(r.Context(), err) continue } } @@ -508,28 +509,28 @@ func (h *AppServeAppHandler) GetAppServeAppTaskDetail(w http.ResponseWriter, r * vars := mux.Vars(r) organizationId, ok := vars["organizationId"] - log.Debugf("organizationId = [%v]\n", organizationId) + log.Debugf(r.Context(), "organizationId = [%v]\n", organizationId) if !ok { ErrorJSON(w, r, httpErrors.NewBadRequestError(fmt.Errorf("Invalid organizationId: [%s]", organizationId), "C_INVALID_ORGANIZATION_ID", "")) return } projectId, ok := vars["projectId"] - log.Debugf("projectId = [%v]\n", projectId) + log.Debugf(r.Context(), "projectId = [%v]\n", projectId) if !ok { ErrorJSON(w, r, httpErrors.NewBadRequestError(fmt.Errorf("Invalid projectId: [%s]", projectId), "C_INVALID_PROJECT_ID", "")) return } appId, ok := vars["appId"] - log.Debugf("appId = [%s]\n", appId) + log.Debugf(r.Context(), "appId = [%s]\n", appId) if !ok { ErrorJSON(w, r, httpErrors.NewBadRequestError(fmt.Errorf("Invalid appId: [%s]", appId), "C_INVALID_ASA_ID", "")) return } taskId, ok := vars["taskId"] - log.Debugf("taskId = [%s]\n", taskId) + log.Debugf(r.Context(), "taskId = [%s]\n", taskId) if !ok { ErrorJSON(w, r, httpErrors.NewBadRequestError(fmt.Errorf("Invalid taskId: [%s]", taskId), "C_INVALID_ASA_TASK_ID", "")) return @@ -552,18 +553,18 @@ func (h *AppServeAppHandler) GetAppServeAppTaskDetail(w http.ResponseWriter, r * var out domain.GetAppServeAppTaskResponse if err := serializer.Map(app, &out.AppServeApp); err != nil { - log.InfoWithContext(r.Context(), err) + log.Info(r.Context(), err) } if err := serializer.Map(task, &out.AppServeAppTask); err != nil { - log.InfoWithContext(r.Context(), err) + log.Info(r.Context(), err) } - out.Stages = makeStages(task, app) + out.Stages = makeStages(r.Context(), task, app) ResponseJSON(w, r, http.StatusOK, out) } -func makeStages(task *model.AppServeAppTask, app *model.AppServeApp) []domain.StageResponse { +func makeStages(ctx context.Context, task *model.AppServeAppTask, app *model.AppServeApp) []domain.StageResponse { stages := make([]domain.StageResponse, 0) var stage domain.StageResponse @@ -592,20 +593,20 @@ func makeStages(task *model.AppServeAppTask, app *model.AppServeApp) []domain.St pipelines = []string{"deploy", "promote"} } } else { - log.Error("Unexpected case happened while making stages!") + log.Error(ctx, "Unexpected case happened while making stages!") } fmt.Printf("Pipeline stages: %v\n", pipelines) for _, pl := range pipelines { - stage = makeStage(task, app, pl) + stage = makeStage(ctx, task, app, pl) stages = append(stages, stage) } return stages } -func makeStage(task *model.AppServeAppTask, app *model.AppServeApp, pl string) domain.StageResponse { +func makeStage(ctx context.Context, task *model.AppServeAppTask, app *model.AppServeApp, pl string) domain.StageResponse { taskStatus := task.Status strategy := task.Strategy @@ -634,7 +635,7 @@ func makeStage(task *model.AppServeAppTask, app *model.AppServeApp, pl string) d actions = append(actions, action) } } else { - log.Error("Not supported strategy!") + log.Error(ctx, "Not supported strategy!") } } else if stage.Status == "PROMOTE_WAIT" && strategy == "blue-green" { diff --git a/internal/delivery/http/audit.go b/internal/delivery/http/audit.go index c04b46ea..5b8defff 100644 --- a/internal/delivery/http/audit.go +++ b/internal/delivery/http/audit.go @@ -110,7 +110,7 @@ func (h *AuditHandler) GetAudit(w http.ResponseWriter, r *http.Request) { ErrorJSON(w, r, err) return } - log.Info(audit) + log.Info(r.Context(), audit) var out domain.GetAuditResponse if err := serializer.Map(audit, &out.Audit); err != nil { diff --git a/internal/delivery/http/auth.go b/internal/delivery/http/auth.go index 801c9ec2..5208a42a 100644 --- a/internal/delivery/http/auth.go +++ b/internal/delivery/http/auth.go @@ -69,7 +69,7 @@ func (h *AuthHandler) Login(w http.ResponseWriter, r *http.Request) { ClientIP: audit.GetClientIpAddress(w, r), UserId: nil, }) - log.ErrorfWithContext(r.Context(), "error is :%s(%T)", err.Error(), err) + log.Errorf(r.Context(), "error is :%s(%T)", err.Error(), err) ErrorJSON(w, r, err) return } else { @@ -85,7 +85,7 @@ func (h *AuthHandler) Login(w http.ResponseWriter, r *http.Request) { var cookies []*http.Cookie if targetCookies, err := h.usecase.SingleSignIn(r.Context(), input.OrganizationId, input.AccountId, input.Password); err != nil { - log.ErrorfWithContext(r.Context(), "error is :%s(%T)", err.Error(), err) + log.Errorf(r.Context(), "error is :%s(%T)", err.Error(), err) } else { cookies = append(cookies, targetCookies...) } @@ -119,13 +119,13 @@ func (h *AuthHandler) Logout(w http.ResponseWriter, r *http.Request) { sessionId, ok := request.SessionFrom(ctx) if !ok { - log.ErrorfWithContext(r.Context(), "session id is not found") + log.Errorf(r.Context(), "session id is not found") ErrorJSON(w, r, httpErrors.NewInternalServerError(fmt.Errorf("session id is not found"), "A_NO_SESSION", "")) return } userInfo, ok := request.UserFrom(ctx) if !ok { - log.ErrorfWithContext(r.Context(), "user info is not found") + log.Errorf(r.Context(), "user info is not found") ErrorJSON(w, r, httpErrors.NewInternalServerError(fmt.Errorf("user info is not found"), "A_NO_SESSION", "")) return } @@ -133,7 +133,7 @@ func (h *AuthHandler) Logout(w http.ResponseWriter, r *http.Request) { err := h.usecase.Logout(r.Context(), sessionId, organizationId) if err != nil { - log.ErrorfWithContext(r.Context(), "error is :%s(%T)", err.Error(), err) + log.Errorf(r.Context(), "error is :%s(%T)", err.Error(), err) ErrorJSON(w, r, httpErrors.NewBadRequestError(err, "", "")) return } @@ -141,7 +141,7 @@ func (h *AuthHandler) Logout(w http.ResponseWriter, r *http.Request) { var cookies []*http.Cookie redirectUrl, targetCookies, err := h.usecase.SingleSignOut(r.Context(), organizationId) if err != nil { - log.ErrorfWithContext(r.Context(), "error is :%s(%T)", err.Error(), err) + log.Errorf(r.Context(), "error is :%s(%T)", err.Error(), err) } cookies = append(cookies, targetCookies...) if len(cookies) > 0 { @@ -185,7 +185,7 @@ func (h *AuthHandler) FindId(w http.ResponseWriter, r *http.Request) { accountId, err := h.usecase.FindId(r.Context(), input.Code, input.Email, input.UserName, input.OrganizationId) if err != nil { - log.ErrorfWithContext(r.Context(), "error is :%s(%T)", err.Error(), err) + log.Errorf(r.Context(), "error is :%s(%T)", err.Error(), err) ErrorJSON(w, r, err) return @@ -217,7 +217,7 @@ func (h *AuthHandler) FindPassword(w http.ResponseWriter, r *http.Request) { err = h.usecase.FindPassword(r.Context(), input.Code, input.AccountId, input.Email, input.UserName, input.OrganizationId) if err != nil { - log.ErrorfWithContext(r.Context(), "error is :%s(%T)", err.Error(), err) + log.Errorf(r.Context(), "error is :%s(%T)", err.Error(), err) ErrorJSON(w, r, err) return } @@ -246,7 +246,7 @@ func (h *AuthHandler) VerifyIdentityForLostId(w http.ResponseWriter, r *http.Req err = h.usecase.VerifyIdentity(r.Context(), "", input.Email, input.UserName, input.OrganizationId) if err != nil { - log.ErrorfWithContext(r.Context(), "error is :%s(%T)", err.Error(), err) + log.Errorf(r.Context(), "error is :%s(%T)", err.Error(), err) ErrorJSON(w, r, err) return } @@ -277,7 +277,7 @@ func (h *AuthHandler) VerifyIdentityForLostPassword(w http.ResponseWriter, r *ht err = h.usecase.VerifyIdentity(r.Context(), input.AccountId, input.Email, input.UserName, input.OrganizationId) if err != nil { - log.ErrorfWithContext(r.Context(), "error is :%s(%T)", err.Error(), err) + log.Errorf(r.Context(), "error is :%s(%T)", err.Error(), err) ErrorJSON(w, r, err) return } @@ -298,14 +298,14 @@ func (h *AuthHandler) VerifyIdentityForLostPassword(w http.ResponseWriter, r *ht func (h *AuthHandler) VerifyToken(w http.ResponseWriter, r *http.Request) { token, ok := request.TokenFrom(r.Context()) if !ok { - log.ErrorfWithContext(r.Context(), "token is not found") + log.Errorf(r.Context(), "token is not found") ErrorJSON(w, r, httpErrors.NewInternalServerError(fmt.Errorf("token is not found"), "C_INTERNAL_ERROR", "")) return } isActive, err := h.usecase.VerifyToken(r.Context(), token) if err != nil { - log.ErrorfWithContext(r.Context(), "error is :%s(%T)", err.Error(), err) + log.Errorf(r.Context(), "error is :%s(%T)", err.Error(), err) ErrorJSON(w, r, httpErrors.NewInternalServerError(err, "", "")) return } diff --git a/internal/delivery/http/cloud-account.go b/internal/delivery/http/cloud-account.go index b4a78d3f..c2685eb8 100644 --- a/internal/delivery/http/cloud-account.go +++ b/internal/delivery/http/cloud-account.go @@ -184,7 +184,7 @@ func (h *CloudAccountHandler) UpdateCloudAccount(w http.ResponseWriter, r *http. ErrorJSON(w, r, httpErrors.NewBadRequestError(fmt.Errorf("Invalid organizationId"), "C_INVALID_ORGANIZATION_ID", "")) return } - log.DebugWithContext(r.Context(), "[TODO] organization check", organizationId) + log.Debug(r.Context(), "[TODO] organization check", organizationId) cloudAccountId, err := uuid.Parse(strId) if err != nil { diff --git a/internal/delivery/http/handler.go b/internal/delivery/http/handler.go index 1fc7de9f..a45435c9 100644 --- a/internal/delivery/http/handler.go +++ b/internal/delivery/http/handler.go @@ -27,7 +27,7 @@ func init() { } func ErrorJSON(w http.ResponseWriter, r *http.Request, err error) { - log.ErrorfWithContext(r.Context(), "error is :%s(%T)", err.Error(), err) + log.Errorf(r.Context(), "error is :%s(%T)", err.Error(), err) errorResponse, status := httpErrors.ErrorResponse(err) ResponseJSON(w, r, status, errorResponse) } diff --git a/internal/delivery/http/organization.go b/internal/delivery/http/organization.go index 69face7e..a224781d 100644 --- a/internal/delivery/http/organization.go +++ b/internal/delivery/http/organization.go @@ -48,7 +48,7 @@ func (h *OrganizationHandler) CreateOrganization(w http.ResponseWriter, r *http. err := UnmarshalRequestInput(r, &input) if err != nil { - log.ErrorfWithContext(r.Context(), "error is :%s(%T)", err.Error(), err) + log.Errorf(r.Context(), "error is :%s(%T)", err.Error(), err) ErrorJSON(w, r, err) return } @@ -61,7 +61,7 @@ func (h *OrganizationHandler) CreateOrganization(w http.ResponseWriter, r *http. organizationId, err := h.usecase.Create(ctx, &organization) if err != nil { - log.ErrorfWithContext(r.Context(), "error is :%s(%T)", err.Error(), err) + log.Errorf(r.Context(), "error is :%s(%T)", err.Error(), err) ErrorJSON(w, r, err) return } @@ -76,7 +76,7 @@ func (h *OrganizationHandler) CreateOrganization(w http.ResponseWriter, r *http. } adminRoleId, err := h.roleUsecase.CreateTksRole(r.Context(), &adminRole) if err != nil { - log.ErrorfWithContext(r.Context(), "error is :%s(%T)", err.Error(), err) + log.Errorf(r.Context(), "error is :%s(%T)", err.Error(), err) ErrorJSON(w, r, err) return } @@ -88,7 +88,7 @@ func (h *OrganizationHandler) CreateOrganization(w http.ResponseWriter, r *http. } userRoleId, err := h.roleUsecase.CreateTksRole(r.Context(), &userRole) if err != nil { - log.ErrorfWithContext(r.Context(), "error is :%s(%T)", err.Error(), err) + log.Errorf(r.Context(), "error is :%s(%T)", err.Error(), err) ErrorJSON(w, r, err) return } @@ -98,7 +98,7 @@ func (h *OrganizationHandler) CreateOrganization(w http.ResponseWriter, r *http. h.permissionUsecase.SetRoleIdToPermissionSet(r.Context(), adminRoleId, adminPermissionSet) err = h.permissionUsecase.CreatePermissionSet(r.Context(), adminPermissionSet) if err != nil { - log.ErrorfWithContext(r.Context(), "error is :%s(%T)", err.Error(), err) + log.Errorf(r.Context(), "error is :%s(%T)", err.Error(), err) ErrorJSON(w, r, err) return } @@ -107,7 +107,7 @@ func (h *OrganizationHandler) CreateOrganization(w http.ResponseWriter, r *http. h.permissionUsecase.SetRoleIdToPermissionSet(r.Context(), userRoleId, userPermissionSet) err = h.permissionUsecase.CreatePermissionSet(r.Context(), userPermissionSet) if err != nil { - log.ErrorfWithContext(r.Context(), "error is :%s(%T)", err.Error(), err) + log.Errorf(r.Context(), "error is :%s(%T)", err.Error(), err) ErrorJSON(w, r, err) return } @@ -115,7 +115,7 @@ func (h *OrganizationHandler) CreateOrganization(w http.ResponseWriter, r *http. // Admin user 생성 admin, err := h.userUsecase.CreateAdmin(r.Context(), organizationId, input.AdminAccountId, input.AdminName, input.AdminEmail) if err != nil { - log.ErrorfWithContext(r.Context(), "error is :%s(%T)", err.Error(), err) + log.Errorf(r.Context(), "error is :%s(%T)", err.Error(), err) ErrorJSON(w, r, err) return } @@ -156,7 +156,7 @@ func (h *OrganizationHandler) GetOrganizations(w http.ResponseWriter, r *http.Re pg := pagination.NewPagination(&urlParams) organizations, err := h.usecase.Fetch(r.Context(), pg) if err != nil { - log.ErrorfWithContext(r.Context(), "error is :%s(%T)", err.Error(), err) + log.Errorf(r.Context(), "error is :%s(%T)", err.Error(), err) ErrorJSON(w, r, err) return @@ -201,7 +201,7 @@ func (h *OrganizationHandler) GetOrganization(w http.ResponseWriter, r *http.Req organization, err := h.usecase.Get(r.Context(), organizationId) if err != nil { - log.ErrorfWithContext(r.Context(), "error is :%s(%T)", err.Error(), err) + log.Errorf(r.Context(), "error is :%s(%T)", err.Error(), err) if _, status := httpErrors.ErrorResponse(err); status == http.StatusNotFound { ErrorJSON(w, r, httpErrors.NewBadRequestError(err, "", "")) return @@ -262,7 +262,7 @@ func (h *OrganizationHandler) DeleteOrganization(w http.ResponseWriter, r *http. err := h.userUsecase.DeleteAll(r.Context(), organizationId) if err != nil { - log.ErrorfWithContext(r.Context(), "error is :%s(%T)", err.Error(), err) + log.Errorf(r.Context(), "error is :%s(%T)", err.Error(), err) ErrorJSON(w, r, err) return @@ -271,7 +271,7 @@ func (h *OrganizationHandler) DeleteOrganization(w http.ResponseWriter, r *http. // organization 삭제 err = h.usecase.Delete(r.Context(), organizationId, token) if err != nil { - log.ErrorfWithContext(r.Context(), "error is :%s(%T)", err.Error(), err) + log.Errorf(r.Context(), "error is :%s(%T)", err.Error(), err) if _, status := httpErrors.ErrorResponse(err); status == http.StatusNotFound { ErrorJSON(w, r, httpErrors.NewBadRequestError(err, "", "")) return @@ -315,7 +315,7 @@ func (h *OrganizationHandler) UpdateOrganization(w http.ResponseWriter, r *http. organization, err := h.usecase.Update(r.Context(), organizationId, input) if err != nil { - log.ErrorfWithContext(r.Context(), "error is :%s(%T)", err.Error(), err) + log.Errorf(r.Context(), "error is :%s(%T)", err.Error(), err) if _, status := httpErrors.ErrorResponse(err); status == http.StatusNotFound { ErrorJSON(w, r, httpErrors.NewBadRequestError(err, "", "")) return diff --git a/internal/delivery/http/permission.go b/internal/delivery/http/permission.go index bdc65716..488c971a 100644 --- a/internal/delivery/http/permission.go +++ b/internal/delivery/http/permission.go @@ -43,7 +43,7 @@ func (h PermissionHandler) GetPermissionTemplates(w http.ResponseWriter, r *http var premissionSetResponse domain.PermissionSetResponse if err := serializer.Map(permissionSet, &premissionSetResponse); err != nil { - log.InfoWithContext(r.Context(), err) + log.Info(r.Context(), err) } var out domain.GetPermissionTemplatesResponse @@ -87,7 +87,7 @@ func (h PermissionHandler) GetPermissionsByRoleId(w http.ResponseWriter, r *http var premissionSetResponse domain.PermissionSetResponse if err := serializer.Map(permissionSet, &premissionSetResponse); err != nil { - log.InfoWithContext(r.Context(), err) + log.Info(r.Context(), err) } var out domain.GetPermissionsByRoleIdResponse @@ -115,7 +115,6 @@ func (h PermissionHandler) GetPermissionsByRoleId(w http.ResponseWriter, r *http // @Security JWT func (h PermissionHandler) UpdatePermissionsByRoleId(w http.ResponseWriter, r *http.Request) { // path parameter - log.Debug("UpdatePermissionsByRoleId Called") var roleId string _ = roleId vars := mux.Vars(r) @@ -133,14 +132,11 @@ func (h PermissionHandler) UpdatePermissionsByRoleId(w http.ResponseWriter, r *h ErrorJSON(w, r, httpErrors.NewBadRequestError(err, "", "")) return } - log.Debugf("input: %+v", input) 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) + log.Info(r.Context(), err) } if err := h.permissionUsecase.UpdatePermission(r.Context(), &permission); err != nil { @@ -149,18 +145,5 @@ func (h PermissionHandler) UpdatePermissionsByRoleId(w http.ResponseWriter, r *h } } - //var edgePermissions []*domain.Permission - //for _, permission := range input.Permissions { - // domain.GetEdgePermission(permission, edgePermissions, nil) - //} - //log.Debugf("edgePermissions: %+v", edgePermissions) - //for _, permission := range edgePermissions { - // err := h.permissionUsecase.UpdatePermission(permission) - // if err != nil { - // ErrorJSON(w, r, httpErrors.NewInternalServerError(err, "", "")) - // return - // } - //} - ResponseJSON(w, r, http.StatusOK, nil) } diff --git a/internal/delivery/http/project.go b/internal/delivery/http/project.go index d9215d42..015c4c48 100644 --- a/internal/delivery/http/project.go +++ b/internal/delivery/http/project.go @@ -82,7 +82,7 @@ func NewProjectHandler(u usecase.Usecase) IProjectHandler { func (p ProjectHandler) CreateProject(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) organizationId, ok := vars["organizationId"] - log.Debugf("organizationId = [%v]\n", organizationId) + log.Debugf(r.Context(), "organizationId = [%v]\n", organizationId) if !ok { ErrorJSON(w, r, httpErrors.NewBadRequestError(fmt.Errorf("invalid organizationId"), "C_INVALID_ORGANIZATION_ID", "")) @@ -101,7 +101,7 @@ func (p ProjectHandler) CreateProject(w http.ResponseWriter, r *http.Request) { Description: projectReq.Description, CreatedAt: now, } - log.Infof("Processing CREATE request for project '%s'...", project.Name) + log.Infof(r.Context(), "Processing CREATE request for project '%s'...", project.Name) projectId, err := p.usecase.CreateProject(r.Context(), project) if err != nil { @@ -112,14 +112,14 @@ func (p ProjectHandler) CreateProject(w http.ResponseWriter, r *http.Request) { project.ID = projectId ProjectLeaderId, err := uuid.Parse(projectReq.ProjectLeaderId) if err != nil { - log.Error(err) + log.Error(r.Context(), err) ErrorJSON(w, r, httpErrors.NewInternalServerError(err, "", "Failed to parse uuid to string")) return } prs, err := p.usecase.GetProjectRoles(r.Context(), usecase.ProjectLeader) if err != nil { - log.Error(err) + log.Error(r.Context(), err) ErrorJSON(w, r, httpErrors.NewInternalServerError(err, "", "Failed to retrieve project-leader id")) return } @@ -137,7 +137,7 @@ func (p ProjectHandler) CreateProject(w http.ResponseWriter, r *http.Request) { projectMemberId, err := p.usecase.AddProjectMember(r.Context(), pm) if err != nil { - log.Errorf("projectMemberId: %v", projectMemberId) + log.Errorf(r.Context(), "projectMemberId: %v", projectMemberId) ErrorJSON(w, r, httpErrors.NewInternalServerError(err, "", "")) return } @@ -302,7 +302,7 @@ func (p ProjectHandler) GetProject(w http.ResponseWriter, r *http.Request) { var pdr domain.ProjectDetailResponse if err = serializer.Map(*project, &pdr); err != nil { - log.Error(err) + log.Error(r.Context(), err) ErrorJSON(w, r, err) return } @@ -371,14 +371,14 @@ func (p ProjectHandler) IsProjectNameExist(w http.ResponseWriter, r *http.Reques func (p ProjectHandler) UpdateProject(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) organizationId, ok := vars["organizationId"] - log.Debugf("organizationId = [%v]\n", organizationId) + log.Debugf(r.Context(), "organizationId = [%v]\n", organizationId) if !ok { ErrorJSON(w, r, httpErrors.NewBadRequestError(fmt.Errorf("invalid organizationId"), "C_INVALID_ORGANIZATION_ID", "")) return } projectId, ok := vars["projectId"] - log.Debugf("projectId = [%v]\n", projectId) + log.Debugf(r.Context(), "projectId = [%v]\n", projectId) if !ok { ErrorJSON(w, r, httpErrors.NewBadRequestError(fmt.Errorf("invalid projectId"), "C_INVALID_PROJECT_ID", "")) @@ -438,7 +438,7 @@ func (p ProjectHandler) DeleteProject(w http.ResponseWriter, r *http.Request) { func (p ProjectHandler) GetProjectRole(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) organizationId, ok := vars["organizationId"] - log.Debugf("organizationId = [%v]\n", organizationId) + log.Debugf(r.Context(), "organizationId = [%v]\n", organizationId) if !ok { ErrorJSON(w, r, httpErrors.NewBadRequestError(fmt.Errorf("invalid organizationId"), "C_INVALID_ORGANIZATION_ID", "")) @@ -446,7 +446,7 @@ func (p ProjectHandler) GetProjectRole(w http.ResponseWriter, r *http.Request) { } projectRoleId, ok := vars["projectRoleId"] - log.Debugf("projectRoleId = [%v]\n", projectRoleId) + log.Debugf(r.Context(), "projectRoleId = [%v]\n", projectRoleId) if !ok { ErrorJSON(w, r, httpErrors.NewBadRequestError(fmt.Errorf("invalid projectRoleId"), "C_INVALID_PROJECT_ROLE_ID", "")) @@ -529,7 +529,7 @@ func (p ProjectHandler) GetProjectRoles(w http.ResponseWriter, r *http.Request) func (p ProjectHandler) AddProjectMember(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) organizationId, ok := vars["organizationId"] - log.Debugf("organizationId = [%v]\n", organizationId) + log.Debugf(r.Context(), "organizationId = [%v]\n", organizationId) if !ok { ErrorJSON(w, r, httpErrors.NewBadRequestError(fmt.Errorf("invalid organizationId"), "C_INVALID_ORGANIZATION_ID", "")) @@ -552,7 +552,7 @@ func (p ProjectHandler) AddProjectMember(w http.ResponseWriter, r *http.Request) pg := pagination.NewPagination(&urlParams) pns, err := p.usecase.GetProjectNamespaces(r.Context(), organizationId, projectId, pg) if err != nil { - log.Error(err) + log.Error(r.Context(), err) ErrorJSON(w, r, httpErrors.NewInternalServerError(err, "", "")) return } @@ -565,7 +565,7 @@ func (p ProjectHandler) AddProjectMember(w http.ResponseWriter, r *http.Request) for _, pmr := range projectMemberReq.ProjectMemberRequests { pu, err := p.usecase.GetProjectUser(r.Context(), pmr.ProjectUserId) if err != nil { - log.Error(err) + log.Error(r.Context(), err) ErrorJSON(w, r, httpErrors.NewBadRequestError(fmt.Errorf("invalid projectUserId"), "C_INVALID_PROJECT_USER_ID", "")) return @@ -573,7 +573,7 @@ func (p ProjectHandler) AddProjectMember(w http.ResponseWriter, r *http.Request) pr, err := p.usecase.GetProjectRole(r.Context(), pmr.ProjectRoleId) if err != nil { - log.Error(err) + log.Error(r.Context(), err) ErrorJSON(w, r, httpErrors.NewInternalServerError(err, "", "")) return } @@ -593,7 +593,7 @@ func (p ProjectHandler) AddProjectMember(w http.ResponseWriter, r *http.Request) } pmId, err := p.usecase.AddProjectMember(r.Context(), pm) if err != nil { - log.Errorf("projectMemberId: %s", pmId) + log.Errorf(r.Context(), "projectMemberId: %s", pmId) ErrorJSON(w, r, httpErrors.NewInternalServerError(err, "", "")) return } @@ -601,7 +601,7 @@ func (p ProjectHandler) AddProjectMember(w http.ResponseWriter, r *http.Request) // tasks for keycloak & k8s for stackId := range stackIds { if err := p.usecase.AssignKeycloakClientRoleToMember(r.Context(), organizationId, projectId, stackId, pmId); err != nil { - log.Error(err) + log.Error(r.Context(), err) ErrorJSON(w, r, httpErrors.NewInternalServerError(err, "", "")) return } @@ -628,7 +628,7 @@ func (p ProjectHandler) AddProjectMember(w http.ResponseWriter, r *http.Request) func (p ProjectHandler) GetProjectMember(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) organizationId, ok := vars["organizationId"] - log.Debugf("organizationId = [%v]\n", organizationId) + log.Debugf(r.Context(), "organizationId = [%v]\n", organizationId) if !ok { ErrorJSON(w, r, httpErrors.NewBadRequestError(fmt.Errorf("invalid organizationId"), "C_INVALID_ORGANIZATION_ID", "")) @@ -636,7 +636,7 @@ func (p ProjectHandler) GetProjectMember(w http.ResponseWriter, r *http.Request) } projectId, ok := vars["projectId"] - log.Debugf("projectId = [%v]\n", projectId) + log.Debugf(r.Context(), "projectId = [%v]\n", projectId) if !ok { ErrorJSON(w, r, httpErrors.NewBadRequestError(fmt.Errorf("invalid projectId"), "C_INVALID_PROJECT_ID", "")) @@ -644,7 +644,7 @@ func (p ProjectHandler) GetProjectMember(w http.ResponseWriter, r *http.Request) } projectMemberId, ok := vars["projectMemberId"] - log.Debugf("projectMemberId = [%v]\n", projectMemberId) + log.Debugf(r.Context(), "projectMemberId = [%v]\n", projectMemberId) if !ok { ErrorJSON(w, r, httpErrors.NewBadRequestError(fmt.Errorf("invalid projectMemberId"), "C_INVALID_PROJECT_MEMBER_ID", "")) @@ -698,7 +698,7 @@ func (p ProjectHandler) GetProjectMember(w http.ResponseWriter, r *http.Request) func (p ProjectHandler) GetProjectMembers(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) organizationId, ok := vars["organizationId"] - log.Debugf("organizationId = [%v]\n", organizationId) + log.Debugf(r.Context(), "organizationId = [%v]\n", organizationId) if !ok { ErrorJSON(w, r, httpErrors.NewBadRequestError(fmt.Errorf("invalid organizationId"), "C_INVALID_ORGANIZATION_ID", "")) @@ -786,7 +786,7 @@ func (p ProjectHandler) GetProjectMembers(w http.ResponseWriter, r *http.Request func (p ProjectHandler) GetProjectMemberCount(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) organizationId, ok := vars["organizationId"] - log.Debugf("organizationId = [%v]\n", organizationId) + log.Debugf(r.Context(), "organizationId = [%v]\n", organizationId) if !ok { ErrorJSON(w, r, httpErrors.NewBadRequestError(fmt.Errorf("invalid organizationId"), "C_INVALID_ORGANIZATION_ID", "")) @@ -830,7 +830,7 @@ func (p ProjectHandler) GetProjectMemberCount(w http.ResponseWriter, r *http.Req func (p ProjectHandler) RemoveProjectMember(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) organizationId, ok := vars["organizationId"] - log.Debugf("organizationId = [%v]\n", organizationId) + log.Debugf(r.Context(), "organizationId = [%v]\n", organizationId) if !ok { ErrorJSON(w, r, httpErrors.NewBadRequestError(fmt.Errorf("invalid organizationId"), "C_INVALID_ORGANIZATION_ID", "")) @@ -838,7 +838,7 @@ func (p ProjectHandler) RemoveProjectMember(w http.ResponseWriter, r *http.Reque } projectId, ok := vars["projectId"] - log.Debugf("projectId = [%v]\n", projectId) + log.Debugf(r.Context(), "projectId = [%v]\n", projectId) if !ok { ErrorJSON(w, r, httpErrors.NewBadRequestError(fmt.Errorf("invalid projectId"), "C_INVALID_PROJECT_ID", "")) @@ -846,7 +846,7 @@ func (p ProjectHandler) RemoveProjectMember(w http.ResponseWriter, r *http.Reque } projectMemberId, ok := vars["projectMemberId"] - log.Debugf("projectMemberId = [%v]\n", projectMemberId) + log.Debugf(r.Context(), "projectMemberId = [%v]\n", projectMemberId) if !ok { ErrorJSON(w, r, httpErrors.NewBadRequestError(fmt.Errorf("invalid projectMemberId"), "C_INVALID_PROJECT_MEMBER_ID", "")) @@ -856,7 +856,7 @@ func (p ProjectHandler) RemoveProjectMember(w http.ResponseWriter, r *http.Reque // tasks for keycloak & k8s pns, err := p.usecase.GetProjectNamespaces(r.Context(), organizationId, projectId, nil) if err != nil { - log.Error(err) + log.Error(r.Context(), err) ErrorJSON(w, r, httpErrors.NewInternalServerError(err, "", "")) return } @@ -866,7 +866,7 @@ func (p ProjectHandler) RemoveProjectMember(w http.ResponseWriter, r *http.Reque } for stackId := range stackIds { if err := p.usecase.UnassignKeycloakClientRoleToMember(r.Context(), organizationId, projectId, stackId, projectMemberId); err != nil { - log.Error(err) + log.Error(r.Context(), err) ErrorJSON(w, r, httpErrors.NewInternalServerError(err, "", "")) return } @@ -896,7 +896,7 @@ func (p ProjectHandler) RemoveProjectMember(w http.ResponseWriter, r *http.Reque func (p ProjectHandler) RemoveProjectMembers(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) organizationId, ok := vars["organizationId"] - log.Debugf("organizationId = [%v]\n", organizationId) + log.Debugf(r.Context(), "organizationId = [%v]\n", organizationId) if !ok { ErrorJSON(w, r, httpErrors.NewBadRequestError(fmt.Errorf("invalid organizationId"), "C_INVALID_ORGANIZATION_ID", "")) @@ -904,7 +904,7 @@ func (p ProjectHandler) RemoveProjectMembers(w http.ResponseWriter, r *http.Requ } projectId, ok := vars["projectId"] - log.Debugf("projectId = [%v]\n", projectId) + log.Debugf(r.Context(), "projectId = [%v]\n", projectId) if !ok { ErrorJSON(w, r, httpErrors.NewBadRequestError(fmt.Errorf("invalid projectId"), "C_INVALID_PROJECT_ID", "")) @@ -920,7 +920,7 @@ func (p ProjectHandler) RemoveProjectMembers(w http.ResponseWriter, r *http.Requ // tasks for keycloak & k8s pns, err := p.usecase.GetProjectNamespaces(r.Context(), organizationId, projectId, nil) if err != nil { - log.Error(err) + log.Error(r.Context(), err) ErrorJSON(w, r, httpErrors.NewInternalServerError(err, "", "")) return } @@ -934,7 +934,7 @@ func (p ProjectHandler) RemoveProjectMembers(w http.ResponseWriter, r *http.Requ // tasks for keycloak & k8s for stackId := range stackIds { if err := p.usecase.UnassignKeycloakClientRoleToMember(r.Context(), organizationId, projectId, stackId, pm.ProjectMemberId); err != nil { - log.Error(err) + log.Error(r.Context(), err) ErrorJSON(w, r, httpErrors.NewInternalServerError(err, "", "")) return } @@ -965,7 +965,7 @@ func (p ProjectHandler) RemoveProjectMembers(w http.ResponseWriter, r *http.Requ func (p ProjectHandler) UpdateProjectMemberRole(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) organizationId, ok := vars["organizationId"] - log.Debugf("organizationId = [%v]\n", organizationId) + log.Debugf(r.Context(), "organizationId = [%v]\n", organizationId) if !ok { ErrorJSON(w, r, httpErrors.NewBadRequestError(fmt.Errorf("invalid organizationId"), "C_INVALID_ORGANIZATION_ID", "")) @@ -973,7 +973,7 @@ func (p ProjectHandler) UpdateProjectMemberRole(w http.ResponseWriter, r *http.R } projectId, ok := vars["projectId"] - log.Debugf("projectId = [%v]\n", projectId) + log.Debugf(r.Context(), "projectId = [%v]\n", projectId) if !ok { ErrorJSON(w, r, httpErrors.NewBadRequestError(fmt.Errorf("invalid projectId"), "C_INVALID_PROJECT_ID", "")) @@ -996,7 +996,7 @@ func (p ProjectHandler) UpdateProjectMemberRole(w http.ResponseWriter, r *http.R now := time.Now() pm, err := p.usecase.GetProjectMember(r.Context(), projectMemberId) if err != nil { - log.Error(err) + log.Error(r.Context(), err) ErrorJSON(w, r, httpErrors.NewInternalServerError(err, "", "")) return } @@ -1008,7 +1008,7 @@ func (p ProjectHandler) UpdateProjectMemberRole(w http.ResponseWriter, r *http.R pns, err := p.usecase.GetProjectNamespaces(r.Context(), organizationId, projectId, nil) if err != nil { - log.Error(err) + log.Error(r.Context(), err) ErrorJSON(w, r, httpErrors.NewInternalServerError(err, "", "")) return } @@ -1019,7 +1019,7 @@ func (p ProjectHandler) UpdateProjectMemberRole(w http.ResponseWriter, r *http.R // tasks for keycloak & k8s. Unassign old role for stackId := range stackIds { if err := p.usecase.UnassignKeycloakClientRoleToMember(r.Context(), organizationId, projectId, stackId, projectMemberId); err != nil { - log.Error(err) + log.Error(r.Context(), err) ErrorJSON(w, r, httpErrors.NewInternalServerError(err, "", "")) return } @@ -1037,7 +1037,7 @@ func (p ProjectHandler) UpdateProjectMemberRole(w http.ResponseWriter, r *http.R // tasks for keycloak & k8s. Assign new role for stackId := range stackIds { if err := p.usecase.AssignKeycloakClientRoleToMember(r.Context(), organizationId, projectId, stackId, projectMemberId); err != nil { - log.Error(err) + log.Error(r.Context(), err) ErrorJSON(w, r, httpErrors.NewInternalServerError(err, "", "")) return } @@ -1062,7 +1062,7 @@ func (p ProjectHandler) UpdateProjectMemberRole(w http.ResponseWriter, r *http.R func (p ProjectHandler) UpdateProjectMembersRole(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) organizationId, ok := vars["organizationId"] - log.Debugf("organizationId = [%v]\n", organizationId) + log.Debugf(r.Context(), "organizationId = [%v]\n", organizationId) if !ok { ErrorJSON(w, r, httpErrors.NewBadRequestError(fmt.Errorf("invalid organizationId"), "C_INVALID_ORGANIZATION_ID", "")) @@ -1070,7 +1070,7 @@ func (p ProjectHandler) UpdateProjectMembersRole(w http.ResponseWriter, r *http. } projectId, ok := vars["projectId"] - log.Debugf("projectId = [%v]\n", projectId) + log.Debugf(r.Context(), "projectId = [%v]\n", projectId) if !ok { ErrorJSON(w, r, httpErrors.NewBadRequestError(fmt.Errorf("invalid projectId"), "C_INVALID_PROJECT_ID", "")) @@ -1086,7 +1086,7 @@ func (p ProjectHandler) UpdateProjectMembersRole(w http.ResponseWriter, r *http. pns, err := p.usecase.GetProjectNamespaces(r.Context(), organizationId, projectId, nil) if err != nil { - log.Error(err) + log.Error(r.Context(), err) ErrorJSON(w, r, httpErrors.NewInternalServerError(err, "", "")) return } @@ -1098,7 +1098,7 @@ func (p ProjectHandler) UpdateProjectMembersRole(w http.ResponseWriter, r *http. for _, pmr := range projectMemberReq.ProjectMemberRoleRequests { pm, err := p.usecase.GetProjectMember(r.Context(), pmr.ProjectMemberId) if err != nil { - log.Error(err) + log.Error(r.Context(), err) ErrorJSON(w, r, httpErrors.NewInternalServerError(err, "", "")) return } @@ -1110,7 +1110,7 @@ func (p ProjectHandler) UpdateProjectMembersRole(w http.ResponseWriter, r *http. for stackId := range stackIds { if err := p.usecase.UnassignKeycloakClientRoleToMember(r.Context(), organizationId, projectId, stackId, pm.ID); err != nil { - log.Error(err) + log.Error(r.Context(), err) ErrorJSON(w, r, httpErrors.NewInternalServerError(err, "", "")) return } @@ -1128,7 +1128,7 @@ func (p ProjectHandler) UpdateProjectMembersRole(w http.ResponseWriter, r *http. for stackId := range stackIds { if err := p.usecase.AssignKeycloakClientRoleToMember(r.Context(), organizationId, projectId, stackId, pm.ID); err != nil { - log.Error(err) + log.Error(r.Context(), err) ErrorJSON(w, r, httpErrors.NewInternalServerError(err, "", "")) return } @@ -1299,7 +1299,7 @@ func (p ProjectHandler) GetProjectNamespaces(w http.ResponseWriter, r *http.Requ for _, pn := range pns { var pnr domain.ProjectNamespaceResponse if err = serializer.Map(pn, &pnr); err != nil { - log.Error(err) + log.Error(r.Context(), err) ErrorJSON(w, r, err) return } @@ -1383,7 +1383,7 @@ func (p ProjectHandler) GetProjectNamespace(w http.ResponseWriter, r *http.Reque var pnr domain.ProjectNamespaceResponse if err = serializer.Map(*pn, &pnr); err != nil { - log.Error(err) + log.Error(r.Context(), err) ErrorJSON(w, r, err) return } @@ -1413,7 +1413,7 @@ func (p ProjectHandler) GetProjectNamespace(w http.ResponseWriter, r *http.Reque func (p ProjectHandler) UpdateProjectNamespace(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) organizationId, ok := vars["organizationId"] - log.Debugf("organizationId = [%v]\n", organizationId) + log.Debugf(r.Context(), "organizationId = [%v]\n", organizationId) if !ok { ErrorJSON(w, r, httpErrors.NewBadRequestError(fmt.Errorf("invalid organizationId"), "C_INVALID_ORGANIZATION_ID", "")) @@ -1632,7 +1632,7 @@ func (p ProjectHandler) GetProjectNamespaceK8sResources(w http.ResponseWriter, r var out domain.GetProjectNamespaceK8sResourcesResponse if err = serializer.Map(k8sResources, &out.K8sResources); err != nil { - log.Error(err) + log.Error(r.Context(), err) } ResponseJSON(w, r, http.StatusOK, out) } @@ -1685,7 +1685,7 @@ func (p ProjectHandler) GetProjectNamespaceResourcesUsage(w http.ResponseWriter, var out domain.GetProjectNamespaceResourcesUsageResponse if err = serializer.Map(resourcesUsage, &out.ResourcesUsage); err != nil { - log.Error(err) + log.Error(r.Context(), err) } ResponseJSON(w, r, http.StatusOK, out) } diff --git a/internal/delivery/http/user.go b/internal/delivery/http/user.go index bfe4d048..203194db 100644 --- a/internal/delivery/http/user.go +++ b/internal/delivery/http/user.go @@ -80,7 +80,7 @@ func (u UserHandler) Create(w http.ResponseWriter, r *http.Request) { input := domain.CreateUserRequest{} err := UnmarshalRequestInput(r, &input) if err != nil { - log.ErrorfWithContext(r.Context(), "error is :%s(%T)", err.Error(), err) + log.Errorf(r.Context(), "error is :%s(%T)", err.Error(), err) ErrorJSON(w, r, err) return @@ -97,7 +97,7 @@ func (u UserHandler) Create(w http.ResponseWriter, r *http.Request) { roles, err := u.roleUsecase.ListTksRoles(r.Context(), organizationId, nil) if err != nil { - log.ErrorfWithContext(r.Context(), "error is :%s(%T)", err.Error(), err) + log.Errorf(r.Context(), "error is :%s(%T)", err.Error(), err) ErrorJSON(w, r, err) return } @@ -110,7 +110,7 @@ func (u UserHandler) Create(w http.ResponseWriter, r *http.Request) { resUser, err := u.usecase.Create(ctx, &user) if err != nil { - log.ErrorfWithContext(r.Context(), "error is :%s(%T)", err.Error(), err) + log.Errorf(r.Context(), "error is :%s(%T)", err.Error(), err) if _, status := httpErrors.ErrorResponse(err); status == http.StatusConflict { ErrorJSON(w, r, httpErrors.NewConflictError(err, "", "")) return @@ -156,7 +156,7 @@ func (u UserHandler) Get(w http.ResponseWriter, r *http.Request) { user, err := u.usecase.GetByAccountId(r.Context(), userId, organizationId) if err != nil { - log.ErrorfWithContext(r.Context(), "error is :%s(%T)", err.Error(), err) + log.Errorf(r.Context(), "error is :%s(%T)", err.Error(), err) if _, status := httpErrors.ErrorResponse(err); status == http.StatusNotFound { ErrorJSON(w, r, httpErrors.NewBadRequestError(err, "", "")) @@ -203,7 +203,7 @@ func (u UserHandler) List(w http.ResponseWriter, r *http.Request) { pg := pagination.NewPagination(&urlParams) users, err := u.usecase.ListWithPagination(r.Context(), organizationId, pg) if err != nil { - log.ErrorfWithContext(r.Context(), "error is :%s(%T)", err.Error(), err) + log.Errorf(r.Context(), "error is :%s(%T)", err.Error(), err) ErrorJSON(w, r, err) return } @@ -254,7 +254,7 @@ func (u UserHandler) Delete(w http.ResponseWriter, r *http.Request) { ErrorJSON(w, r, httpErrors.NewBadRequestError(err, "", "")) return } - log.ErrorfWithContext(r.Context(), "error is :%s(%T)", err.Error(), err) + log.Errorf(r.Context(), "error is :%s(%T)", err.Error(), err) ErrorJSON(w, r, err) return @@ -292,7 +292,7 @@ func (u UserHandler) Update(w http.ResponseWriter, r *http.Request) { input := domain.UpdateUserRequest{} err := UnmarshalRequestInput(r, &input) if err != nil { - log.ErrorfWithContext(r.Context(), "error is :%s(%T)", err.Error(), err) + log.Errorf(r.Context(), "error is :%s(%T)", err.Error(), err) ErrorJSON(w, r, err) return @@ -311,7 +311,7 @@ func (u UserHandler) Update(w http.ResponseWriter, r *http.Request) { roles, err := u.roleUsecase.ListTksRoles(r.Context(), organizationId, nil) if err != nil { - log.ErrorfWithContext(r.Context(), "error is :%s(%T)", err.Error(), err) + log.Errorf(r.Context(), "error is :%s(%T)", err.Error(), err) ErrorJSON(w, r, err) return } @@ -438,7 +438,7 @@ func (u UserHandler) UpdateMyProfile(w http.ResponseWriter, r *http.Request) { input := domain.UpdateMyProfileRequest{} err := UnmarshalRequestInput(r, &input) if err != nil { - log.ErrorfWithContext(r.Context(), "error is :%s(%T)", err.Error(), err) + log.Errorf(r.Context(), "error is :%s(%T)", err.Error(), err) ErrorJSON(w, r, err) return @@ -446,7 +446,7 @@ func (u UserHandler) UpdateMyProfile(w http.ResponseWriter, r *http.Request) { err = u.usecase.ValidateAccount(r.Context(), requestUserInfo.GetUserId(), input.Password, requestUserInfo.GetOrganizationId()) if err != nil { - log.ErrorfWithContext(r.Context(), "error is :%s(%T)", err.Error(), err) + log.Errorf(r.Context(), "error is :%s(%T)", err.Error(), err) ErrorJSON(w, r, err) return } @@ -522,7 +522,7 @@ func (u UserHandler) UpdateMyPassword(w http.ResponseWriter, r *http.Request) { ErrorJSON(w, r, httpErrors.NewBadRequestError(err, "", "")) return } - log.ErrorfWithContext(r.Context(), "error is :%s(%T)", err.Error(), err) + log.Errorf(r.Context(), "error is :%s(%T)", err.Error(), err) ErrorJSON(w, r, err) return @@ -690,7 +690,7 @@ func (u UserHandler) Admin_Create(w http.ResponseWriter, r *http.Request) { input := admin_domain.CreateUserRequest{} err := UnmarshalRequestInput(r, &input) if err != nil { - log.ErrorfWithContext(r.Context(), "error is :%s(%T)", err.Error(), err) + log.Errorf(r.Context(), "error is :%s(%T)", err.Error(), err) ErrorJSON(w, r, err) return @@ -721,7 +721,7 @@ func (u UserHandler) Admin_Create(w http.ResponseWriter, r *http.Request) { roles, err := u.roleUsecase.ListTksRoles(r.Context(), organizationId, nil) if err != nil { - log.ErrorfWithContext(r.Context(), "error is :%s(%T)", err.Error(), err) + log.Errorf(r.Context(), "error is :%s(%T)", err.Error(), err) ErrorJSON(w, r, err) return } @@ -741,7 +741,7 @@ func (u UserHandler) Admin_Create(w http.ResponseWriter, r *http.Request) { resUser, err := u.usecase.Create(r.Context(), &user) if err != nil { - log.ErrorfWithContext(r.Context(), "error is :%s(%T)", err.Error(), err) + log.Errorf(r.Context(), "error is :%s(%T)", err.Error(), err) if _, status := httpErrors.ErrorResponse(err); status == http.StatusConflict { ErrorJSON(w, r, httpErrors.NewConflictError(err, "", "")) return @@ -753,7 +753,7 @@ func (u UserHandler) Admin_Create(w http.ResponseWriter, r *http.Request) { err = u.usecase.SendEmailForTemporaryPassword(r.Context(), user.AccountId, organizationId, user.Password) if err != nil { - log.ErrorfWithContext(r.Context(), "error is :%s(%T)", err.Error(), err) + log.Errorf(r.Context(), "error is :%s(%T)", err.Error(), err) ErrorJSON(w, r, err) return } @@ -793,7 +793,7 @@ func (u UserHandler) Admin_List(w http.ResponseWriter, r *http.Request) { pg := pagination.NewPagination(&urlParams) users, err := u.usecase.ListWithPagination(r.Context(), organizationId, pg) if err != nil { - log.ErrorfWithContext(r.Context(), "error is :%s(%T)", err.Error(), err) + log.Errorf(r.Context(), "error is :%s(%T)", err.Error(), err) ErrorJSON(w, r, err) return } @@ -839,7 +839,7 @@ func (u UserHandler) Admin_Get(w http.ResponseWriter, r *http.Request) { user, err := u.usecase.GetByAccountId(r.Context(), userId, organizationId) if err != nil { - log.ErrorfWithContext(r.Context(), "error is :%s(%T)", err.Error(), err) + log.Errorf(r.Context(), "error is :%s(%T)", err.Error(), err) if _, status := httpErrors.ErrorResponse(err); status == http.StatusNotFound { ErrorJSON(w, r, httpErrors.NewBadRequestError(err, "", "")) @@ -889,7 +889,7 @@ func (u UserHandler) Admin_Delete(w http.ResponseWriter, r *http.Request) { if organizationId != "master" { err := UnmarshalRequestInput(r, &input) if err != nil { - log.ErrorfWithContext(r.Context(), "error is :%s(%T)", err.Error(), err) + log.Errorf(r.Context(), "error is :%s(%T)", err.Error(), err) ErrorJSON(w, r, err) return @@ -914,7 +914,7 @@ func (u UserHandler) Admin_Delete(w http.ResponseWriter, r *http.Request) { ErrorJSON(w, r, httpErrors.NewBadRequestError(err, "", "")) return } - log.ErrorfWithContext(r.Context(), "error is :%s(%T)", err.Error(), err) + log.Errorf(r.Context(), "error is :%s(%T)", err.Error(), err) ErrorJSON(w, r, err) return @@ -952,7 +952,7 @@ func (u UserHandler) Admin_Update(w http.ResponseWriter, r *http.Request) { input := admin_domain.UpdateUserRequest{} err := UnmarshalRequestInput(r, &input) if err != nil { - log.ErrorfWithContext(r.Context(), "error is :%s(%T)", err.Error(), err) + log.Errorf(r.Context(), "error is :%s(%T)", err.Error(), err) ErrorJSON(w, r, err) return @@ -987,7 +987,7 @@ func (u UserHandler) Admin_Update(w http.ResponseWriter, r *http.Request) { roles, err := u.roleUsecase.ListTksRoles(r.Context(), organizationId, nil) if err != nil { - log.ErrorfWithContext(r.Context(), "error is :%s(%T)", err.Error(), err) + log.Errorf(r.Context(), "error is :%s(%T)", err.Error(), err) ErrorJSON(w, r, err) return } diff --git a/internal/gorm/gorm.go b/internal/gorm/gorm.go index 37bd2deb..30b95d01 100644 --- a/internal/gorm/gorm.go +++ b/internal/gorm/gorm.go @@ -47,19 +47,19 @@ func (l *customGormLogger) LogMode(level logger.LogLevel) logger.Interface { func (l *customGormLogger) Info(ctx context.Context, msg string, data ...interface{}) { if l.LogLevel >= logger.Info { - internalLogger.InfofWithContext(ctx, l.infoStr+msg, append([]interface{}{utils.FileWithLineNum()}, data...)...) + internalLogger.Infof(ctx, l.infoStr+msg, append([]interface{}{utils.FileWithLineNum()}, data...)...) } } func (l *customGormLogger) Warn(ctx context.Context, msg string, data ...interface{}) { if l.LogLevel >= logger.Warn { - internalLogger.WarnfWithContext(ctx, l.warnStr+msg, append([]interface{}{utils.FileWithLineNum()}, data...)...) + internalLogger.Warnf(ctx, l.warnStr+msg, append([]interface{}{utils.FileWithLineNum()}, data...)...) } } func (l *customGormLogger) Error(ctx context.Context, msg string, data ...interface{}) { if l.LogLevel >= logger.Error { - internalLogger.ErrorfWithContext(ctx, l.errStr+msg, append([]interface{}{utils.FileWithLineNum()}, data...)...) + internalLogger.Errorf(ctx, l.errStr+msg, append([]interface{}{utils.FileWithLineNum()}, data...)...) } } @@ -73,33 +73,33 @@ func (l *customGormLogger) Trace(ctx context.Context, begin time.Time, fc func() case err != nil && l.LogLevel >= logger.Error && (!errors.Is(err, logger.ErrRecordNotFound) || !l.IgnoreRecordNotFoundError): sql, rows := fc() if rows == -1 { - internalLogger.ErrorfWithContext(ctx, l.traceErrStr, utils.FileWithLineNum(), err, float64(elapsed.Nanoseconds())/1e6, "-", sql) + internalLogger.Errorf(ctx, l.traceErrStr, utils.FileWithLineNum(), err, float64(elapsed.Nanoseconds())/1e6, "-", sql) //l.Printf(l.traceErrStr, utils.FileWithLineNum(), err, float64(elapsed.Nanoseconds())/1e6, "-", sql) } else { - internalLogger.ErrorfWithContext(ctx, l.traceErrStr, utils.FileWithLineNum(), err, float64(elapsed.Nanoseconds())/1e6, rows, sql) + internalLogger.Errorf(ctx, l.traceErrStr, utils.FileWithLineNum(), err, float64(elapsed.Nanoseconds())/1e6, rows, sql) //l.Printf(l.traceErrStr, utils.FileWithLineNum(), err, float64(elapsed.Nanoseconds())/1e6, rows, sql) } case elapsed > l.SlowThreshold && l.SlowThreshold != 0 && l.LogLevel >= logger.Warn: sql, rows := fc() slowLog := fmt.Sprintf("SLOW SQL >= %v", l.SlowThreshold) if rows == -1 { - internalLogger.WarnfWithContext(ctx, l.traceWarnStr, utils.FileWithLineNum(), slowLog, float64(elapsed.Nanoseconds())/1e6, "-", sql) + internalLogger.Warnf(ctx, l.traceWarnStr, utils.FileWithLineNum(), slowLog, float64(elapsed.Nanoseconds())/1e6, "-", sql) //l.Printf(l.traceWarnStr, utils.FileWithLineNum(), slowLog, float64(elapsed.Nanoseconds())/1e6, "-", sql) } else { - internalLogger.WarnfWithContext(ctx, l.traceWarnStr, utils.FileWithLineNum(), slowLog, float64(elapsed.Nanoseconds())/1e6, rows, sql) + internalLogger.Warnf(ctx, l.traceWarnStr, utils.FileWithLineNum(), slowLog, float64(elapsed.Nanoseconds())/1e6, rows, sql) //l.Printf(l.traceWarnStr, utils.FileWithLineNum(), slowLog, float64(elapsed.Nanoseconds())/1e6, rows, sql) } case l.LogLevel == logger.Info: sql, rows := fc() if rows == -1 { - internalLogger.InfofWithContext(ctx, l.traceStr, utils.FileWithLineNum(), float64(elapsed.Nanoseconds())/1e6, "-", sql) + internalLogger.Infof(ctx, l.traceStr, utils.FileWithLineNum(), float64(elapsed.Nanoseconds())/1e6, "-", sql) //l.Printf(l.traceStr, utils.FileWithLineNum(), float64(elapsed.Nanoseconds())/1e6, "-", sql) } else { - internalLogger.InfofWithContext(ctx, l.traceStr, utils.FileWithLineNum(), float64(elapsed.Nanoseconds())/1e6, rows, sql) + internalLogger.Infof(ctx, l.traceStr, utils.FileWithLineNum(), float64(elapsed.Nanoseconds())/1e6, rows, sql) //l.Printf(l.traceStr, utils.FileWithLineNum(), float64(elapsed.Nanoseconds())/1e6, rows, sql) } default: - internalLogger.Info("Trace") + internalLogger.Info(ctx, "Trace") } } diff --git a/internal/helper/ssh.go b/internal/helper/ssh.go index 7b65b929..08505708 100644 --- a/internal/helper/ssh.go +++ b/internal/helper/ssh.go @@ -7,7 +7,6 @@ import ( "time" "github.com/gorilla/websocket" - "github.com/openinfradev/tks-api/pkg/log" "golang.org/x/crypto/ssh" ) @@ -114,12 +113,12 @@ func (sws *LogicSshWsSession) receiveWsMsg(exitCh chan bool) { //read websocket msg _, wsData, err := wsConn.ReadMessage() if err != nil { - log.Error(err) - log.Error("reading webSocket message failed") + //log.Error(err) + //log.Error("reading webSocket message failed") return } - cmd := bytes.NewBuffer(wsData).String() - log.Debug(cmd) + //cmd := bytes.NewBuffer(wsData).String() + //log.Debug(cmd) //unmashal bytes into struct /* if err := json.Unmarshal(wsData, &msgObj); err != nil { @@ -140,7 +139,8 @@ func (sws *LogicSshWsSession) receiveWsMsg(exitCh chan bool) { // sendWebsocketInputCommandToSshSessionStdinPipe func (sws *LogicSshWsSession) sendWebsocketInputCommandToSshSessionStdinPipe(cmdBytes []byte) { if _, err := sws.stdinPipe.Write(cmdBytes); err != nil { - log.Error("ws cmd bytes write to ssh.stdin pipe failed") + + //log.Error("ws cmd bytes write to ssh.stdin pipe failed") } } @@ -162,11 +162,11 @@ func (sws *LogicSshWsSession) sendComboOutput(exitCh chan bool) { if len(bs) > 0 { err := wsConn.WriteMessage(websocket.TextMessage, bs) if err != nil { - log.Error("ssh sending combo output to webSocket failed") + //log.Error("ssh sending combo output to webSocket failed") } _, err = sws.logBuff.Write(bs) if err != nil { - log.Error("combo output to log buffer failed") + //log.Error("combo output to log buffer failed") } sws.comboOutput.buffer.Reset() } @@ -179,7 +179,7 @@ func (sws *LogicSshWsSession) sendComboOutput(exitCh chan bool) { func (sws *LogicSshWsSession) Wait(quitChan chan bool) { if err := sws.session.Wait(); err != nil { - log.Error("ssh session wait failed") + //log.Error("ssh session wait failed") setQuit(quitChan) } } diff --git a/internal/helper/util.go b/internal/helper/util.go index 5a7cae86..9e4e573a 100644 --- a/internal/helper/util.go +++ b/internal/helper/util.go @@ -1,7 +1,7 @@ package helper import ( - "bytes" + "context" "crypto/rand" "encoding/json" "fmt" @@ -37,20 +37,10 @@ func ModelToJson(in any) string { return s } -func Transcode(in, out interface{}) { - buf := new(bytes.Buffer) - if err := json.NewEncoder(buf).Encode(in); err != nil { - log.Error(err) - } - if err := json.NewDecoder(buf).Decode(out); err != nil { - log.Error(err) - } -} - -func GenerateEmailCode() (string, error) { +func GenerateEmailCode(ctx context.Context) (string, error) { num, err := rand.Int(rand.Reader, big.NewInt(900000)) if err != nil { - log.Error(err) + log.Error(ctx, err) return "", err } num = num.Add(num, big.NewInt(100000)) @@ -64,7 +54,7 @@ func IsDurationExpired(targetTime time.Time, duration time.Duration) bool { return diff > duration } -func SplitAddress(url string) (address string, port int) { +func SplitAddress(ctx context.Context, url string) (address string, port int) { url = strings.TrimSuffix(url, "\n") arr := strings.Split(url, ":") address = arr[0] + ":" + arr[1] @@ -79,7 +69,7 @@ func SplitAddress(url string) (address string, port int) { } port = portNum - log.Infof("address : %s, port : %d", address, port) + log.Infof(ctx, "address : %s, port : %d", address, port) return } diff --git a/internal/keycloak/keycloak.go b/internal/keycloak/keycloak.go index 610d59ad..277f1296 100644 --- a/internal/keycloak/keycloak.go +++ b/internal/keycloak/keycloak.go @@ -16,34 +16,34 @@ import ( ) type IKeycloak interface { - InitializeKeycloak() error + InitializeKeycloak(ctx context.Context) 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 + LoginAdmin(ctx context.Context, accountId string, password string) (*model.User, error) + Login(ctx context.Context, accountId string, password string, organizationId string) (*model.User, error) + Logout(ctx context.Context, sessionId string, organizationId string) error - CreateRealm(organizationId string) (string, error) - GetRealm(organizationId string) (*model.Organization, error) - GetRealms() ([]*model.Organization, error) - DeleteRealm(organizationId string) error - UpdateRealm(organizationId string, organizationConfig model.Organization) error + CreateRealm(ctx context.Context, organizationId string) (string, error) + GetRealm(ctx context.Context, organizationId string) (*model.Organization, error) + GetRealms(ctx context.Context) ([]*model.Organization, error) + DeleteRealm(ctx context.Context, organizationId string) error + UpdateRealm(ctx context.Context, organizationId string, organizationConfig model.Organization) error - CreateUser(organizationId string, user *gocloak.User) (string, error) - GetUser(organizationId string, userAccountId string) (*gocloak.User, error) - GetUsers(organizationId string) ([]*gocloak.User, error) - DeleteUser(organizationId string, userAccountId string) error - UpdateUser(organizationId string, user *gocloak.User) error - JoinGroup(organizationId string, userId string, groupName string) error - LeaveGroup(organizationId string, userId string, groupName string) error + CreateUser(ctx context.Context, organizationId string, user *gocloak.User) (string, error) + GetUser(ctx context.Context, organizationId string, userAccountId string) (*gocloak.User, error) + GetUsers(ctx context.Context, organizationId string) ([]*gocloak.User, error) + DeleteUser(ctx context.Context, organizationId string, userAccountId string) error + UpdateUser(ctx context.Context, organizationId string, user *gocloak.User) error + JoinGroup(ctx context.Context, organizationId string, userId string, groupName string) error + LeaveGroup(ctx context.Context, organizationId string, userId string, groupName string) error - EnsureClientRoleWithClientName(organizationId string, clientName string, roleName string) error - DeleteClientRoleWithClientName(organizationId string, clientName string, roleName string) error + EnsureClientRoleWithClientName(ctx context.Context, organizationId string, clientName string, roleName string) error + DeleteClientRoleWithClientName(ctx context.Context, organizationId string, clientName string, roleName string) error - AssignClientRoleToUser(organizationId string, userId string, clientName string, roleName string) error - UnassignClientRoleToUser(organizationId string, userId string, clientName string, roleName string) error + AssignClientRoleToUser(ctx context.Context, organizationId string, userId string, clientName string, roleName string) error + UnassignClientRoleToUser(ctx context.Context, organizationId string, userId string, clientName string, roleName string) error - VerifyAccessToken(token string, organizationId string) (bool, error) - GetSessions(userId string, organizationId string) (*[]string, error) + VerifyAccessToken(ctx context.Context, token string, organizationId string) (bool, error) + GetSessions(ctx context.Context, userId string, organizationId string) (*[]string, error) } type Keycloak struct { config *Config @@ -51,22 +51,20 @@ type Keycloak struct { adminCliToken *gocloak.JWT } -func (k *Keycloak) LoginAdmin(accountId string, password string) (*model.User, error) { - ctx := context.Background() - JWTToken, err := k.client.LoginAdmin(ctx, accountId, password, DefaultMasterRealm) +func (k *Keycloak) LoginAdmin(ctx context.Context, accountId string, password string) (*model.User, error) { + JWTToken, err := k.client.LoginAdmin(context.Background(), accountId, password, DefaultMasterRealm) if err != nil { - log.Error(err) + log.Error(ctx, err) return nil, err } return &model.User{Token: JWTToken.AccessToken}, nil } -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) +func (k *Keycloak) Login(ctx context.Context, accountId string, password string, organizationId string) (*model.User, error) { + JWTToken, err := k.client.Login(context.Background(), DefaultClientID, k.config.ClientSecret, organizationId, accountId, password) if err != nil { - log.Error(err) + log.Error(ctx, err) return nil, err } return &model.User{Token: JWTToken.AccessToken}, nil @@ -77,16 +75,15 @@ func New(config *Config) IKeycloak { config: config, } } -func (k *Keycloak) InitializeKeycloak() error { +func (k *Keycloak) InitializeKeycloak(ctx context.Context) error { k.client = gocloak.NewClient(k.config.Address) - ctx := context.Background() restyClient := k.client.RestyClient() restyClient.SetTLSClientConfig(&tls.Config{InsecureSkipVerify: true}) var token *gocloak.JWT var err error - if token, err = k.client.LoginAdmin(ctx, k.config.AdminId, k.config.AdminPassword, DefaultMasterRealm); err != nil { - log.Fatal(err) + if token, err = k.client.LoginAdmin(context.Background(), k.config.AdminId, k.config.AdminPassword, DefaultMasterRealm); err != nil { + log.Fatal(ctx, err) return err } k.adminCliToken = token @@ -98,18 +95,18 @@ func (k *Keycloak) InitializeKeycloak() error { group, err := k.ensureGroupByName(ctx, token, DefaultMasterRealm, "tks-admin@master") if err != nil { - log.Fatal(err) + log.Fatal(ctx, err) return err } user, err := k.ensureUserByName(ctx, token, DefaultMasterRealm, k.config.AdminId, k.config.AdminPassword) if err != nil { - log.Fatal(err) + log.Fatal(ctx, err) return err } if err := k.addUserToGroup(ctx, token, DefaultMasterRealm, *user.ID, *group.ID); err != nil { - log.Fatal(err) + log.Fatal(ctx, err) return err } @@ -117,27 +114,27 @@ func (k *Keycloak) InitializeKeycloak() error { redirectURIs = append(redirectURIs, viper.GetString("external-address")+"/*") tksClient, err := k.ensureClient(ctx, token, DefaultMasterRealm, DefaultClientID, k.config.ClientSecret, &redirectURIs) if err != nil { - log.Fatal(err) + log.Fatal(ctx, err) return err } // for _, defaultMapper := range defaultProtocolTksMapper { if err := k.ensureClientProtocolMappers(ctx, token, DefaultMasterRealm, *tksClient.ClientID, "openid", defaultMapper); err != nil { - log.Fatal(err) + log.Fatal(ctx, err) return err } } adminCliClient, err := k.ensureClient(ctx, token, DefaultMasterRealm, AdminCliClientID, k.config.ClientSecret, nil) if err != nil { - log.Fatal(err) + log.Fatal(ctx, err) return err } for _, defaultMapper := range defaultProtocolTksMapper { if err := k.ensureClientProtocolMappers(ctx, token, DefaultMasterRealm, *adminCliClient.ClientID, "openid", defaultMapper); err != nil { - log.Fatal(err) + log.Fatal(ctx, err) return err } } @@ -147,11 +144,11 @@ func (k *Keycloak) InitializeKeycloak() error { go func() { for { if token, err := k.client.RefreshToken(context.Background(), k.adminCliToken.RefreshToken, AdminCliClientID, k.config.ClientSecret, DefaultMasterRealm); err != nil { - log.Errorf("[Refresh]error is :%s(%T)", err.Error(), err) - log.Info("[Do Keycloak Admin CLI Login]") + log.Errorf(ctx, "[Refresh]error is :%s(%T)", err.Error(), err) + log.Info(ctx, "[Do Keycloak Admin CLI Login]") k.adminCliToken, err = k.client.LoginAdmin(ctx, k.config.AdminId, k.config.AdminPassword, DefaultMasterRealm) if err != nil { - log.Errorf("[LoginAdmin]error is :%s(%T)", err.Error(), err) + log.Errorf(ctx, "[LoginAdmin]error is :%s(%T)", err.Error(), err) } } else { k.adminCliToken = token @@ -163,12 +160,11 @@ func (k *Keycloak) InitializeKeycloak() error { return nil } -func (k *Keycloak) CreateRealm(organizationId string) (string, error) { +func (k *Keycloak) CreateRealm(ctx context.Context, organizationId string) (string, error) { //TODO implement me - ctx := context.Background() token := k.adminCliToken - realmUUID, err := k.client.CreateRealm(ctx, token.AccessToken, defaultRealmSetting(organizationId)) + realmUUID, err := k.client.CreateRealm(context.Background(), token.AccessToken, defaultRealmSetting(organizationId)) if err != nil { return "", err } @@ -177,7 +173,7 @@ func (k *Keycloak) CreateRealm(organizationId string) (string, error) { redirectURIs = append(redirectURIs, viper.GetString("external-address")+"/*") clientUUID, err := k.createDefaultClient(context.Background(), token.AccessToken, organizationId, DefaultClientID, k.config.ClientSecret, &redirectURIs) if err != nil { - log.Error(err, "createDefaultClient") + log.Error(ctx, err, "createDefaultClient") return "", err } @@ -192,7 +188,7 @@ func (k *Keycloak) CreateRealm(organizationId string) (string, error) { "userinfo.token.claim": "false", } } - if _, err := k.createClientProtocolMapper(ctx, token.AccessToken, organizationId, clientUUID, defaultMapper); err != nil { + if _, err := k.createClientProtocolMapper(context.Background(), token.AccessToken, organizationId, clientUUID, defaultMapper); err != nil { return "", err } } @@ -249,10 +245,9 @@ func (k *Keycloak) CreateRealm(organizationId string) (string, error) { return realmUUID, nil } -func (k *Keycloak) GetRealm(organizationId string) (*model.Organization, error) { - ctx := context.Background() +func (k *Keycloak) GetRealm(ctx context.Context, organizationId string) (*model.Organization, error) { token := k.adminCliToken - realm, err := k.client.GetRealm(ctx, token.AccessToken, organizationId) + realm, err := k.client.GetRealm(context.Background(), token.AccessToken, organizationId) if err != nil { return nil, err } @@ -260,10 +255,9 @@ func (k *Keycloak) GetRealm(organizationId string) (*model.Organization, error) return k.reflectOrganization(*realm), nil } -func (k *Keycloak) GetRealms() ([]*model.Organization, error) { - ctx := context.Background() +func (k *Keycloak) GetRealms(ctx context.Context) ([]*model.Organization, error) { token := k.adminCliToken - realms, err := k.client.GetRealms(ctx, token.AccessToken) + realms, err := k.client.GetRealms(context.Background(), token.AccessToken) if err != nil { return nil, err } @@ -275,21 +269,19 @@ func (k *Keycloak) GetRealms() ([]*model.Organization, error) { return organization, nil } -func (k *Keycloak) UpdateRealm(organizationId string, organizationConfig model.Organization) error { - ctx := context.Background() +func (k *Keycloak) UpdateRealm(ctx context.Context, organizationId string, organizationConfig model.Organization) error { token := k.adminCliToken realm := k.reflectRealmRepresentation(organizationConfig) - err := k.client.UpdateRealm(ctx, token.AccessToken, *realm) + err := k.client.UpdateRealm(context.Background(), token.AccessToken, *realm) if err != nil { return err } return nil } -func (k *Keycloak) DeleteRealm(organizationId string) error { - ctx := context.Background() +func (k *Keycloak) DeleteRealm(ctx context.Context, organizationId string) error { token := k.adminCliToken - err := k.client.DeleteRealm(ctx, token.AccessToken, organizationId) + err := k.client.DeleteRealm(context.Background(), token.AccessToken, organizationId) if err != nil { return err } @@ -297,11 +289,10 @@ func (k *Keycloak) DeleteRealm(organizationId string) error { return nil } -func (k *Keycloak) CreateUser(organizationId string, user *gocloak.User) (string, error) { - ctx := context.Background() +func (k *Keycloak) CreateUser(ctx context.Context, organizationId string, user *gocloak.User) (string, error) { token := k.adminCliToken user.Enabled = gocloak.BoolP(true) - uuid, err := k.client.CreateUser(ctx, token.AccessToken, organizationId, *user) + uuid, err := k.client.CreateUser(context.Background(), token.AccessToken, organizationId, *user) if err != nil { return "", err } @@ -309,12 +300,11 @@ func (k *Keycloak) CreateUser(organizationId string, user *gocloak.User) (string return uuid, nil } -func (k *Keycloak) GetUser(organizationId string, accountId string) (*gocloak.User, error) { - ctx := context.Background() +func (k *Keycloak) GetUser(ctx context.Context, organizationId string, accountId string) (*gocloak.User, error) { token := k.adminCliToken //TODO: this is rely on the fact that username is the same as userAccountId and unique - users, err := k.client.GetUsers(ctx, token.AccessToken, organizationId, gocloak.GetUsersParams{ + users, err := k.client.GetUsers(context.Background(), token.AccessToken, organizationId, gocloak.GetUsersParams{ Username: gocloak.StringP(accountId), }) if err != nil { @@ -328,11 +318,10 @@ func (k *Keycloak) GetUser(organizationId string, accountId string) (*gocloak.Us return users[0], nil } -func (k *Keycloak) GetUsers(organizationId string) ([]*gocloak.User, error) { - ctx := context.Background() +func (k *Keycloak) GetUsers(ctx context.Context, organizationId string) ([]*gocloak.User, error) { token := k.adminCliToken //TODO: this is rely on the fact that username is the same as userAccountId and unique - users, err := k.client.GetUsers(ctx, token.AccessToken, organizationId, gocloak.GetUsersParams{}) + users, err := k.client.GetUsers(context.Background(), token.AccessToken, organizationId, gocloak.GetUsersParams{}) if err != nil { return nil, err } @@ -344,11 +333,10 @@ func (k *Keycloak) GetUsers(organizationId string) ([]*gocloak.User, error) { return users, nil } -func (k *Keycloak) UpdateUser(organizationId string, user *gocloak.User) error { - ctx := context.Background() +func (k *Keycloak) UpdateUser(ctx context.Context, organizationId string, user *gocloak.User) error { token := k.adminCliToken user.Enabled = gocloak.BoolP(true) - err := k.client.UpdateUser(ctx, token.AccessToken, organizationId, *user) + err := k.client.UpdateUser(context.Background(), token.AccessToken, organizationId, *user) if err != nil { return err } @@ -356,24 +344,22 @@ func (k *Keycloak) UpdateUser(organizationId string, user *gocloak.User) error { return nil } -func (k *Keycloak) DeleteUser(organizationId string, userAccountId string) error { - ctx := context.Background() +func (k *Keycloak) DeleteUser(ctx context.Context, organizationId string, userAccountId string) error { token := k.adminCliToken - u, err := k.GetUser(organizationId, userAccountId) + u, err := k.GetUser(ctx, organizationId, userAccountId) if err != nil { - log.Errorf("error is :%s(%T)", err.Error(), err) + log.Errorf(ctx, "error is :%s(%T)", err.Error(), err) return httpErrors.NewNotFoundError(err, "", "") } - err = k.client.DeleteUser(ctx, token.AccessToken, organizationId, *u.ID) + err = k.client.DeleteUser(context.Background(), token.AccessToken, organizationId, *u.ID) if err != nil { return err } return nil } -func (k *Keycloak) VerifyAccessToken(token string, organizationId string) (bool, error) { - ctx := context.Background() - rptResult, err := k.client.RetrospectToken(ctx, token, DefaultClientID, k.config.ClientSecret, organizationId) +func (k *Keycloak) VerifyAccessToken(ctx context.Context, token string, organizationId string) (bool, error) { + rptResult, err := k.client.RetrospectToken(context.Background(), token, DefaultClientID, k.config.ClientSecret, organizationId) if err != nil { return false, err } @@ -384,12 +370,11 @@ func (k *Keycloak) VerifyAccessToken(token string, organizationId string) (bool, return true, nil } -func (k *Keycloak) GetSessions(userId string, organizationId string) (*[]string, error) { - ctx := context.Background() +func (k *Keycloak) GetSessions(ctx context.Context, userId string, organizationId string) (*[]string, error) { token := k.adminCliToken - sessions, err := k.client.GetUserSessions(ctx, token.AccessToken, organizationId, userId) + sessions, err := k.client.GetUserSessions(context.Background(), token.AccessToken, organizationId, userId) if err != nil { - log.Errorf("error is :%s(%T)", err.Error(), err) + log.Errorf(ctx, "error is :%s(%T)", err.Error(), err) return nil, err } @@ -401,10 +386,9 @@ func (k *Keycloak) GetSessions(userId string, organizationId string) (*[]string, return &sessionIds, nil } -func (k *Keycloak) Logout(sessionId string, organizationId string) error { - ctx := context.Background() +func (k *Keycloak) Logout(ctx context.Context, sessionId string, organizationId string) error { token := k.adminCliToken - err := k.client.LogoutUserSession(ctx, token.AccessToken, organizationId, sessionId) + err := k.client.LogoutUserSession(context.Background(), token.AccessToken, organizationId, sessionId) if err != nil { return err } @@ -412,57 +396,54 @@ func (k *Keycloak) Logout(sessionId string, organizationId string) error { return nil } -func (k *Keycloak) JoinGroup(organizationId string, userId string, groupName string) error { - ctx := context.Background() +func (k *Keycloak) JoinGroup(ctx context.Context, organizationId string, userId string, groupName string) error { token := k.adminCliToken - groups, err := k.client.GetGroups(ctx, token.AccessToken, organizationId, gocloak.GetGroupsParams{ + groups, err := k.client.GetGroups(context.Background(), token.AccessToken, organizationId, gocloak.GetGroupsParams{ Search: &groupName, }) if err != nil { - log.Error(err) + log.Error(ctx, err) return httpErrors.NewInternalServerError(err, "", "") } if len(groups) == 0 { return httpErrors.NewNotFoundError(fmt.Errorf("group not found"), "", "") } if err := k.client.AddUserToGroup(ctx, token.AccessToken, organizationId, userId, *groups[0].ID); err != nil { - log.Error(err) + log.Error(ctx, err) return httpErrors.NewInternalServerError(err, "", "") } return nil } -func (k *Keycloak) LeaveGroup(organizationId string, userId string, groupName string) error { - ctx := context.Background() +func (k *Keycloak) LeaveGroup(ctx context.Context, organizationId string, userId string, groupName string) error { token := k.adminCliToken - groups, err := k.client.GetGroups(ctx, token.AccessToken, organizationId, gocloak.GetGroupsParams{ + groups, err := k.client.GetGroups(context.Background(), token.AccessToken, organizationId, gocloak.GetGroupsParams{ Search: &groupName, }) if err != nil { - log.Error(err) + log.Error(ctx, err) return httpErrors.NewInternalServerError(err, "", "") } if len(groups) == 0 { return httpErrors.NewNotFoundError(fmt.Errorf("group not found"), "", "") } - if err := k.client.DeleteUserFromGroup(ctx, token.AccessToken, organizationId, userId, *groups[0].ID); err != nil { - log.Error(err) + if err := k.client.DeleteUserFromGroup(context.Background(), token.AccessToken, organizationId, userId, *groups[0].ID); err != nil { + log.Error(ctx, err) return httpErrors.NewInternalServerError(err, "", "") } return nil } -func (k *Keycloak) EnsureClientRoleWithClientName(organizationId string, clientName string, roleName string) error { - ctx := context.Background() +func (k *Keycloak) EnsureClientRoleWithClientName(ctx context.Context, organizationId string, clientName string, roleName string) error { token := k.adminCliToken - clients, err := k.client.GetClients(ctx, token.AccessToken, organizationId, gocloak.GetClientsParams{ + clients, err := k.client.GetClients(context.Background(), token.AccessToken, organizationId, gocloak.GetClientsParams{ ClientID: &clientName, }) if err != nil { - log.Error("Getting Client is failed", err) + log.Error(ctx, "Getting Client is failed", err) return err } @@ -472,126 +453,123 @@ func (k *Keycloak) EnsureClientRoleWithClientName(organizationId string, clientN Name: gocloak.StringP(roleName), } - _, err = k.client.CreateClientRole(ctx, token.AccessToken, organizationId, *targetClient.ID, role) + _, err = k.client.CreateClientRole(context.Background(), token.AccessToken, organizationId, *targetClient.ID, role) if err != nil { - log.Error("Creating Client Role is failed", err) + log.Error(ctx, "Creating Client Role is failed", err) return err } return nil } -func (k *Keycloak) DeleteClientRoleWithClientName(organizationId string, clientName string, roleName string) error { - ctx := context.Background() +func (k *Keycloak) DeleteClientRoleWithClientName(ctx context.Context, organizationId string, clientName string, roleName string) error { token := k.adminCliToken - clients, err := k.client.GetClients(ctx, token.AccessToken, organizationId, gocloak.GetClientsParams{ + clients, err := k.client.GetClients(context.Background(), token.AccessToken, organizationId, gocloak.GetClientsParams{ ClientID: &clientName, }) if err != nil { - log.Error("Getting Client is failed", err) + log.Error(ctx, "Getting Client is failed", err) return err } targetClient := clients[0] - roles, err := k.client.GetClientRoles(ctx, token.AccessToken, organizationId, *targetClient.ID, gocloak.GetRoleParams{ + roles, err := k.client.GetClientRoles(context.Background(), token.AccessToken, organizationId, *targetClient.ID, gocloak.GetRoleParams{ Search: &roleName, }) if err != nil { - log.Error("Getting Client Role is failed", err) + log.Error(ctx, "Getting Client Role is failed", err) return err } if len(roles) == 0 { - log.Warn("Client Role not found", roleName) + log.Warn(ctx, "Client Role not found", roleName) return nil } - err = k.client.DeleteClientRole(ctx, token.AccessToken, organizationId, *targetClient.ID, *roles[0].ID) + err = k.client.DeleteClientRole(context.Background(), token.AccessToken, organizationId, *targetClient.ID, *roles[0].ID) if err != nil { - log.Error("Deleting Client Role is failed", err) + log.Error(ctx, "Deleting Client Role is failed", err) return err } return nil } -func (k *Keycloak) AssignClientRoleToUser(organizationId string, userId string, clientName string, roleName string) error { - ctx := context.Background() +func (k *Keycloak) AssignClientRoleToUser(ctx context.Context, organizationId string, userId string, clientName string, roleName string) error { token := k.adminCliToken - clients, err := k.client.GetClients(ctx, token.AccessToken, organizationId, gocloak.GetClientsParams{ + clients, err := k.client.GetClients(context.Background(), token.AccessToken, organizationId, gocloak.GetClientsParams{ ClientID: &clientName, }) if err != nil { - log.Error("Getting Client is failed", err) + log.Error(ctx, "Getting Client is failed", err) return err } if len(clients) == 0 { - log.Warn("Client not found", clientName) + log.Warn(ctx, "Client not found", clientName) return nil } targetClient := clients[0] - roles, err := k.client.GetClientRoles(ctx, token.AccessToken, organizationId, *targetClient.ID, gocloak.GetRoleParams{ + roles, err := k.client.GetClientRoles(context.Background(), token.AccessToken, organizationId, *targetClient.ID, gocloak.GetRoleParams{ Search: &roleName, }) if err != nil { - log.Error("Getting Client Role is failed", err) + log.Error(ctx, "Getting Client Role is failed", err) return err } if len(roles) == 0 { - log.Warn("Client Role not found", roleName) + log.Warn(ctx, "Client Role not found", roleName) return nil } - err = k.client.AddClientRolesToUser(ctx, token.AccessToken, organizationId, userId, *targetClient.ID, []gocloak.Role{*roles[0]}) + err = k.client.AddClientRolesToUser(context.Background(), token.AccessToken, organizationId, userId, *targetClient.ID, []gocloak.Role{*roles[0]}) if err != nil { - log.Error("Assigning Client Role to User is failed", err) + log.Error(ctx, "Assigning Client Role to User is failed", err) return err } return nil } -func (k *Keycloak) UnassignClientRoleToUser(organizationId string, userId string, clientName string, roleName string) error { - ctx := context.Background() +func (k *Keycloak) UnassignClientRoleToUser(ctx context.Context, organizationId string, userId string, clientName string, roleName string) error { token := k.adminCliToken - clients, err := k.client.GetClients(ctx, token.AccessToken, organizationId, gocloak.GetClientsParams{ + clients, err := k.client.GetClients(context.Background(), token.AccessToken, organizationId, gocloak.GetClientsParams{ ClientID: &clientName, }) if err != nil { - log.Error("Getting Client is failed", err) + log.Error(ctx, "Getting Client is failed", err) return err } if len(clients) == 0 { - log.Warn("Client not found", clientName) + log.Warn(ctx, "Client not found", clientName) return nil } targetClient := clients[0] - roles, err := k.client.GetClientRoles(ctx, token.AccessToken, organizationId, *targetClient.ID, gocloak.GetRoleParams{ + roles, err := k.client.GetClientRoles(context.Background(), token.AccessToken, organizationId, *targetClient.ID, gocloak.GetRoleParams{ Search: &roleName, }) if err != nil { - log.Error("Getting Client Role is failed", err) + log.Error(ctx, "Getting Client Role is failed", err) return err } if len(roles) == 0 { - log.Warn("Client Role not found", roleName) + log.Warn(ctx, "Client Role not found", roleName) return nil } - err = k.client.DeleteClientRolesFromUser(ctx, token.AccessToken, organizationId, userId, *targetClient.ID, []gocloak.Role{*roles[0]}) + err = k.client.DeleteClientRolesFromUser(context.Background(), token.AccessToken, organizationId, userId, *targetClient.ID, []gocloak.Role{*roles[0]}) if err != nil { - log.Error("Unassigning Client Role to User is failed", err) + log.Error(ctx, "Unassigning Client Role to User is failed", err) return err } @@ -601,69 +579,69 @@ func (k *Keycloak) UnassignClientRoleToUser(organizationId string, userId string func (k *Keycloak) ensureClientProtocolMappers(ctx context.Context, token *gocloak.JWT, realm string, clientId string, scope string, mapper gocloak.ProtocolMapperRepresentation) error { //TODO: Check current logic(if exist, do nothing) is fine - clients, err := k.client.GetClients(ctx, token.AccessToken, realm, gocloak.GetClientsParams{ + clients, err := k.client.GetClients(context.Background(), token.AccessToken, realm, gocloak.GetClientsParams{ ClientID: &clientId, }) if err != nil { - log.Error("Getting Client is failed", err) + log.Error(ctx, "Getting Client is failed", err) return err } if clients[0].ProtocolMappers != nil { for _, protocolMapper := range *clients[0].ProtocolMappers { if *protocolMapper.Name == *mapper.Name { - log.Warn("Protocol Mapper already exists", *protocolMapper.Name) + log.Warn(ctx, "Protocol Mapper already exists", *protocolMapper.Name) return nil } } } - if _, err := k.client.CreateClientProtocolMapper(ctx, token.AccessToken, realm, *clients[0].ID, mapper); err != nil { - log.Error("Creating Client Protocol Mapper is failed", err) + if _, err := k.client.CreateClientProtocolMapper(context.Background(), token.AccessToken, realm, *clients[0].ID, mapper); err != nil { + log.Error(ctx, "Creating Client Protocol Mapper is failed", err) return err } return nil } func (k *Keycloak) ensureClient(ctx context.Context, token *gocloak.JWT, realm string, clientId string, secret string, redirectURIs *[]string) (*gocloak.Client, error) { - keycloakClient, err := k.client.GetClients(ctx, token.AccessToken, realm, gocloak.GetClientsParams{ + keycloakClient, err := k.client.GetClients(context.Background(), token.AccessToken, realm, gocloak.GetClientsParams{ ClientID: &clientId, }) if err != nil { - log.Error("Getting Client is failed", err) + log.Error(ctx, "Getting Client is failed", err) } if len(keycloakClient) == 0 { - _, err = k.client.CreateClient(ctx, token.AccessToken, realm, gocloak.Client{ + _, err = k.client.CreateClient(context.Background(), token.AccessToken, realm, gocloak.Client{ ClientID: gocloak.StringP(clientId), Enabled: gocloak.BoolP(true), DirectAccessGrantsEnabled: gocloak.BoolP(true), RedirectURIs: redirectURIs, }) if err != nil { - log.Error("Creating Client is failed", err) + log.Error(ctx, "Creating Client is failed", err) } - keycloakClient, err = k.client.GetClients(ctx, token.AccessToken, realm, gocloak.GetClientsParams{ + keycloakClient, err = k.client.GetClients(context.Background(), token.AccessToken, realm, gocloak.GetClientsParams{ ClientID: &clientId, }) if err != nil { - log.Error("Getting Client is failed", err) + log.Error(ctx, "Getting Client is failed", err) } } else { - err = k.client.UpdateClient(ctx, token.AccessToken, realm, gocloak.Client{ + err = k.client.UpdateClient(context.Background(), token.AccessToken, realm, gocloak.Client{ ID: keycloakClient[0].ID, Enabled: gocloak.BoolP(true), DirectAccessGrantsEnabled: gocloak.BoolP(true), RedirectURIs: redirectURIs, }) if err != nil { - log.Error("Update Client is failed", err) + log.Error(ctx, "Update Client is failed", err) } } if keycloakClient[0].Secret == nil || *keycloakClient[0].Secret != secret { - log.Warn("Client secret is not matched. Overwrite it") + log.Warn(ctx, "Client secret is not matched. Overwrite it") keycloakClient[0].Secret = gocloak.StringP(secret) - if err := k.client.UpdateClient(ctx, token.AccessToken, realm, *keycloakClient[0]); err != nil { - log.Error("Updating Client is failed", err) + if err := k.client.UpdateClient(context.Background(), token.AccessToken, realm, *keycloakClient[0]); err != nil { + log.Error(ctx, "Updating Client is failed", err) } } @@ -671,9 +649,9 @@ func (k *Keycloak) ensureClient(ctx context.Context, token *gocloak.JWT, realm s } func (k *Keycloak) addUserToGroup(ctx context.Context, token *gocloak.JWT, realm string, userID string, groupID string) error { - groups, err := k.client.GetUserGroups(ctx, token.AccessToken, realm, userID, gocloak.GetGroupsParams{}) + groups, err := k.client.GetUserGroups(context.Background(), token.AccessToken, realm, userID, gocloak.GetGroupsParams{}) if err != nil { - log.Error("Getting User Groups is failed") + log.Error(ctx, "Getting User Groups is failed") } for _, group := range groups { if *group.ID == groupID { @@ -681,15 +659,15 @@ func (k *Keycloak) addUserToGroup(ctx context.Context, token *gocloak.JWT, realm } } - err = k.client.AddUserToGroup(ctx, token.AccessToken, realm, userID, groupID) + err = k.client.AddUserToGroup(context.Background(), token.AccessToken, realm, userID, groupID) if err != nil { - log.Error("Assigning User to Group is failed", err) + log.Error(ctx, "Assigning User to Group is failed", err) } return err } func (k *Keycloak) ensureUserByName(ctx context.Context, token *gocloak.JWT, realm string, userName string, password string) (*gocloak.User, error) { - user, err := k.ensureUser(ctx, token, realm, userName, password) + user, err := k.ensureUser(context.Background(), token, realm, userName, password) return user, err } @@ -697,9 +675,9 @@ func (k *Keycloak) ensureUser(ctx context.Context, token *gocloak.JWT, realm str searchParam := gocloak.GetUsersParams{ Search: gocloak.StringP(userName), } - users, err := k.client.GetUsers(ctx, token.AccessToken, realm, searchParam) + users, err := k.client.GetUsers(context.Background(), token.AccessToken, realm, searchParam) if err != nil { - log.Error("Getting User is failed", err) + log.Error(ctx, "Getting User is failed", err) } if len(users) == 0 { user := gocloak.User{ @@ -713,14 +691,14 @@ func (k *Keycloak) ensureUser(ctx context.Context, token *gocloak.JWT, realm str }, }, } - _, err = k.client.CreateUser(ctx, token.AccessToken, realm, user) + _, err = k.client.CreateUser(context.Background(), token.AccessToken, realm, user) if err != nil { - log.Error("Creating User is failed", err) + log.Error(ctx, "Creating User is failed", err) } - users, err = k.client.GetUsers(ctx, token.AccessToken, realm, searchParam) + users, err = k.client.GetUsers(context.Background(), token.AccessToken, realm, searchParam) if err != nil { - log.Error("Getting User is failed", err) + log.Error(ctx, "Getting User is failed", err) } } @@ -728,7 +706,7 @@ func (k *Keycloak) ensureUser(ctx context.Context, token *gocloak.JWT, realm str } func (k *Keycloak) ensureGroupByName(ctx context.Context, token *gocloak.JWT, realm string, groupName string, groupParam ...gocloak.Group) (*gocloak.Group, error) { - group, err := k.ensureGroup(ctx, token, realm, groupName) + group, err := k.ensureGroup(context.Background(), token, realm, groupName) return group, err } @@ -740,27 +718,27 @@ func (k *Keycloak) ensureGroup(ctx context.Context, token *gocloak.JWT, realm st Name: gocloak.StringP(groupName), } - groups, err := k.client.GetGroups(ctx, token.AccessToken, realm, searchParam) + groups, err := k.client.GetGroups(context.Background(), token.AccessToken, realm, searchParam) if err != nil { - log.Error("Getting Group is failed", err) + log.Error(ctx, "Getting Group is failed", err) } if len(groups) == 0 { - _, err = k.client.CreateGroup(ctx, token.AccessToken, realm, groupParam) + _, err = k.client.CreateGroup(context.Background(), token.AccessToken, realm, groupParam) if err != nil { - log.Error("Creating Group is failed", err) + log.Error(ctx, "Creating Group is failed", err) } - groups, err = k.client.GetGroups(ctx, token.AccessToken, realm, searchParam) + groups, err = k.client.GetGroups(context.Background(), token.AccessToken, realm, searchParam) if err != nil { - log.Error("Getting Group is failed", err) + log.Error(ctx, "Getting Group is failed", err) } } return groups[0], err } func (k *Keycloak) createGroup(ctx context.Context, accessToken string, realm string, groupName string) (string, error) { - id, err := k.client.CreateGroup(ctx, accessToken, realm, gocloak.Group{Name: gocloak.StringP(groupName)}) + id, err := k.client.CreateGroup(context.Background(), accessToken, realm, gocloak.Group{Name: gocloak.StringP(groupName)}) if err != nil { - log.Error("Creating Group is failed", err) + log.Error(ctx, "Creating Group is failed", err) return "", err } return id, nil @@ -768,9 +746,9 @@ func (k *Keycloak) createGroup(ctx context.Context, accessToken string, realm st func (k *Keycloak) getClientByClientId(ctx context.Context, accessToken string, realm string, clientId string) ( string, error) { - clients, err := k.client.GetClients(ctx, accessToken, realm, gocloak.GetClientsParams{ClientID: &clientId}) + clients, err := k.client.GetClients(context.Background(), accessToken, realm, gocloak.GetClientsParams{ClientID: &clientId}) if err != nil { - log.Error("Getting Client is failed", err) + log.Error(ctx, "Getting Client is failed", err) return "", err } return *clients[0].ID, nil @@ -778,9 +756,9 @@ func (k *Keycloak) getClientByClientId(ctx context.Context, accessToken string, func (k *Keycloak) createClientRole(ctx context.Context, accessToken string, realm string, clientUuid string, roleName string) (string, error) { - id, err := k.client.CreateClientRole(ctx, accessToken, realm, clientUuid, gocloak.Role{Name: gocloak.StringP(roleName)}) + id, err := k.client.CreateClientRole(context.Background(), accessToken, realm, clientUuid, gocloak.Role{Name: gocloak.StringP(roleName)}) if err != nil { - log.Error("Creating Client Role is failed", err) + log.Error(ctx, "Creating Client Role is failed", err) return "", err } return id, nil @@ -788,9 +766,9 @@ func (k *Keycloak) createClientRole(ctx context.Context, accessToken string, rea func (k *Keycloak) getClientRole(ctx context.Context, accessToken string, realm string, clientUuid string, roleName string) (*gocloak.Role, error) { - role, err := k.client.GetClientRole(ctx, accessToken, realm, clientUuid, roleName) + role, err := k.client.GetClientRole(context.Background(), accessToken, realm, clientUuid, roleName) if err != nil { - log.Error("Getting Client Role is failed", err) + log.Error(ctx, "Getting Client Role is failed", err) return nil, err } return role, nil @@ -798,9 +776,9 @@ func (k *Keycloak) getClientRole(ctx context.Context, accessToken string, realm func (k *Keycloak) addClientRoleToGroup(ctx context.Context, accessToken string, realm string, clientUuid string, groupUuid string, role *gocloak.Role) error { - err := k.client.AddClientRolesToGroup(ctx, accessToken, realm, clientUuid, groupUuid, []gocloak.Role{*role}) + err := k.client.AddClientRolesToGroup(context.Background(), accessToken, realm, clientUuid, groupUuid, []gocloak.Role{*role}) if err != nil { - log.Error("Adding Client Role to Group is failed", err) + log.Error(ctx, "Adding Client Role to Group is failed", err) return err } return nil @@ -808,9 +786,9 @@ func (k *Keycloak) addClientRoleToGroup(ctx context.Context, accessToken string, func (k *Keycloak) createClientProtocolMapper(ctx context.Context, accessToken string, realm string, id string, mapper gocloak.ProtocolMapperRepresentation) (string, error) { - id, err := k.client.CreateClientProtocolMapper(ctx, accessToken, realm, id, mapper) + id, err := k.client.CreateClientProtocolMapper(context.Background(), accessToken, realm, id, mapper) if err != nil { - log.Error("Creating Client Protocol Mapper is failed", err) + log.Error(ctx, "Creating Client Protocol Mapper is failed", err) return "", err } @@ -819,7 +797,7 @@ func (k *Keycloak) createClientProtocolMapper(ctx context.Context, accessToken s func (k *Keycloak) createDefaultClient(ctx context.Context, accessToken string, realm string, clientId string, clientSecret string, redirectURIs *[]string) (string, error) { - id, err := k.client.CreateClient(ctx, accessToken, realm, gocloak.Client{ + id, err := k.client.CreateClient(context.Background(), accessToken, realm, gocloak.Client{ ClientID: gocloak.StringP(clientId), DirectAccessGrantsEnabled: gocloak.BoolP(true), Enabled: gocloak.BoolP(true), @@ -827,16 +805,16 @@ func (k *Keycloak) createDefaultClient(ctx context.Context, accessToken string, }) if err != nil { - log.Error("Creating Client is failed", err) + log.Error(ctx, "Creating Client is failed", err) return "", err } - client, err := k.client.GetClient(ctx, accessToken, realm, id) + client, err := k.client.GetClient(context.Background(), accessToken, realm, id) if err != nil { - log.Error("Getting Client is failed", err) + log.Error(ctx, "Getting Client is failed", err) return "", err } client.Secret = gocloak.StringP(clientSecret) - err = k.client.UpdateClient(ctx, accessToken, realm, *client) + err = k.client.UpdateClient(context.Background(), accessToken, realm, *client) if err != nil { return "", err } diff --git a/internal/kubernetes/kubernetes.go b/internal/kubernetes/kubernetes.go index 2af15b06..d709134b 100644 --- a/internal/kubernetes/kubernetes.go +++ b/internal/kubernetes/kubernetes.go @@ -22,30 +22,30 @@ import ( "github.com/openinfradev/tks-api/pkg/log" ) -func getAdminConfig() (*rest.Config, error) { +func getAdminConfig(ctx context.Context) (*rest.Config, error) { kubeconfigPath := viper.GetString("kubeconfig-path") if kubeconfigPath == "" { - log.Info("Use in-cluster config") + log.Info(ctx, "Use in-cluster config") config, err := rest.InClusterConfig() if err != nil { - log.Error("Failed to load incluster kubeconfig") + log.Error(ctx, "Failed to load incluster kubeconfig") return nil, err } return config, nil } else { config, err := clientcmd.BuildConfigFromFlags("", viper.GetString("kubeconfig-path")) if err != nil { - log.Error("Failed to local kubeconfig") + log.Error(ctx, "Failed to local kubeconfig") return nil, err } return config, nil } } -func GetClientAdminCluster() (*kubernetes.Clientset, error) { - config, err := getAdminConfig() +func GetClientAdminCluster(ctx context.Context) (*kubernetes.Clientset, error) { + config, err := getAdminConfig(ctx) if err != nil { - log.Error("Failed to load kubeconfig") + log.Error(ctx, "Failed to load kubeconfig") return nil, err } @@ -57,15 +57,15 @@ func GetClientAdminCluster() (*kubernetes.Clientset, error) { return clientset, nil } -func GetAwsSecret() (awsAccessKeyId string, awsSecretAccessKey string, err error) { - clientset, err := GetClientAdminCluster() +func GetAwsSecret(ctx context.Context) (awsAccessKeyId string, awsSecretAccessKey string, err error) { + clientset, err := GetClientAdminCluster(ctx) if err != nil { return "", "", err } secrets, err := clientset.CoreV1().Secrets("argo").Get(context.TODO(), "awsconfig-secret", metav1.GetOptions{}) if err != nil { - log.Error(err) + log.Error(ctx, err) return "", "", err } @@ -81,15 +81,15 @@ func GetAwsSecret() (awsAccessKeyId string, awsSecretAccessKey string, err error return } -func GetAwsAccountIdSecret() (awsAccountId string, err error) { - clientset, err := GetClientAdminCluster() +func GetAwsAccountIdSecret(ctx context.Context) (awsAccountId string, err error) { + clientset, err := GetClientAdminCluster(ctx) if err != nil { return "", err } secrets, err := clientset.CoreV1().Secrets("argo").Get(context.TODO(), "tks-aws-user", metav1.GetOptions{}) if err != nil { - log.Error(err) + log.Error(ctx, err) return "", err } @@ -97,36 +97,36 @@ func GetAwsAccountIdSecret() (awsAccountId string, err error) { return } -func GetKubeConfig(clusterId string) ([]byte, error) { - clientset, err := GetClientAdminCluster() +func GetKubeConfig(ctx context.Context, clusterId string) ([]byte, error) { + clientset, err := GetClientAdminCluster(ctx) if err != nil { return nil, err } secrets, err := clientset.CoreV1().Secrets(clusterId).Get(context.TODO(), clusterId+"-tks-user-kubeconfig", metav1.GetOptions{}) if err != nil { - log.Error(err) + log.Error(ctx, err) return nil, err } return secrets.Data["value"], nil } -func GetClientFromClusterId(clusterId string) (*kubernetes.Clientset, error) { - clientset, err := GetClientAdminCluster() +func GetClientFromClusterId(ctx context.Context, clusterId string) (*kubernetes.Clientset, error) { + clientset, err := GetClientAdminCluster(ctx) if err != nil { return nil, err } secrets, err := clientset.CoreV1().Secrets(clusterId).Get(context.TODO(), clusterId+"-tks-kubeconfig", metav1.GetOptions{}) if err != nil { - log.Error(err) + log.Error(ctx, err) return nil, err } config_user, err := clientcmd.RESTConfigFromKubeConfig(secrets.Data["value"]) if err != nil { - log.Error(err) + log.Error(ctx, err) return nil, err } clientset_user, err := kubernetes.NewForConfig(config_user) @@ -137,64 +137,64 @@ func GetClientFromClusterId(clusterId string) (*kubernetes.Clientset, error) { return clientset_user, nil } -func GetKubernetesVserionByClusterId(clusterId string) (string, error) { - clientset, err := GetClientAdminCluster() +func GetKubernetesVserionByClusterId(ctx context.Context, clusterId string) (string, error) { + clientset, err := GetClientAdminCluster(ctx) if err != nil { return "", err } secrets, err := clientset.CoreV1().Secrets(clusterId).Get(context.TODO(), clusterId+"-tks-kubeconfig", metav1.GetOptions{}) if err != nil { - log.Error(err) + log.Error(ctx, err) return "", err } config_user, err := clientcmd.RESTConfigFromKubeConfig(secrets.Data["value"]) if err != nil { - log.Error(err) + log.Error(ctx, err) return "", err } discoveryClient, err := discovery.NewDiscoveryClientForConfig(config_user) if err != nil { - log.Error(err) + log.Error(ctx, err) return "", err } information, err := discoveryClient.ServerVersion() if err != nil { - log.Error("Error while fetching server version information", err) + log.Error(ctx, "Error while fetching server version information", err) return "", err } return information.GitVersion, nil } -func GetKubernetesVserion() (string, error) { - config, err := getAdminConfig() +func GetKubernetesVserion(ctx context.Context) (string, error) { + config, err := getAdminConfig(ctx) if err != nil { - log.Error("Failed to load kubeconfig") + log.Error(ctx, "Failed to load kubeconfig") return "", err } discoveryClient, err := discovery.NewDiscoveryClientForConfig(config) if err != nil { - log.Error(err) + log.Error(ctx, err) return "", err } information, err := discoveryClient.ServerVersion() if err != nil { - log.Error("Error while fetching server version information", err) + log.Error(ctx, "Error while fetching server version information", err) return "", err } return information.GitVersion, nil } -func GetResourceApiVersion(kubeconfig []byte, kind string) (string, error) { +func GetResourceApiVersion(ctx context.Context, kubeconfig []byte, kind string) (string, error) { config_user, err := clientcmd.RESTConfigFromKubeConfig(kubeconfig) if err != nil { - log.Error(err) + log.Error(ctx, err) return "", err } @@ -202,7 +202,7 @@ func GetResourceApiVersion(kubeconfig []byte, kind string) (string, error) { apiResourceList, err := clientset.Discovery().ServerPreferredResources() if err != nil { - log.Error(err) + log.Error(ctx, err) return "", err } @@ -217,10 +217,10 @@ func GetResourceApiVersion(kubeconfig []byte, kind string) (string, error) { return "", nil } -func EnsureClusterRole(kubeconfig []byte, projectName string) error { +func EnsureClusterRole(ctx context.Context, kubeconfig []byte, projectName string) error { config_user, err := clientcmd.RESTConfigFromKubeConfig(kubeconfig) if err != nil { - log.Error(err) + log.Error(ctx, err) return err } @@ -233,13 +233,13 @@ func EnsureClusterRole(kubeconfig []byte, projectName string) error { if _, err := clientset.RbacV1().ClusterRoles().Get(context.Background(), projectName+"-"+role, metav1.GetOptions{}); err != nil { _, err = clientset.RbacV1().ClusterRoles().Create(context.Background(), obj, metav1.CreateOptions{}) if err != nil { - log.Error(err) + log.Error(ctx, err) return err } } else { _, err = clientset.RbacV1().ClusterRoles().Update(context.Background(), obj, metav1.UpdateOptions{}) if err != nil { - log.Error(err) + log.Error(ctx, err) return err } } @@ -248,10 +248,10 @@ func EnsureClusterRole(kubeconfig []byte, projectName string) error { return nil } -func RemoveClusterRole(kubeconfig []byte, projectName string) error { +func RemoveClusterRole(ctx context.Context, kubeconfig []byte, projectName string) error { config_user, err := clientcmd.RESTConfigFromKubeConfig(kubeconfig) if err != nil { - log.Error(err) + log.Error(ctx, err) return err } @@ -260,17 +260,17 @@ func RemoveClusterRole(kubeconfig []byte, projectName string) error { // remove clusterrole object for _, role := range []string{leaderRole, memberRole, viewerRole} { if err := clientset.RbacV1().ClusterRoles().Delete(context.Background(), projectName+"-"+role, metav1.DeleteOptions{}); err != nil { - log.Error(err) + log.Error(ctx, err) } } return nil } -func EnsureClusterRoleBinding(kubeconfig []byte, projectName string) error { +func EnsureClusterRoleBinding(ctx context.Context, kubeconfig []byte, projectName string) error { config_user, err := clientcmd.RESTConfigFromKubeConfig(kubeconfig) if err != nil { - log.Error(err) + log.Error(ctx, err) return err } @@ -281,13 +281,13 @@ func EnsureClusterRoleBinding(kubeconfig []byte, projectName string) error { if _, err = clientset.RbacV1().ClusterRoleBindings().Get(context.Background(), projectName+"-"+role, metav1.GetOptions{}); err != nil { _, err = clientset.RbacV1().ClusterRoleBindings().Create(context.Background(), obj, metav1.CreateOptions{}) if err != nil { - log.Error(err) + log.Error(ctx, err) return err } } else { _, err = clientset.RbacV1().ClusterRoleBindings().Update(context.Background(), obj, metav1.UpdateOptions{}) if err != nil { - log.Error(err) + log.Error(ctx, err) return err } } @@ -296,10 +296,10 @@ func EnsureClusterRoleBinding(kubeconfig []byte, projectName string) error { return nil } -func RemoveClusterRoleBinding(kubeconfig []byte, projectName string) error { +func RemoveClusterRoleBinding(ctx context.Context, kubeconfig []byte, projectName string) error { config_user, err := clientcmd.RESTConfigFromKubeConfig(kubeconfig) if err != nil { - log.Error(err) + log.Error(ctx, err) return err } @@ -307,17 +307,17 @@ func RemoveClusterRoleBinding(kubeconfig []byte, projectName string) error { for _, role := range []string{leaderRole, memberRole, viewerRole} { if err := clientset.RbacV1().ClusterRoleBindings().Delete(context.Background(), projectName+"-"+role, metav1.DeleteOptions{}); err != nil { - log.Error(err) + log.Error(ctx, err) } } return nil } -func EnsureRoleBinding(kubeconfig []byte, projectName string, namespace string) error { +func EnsureRoleBinding(ctx context.Context, kubeconfig []byte, projectName string, namespace string) error { config_user, err := clientcmd.RESTConfigFromKubeConfig(kubeconfig) if err != nil { - log.Error(err) + log.Error(ctx, err) return err } @@ -328,13 +328,13 @@ func EnsureRoleBinding(kubeconfig []byte, projectName string, namespace string) if _, err = clientset.RbacV1().RoleBindings(namespace).Get(context.Background(), projectName+"-"+role, metav1.GetOptions{}); err != nil { _, err = clientset.RbacV1().RoleBindings(namespace).Create(context.Background(), obj, metav1.CreateOptions{}) if err != nil { - log.Error(err) + log.Error(ctx, err) return err } } else { _, err = clientset.RbacV1().RoleBindings(namespace).Update(context.Background(), obj, metav1.UpdateOptions{}) if err != nil { - log.Error(err) + log.Error(ctx, err) return err } } @@ -343,10 +343,10 @@ func EnsureRoleBinding(kubeconfig []byte, projectName string, namespace string) return nil } -func RemoveRoleBinding(kubeconfig []byte, projectName string, namespace string) error { +func RemoveRoleBinding(ctx context.Context, kubeconfig []byte, projectName string, namespace string) error { config_user, err := clientcmd.RESTConfigFromKubeConfig(kubeconfig) if err != nil { - log.Error(err) + log.Error(ctx, err) return err } @@ -354,7 +354,7 @@ func RemoveRoleBinding(kubeconfig []byte, projectName string, namespace string) for _, role := range []string{leaderRole, memberRole, viewerRole} { if err := clientset.RbacV1().RoleBindings(namespace).Delete(context.Background(), projectName+"-"+role, metav1.DeleteOptions{}); err != nil { - log.Error(err) + log.Error(ctx, err) } } @@ -396,10 +396,10 @@ func getClusterRole(role, objName string) *rbacV1.ClusterRole { return &clusterRole } -func EnsureCommonClusterRole(kubeconfig []byte, projectName string) error { +func EnsureCommonClusterRole(ctx context.Context, kubeconfig []byte, projectName string) error { config_user, err := clientcmd.RESTConfigFromKubeConfig(kubeconfig) if err != nil { - log.Error(err) + log.Error(ctx, err) return err } @@ -409,13 +409,13 @@ func EnsureCommonClusterRole(kubeconfig []byte, projectName string) error { if _, err = clientset.RbacV1().ClusterRoles().Get(context.Background(), projectName+"-common", metav1.GetOptions{}); err != nil { _, err = clientset.RbacV1().ClusterRoles().Create(context.Background(), obj, metav1.CreateOptions{}) if err != nil { - log.Error(err) + log.Error(ctx, err) return err } } else { _, err = clientset.RbacV1().ClusterRoles().Update(context.Background(), obj, metav1.UpdateOptions{}) if err != nil { - log.Error(err) + log.Error(ctx, err) return err } } @@ -423,27 +423,27 @@ func EnsureCommonClusterRole(kubeconfig []byte, projectName string) error { return nil } -func RemoveCommonClusterRole(kubeconfig []byte, projectName string) error { +func RemoveCommonClusterRole(ctx context.Context, kubeconfig []byte, projectName string) error { config_user, err := clientcmd.RESTConfigFromKubeConfig(kubeconfig) if err != nil { - log.Error(err) + log.Error(ctx, err) return err } clientset := kubernetes.NewForConfigOrDie(config_user) if err := clientset.RbacV1().ClusterRoles().Delete(context.Background(), projectName+"-common", metav1.DeleteOptions{}); err != nil { - log.Error(err) + log.Error(ctx, err) return err } return nil } -func EnsureCommonClusterRoleBinding(kubeconfig []byte, projectName string) error { +func EnsureCommonClusterRoleBinding(ctx context.Context, kubeconfig []byte, projectName string) error { config_user, err := clientcmd.RESTConfigFromKubeConfig(kubeconfig) if err != nil { - log.Error(err) + log.Error(ctx, err) return err } @@ -454,13 +454,13 @@ func EnsureCommonClusterRoleBinding(kubeconfig []byte, projectName string) error if _, err = clientset.RbacV1().ClusterRoleBindings().Get(context.Background(), projectName+"-common"+"-"+role, metav1.GetOptions{}); err != nil { _, err = clientset.RbacV1().ClusterRoleBindings().Create(context.Background(), obj, metav1.CreateOptions{}) if err != nil { - log.Error(err) + log.Error(ctx, err) return err } } else { _, err = clientset.RbacV1().ClusterRoleBindings().Update(context.Background(), obj, metav1.UpdateOptions{}) if err != nil { - log.Error(err) + log.Error(ctx, err) return err } } @@ -469,10 +469,10 @@ func EnsureCommonClusterRoleBinding(kubeconfig []byte, projectName string) error return nil } -func RemoveCommonClusterRoleBinding(kubeconfig []byte, projectName string) error { +func RemoveCommonClusterRoleBinding(ctx context.Context, kubeconfig []byte, projectName string) error { config_user, err := clientcmd.RESTConfigFromKubeConfig(kubeconfig) if err != nil { - log.Error(err) + log.Error(ctx, err) return err } @@ -480,7 +480,7 @@ func RemoveCommonClusterRoleBinding(kubeconfig []byte, projectName string) error for _, role := range []string{leaderRole, memberRole, viewerRole} { if err := clientset.RbacV1().ClusterRoles().Delete(context.Background(), projectName+"-common-"+role, metav1.DeleteOptions{}); err != nil { - log.Error(err) + log.Error(ctx, err) return err } } diff --git a/internal/mail/content.go b/internal/mail/content.go index d8ac55c9..77a4950d 100644 --- a/internal/mail/content.go +++ b/internal/mail/content.go @@ -2,17 +2,18 @@ package mail import ( "bytes" + "context" "html/template" "github.com/openinfradev/tks-api/pkg/log" ) -func MakeVerityIdentityMessage(to, code string) (*MessageInfo, error) { +func MakeVerityIdentityMessage(ctx context.Context, to, code string) (*MessageInfo, error) { subject := "[TKS] [인증번호:" + code + "] 인증번호가 발급되었습니다." tmpl, err := template.ParseFS(templateFS, "contents/authcode.html") if err != nil { - log.Errorf("failed to parse template, %v", err) + log.Errorf(ctx, "failed to parse template, %v", err) return nil, err } @@ -20,7 +21,7 @@ func MakeVerityIdentityMessage(to, code string) (*MessageInfo, error) { var tpl bytes.Buffer if err := tmpl.Execute(&tpl, data); err != nil { - log.Errorf("failed to execute template, %v", err) + log.Errorf(ctx, "failed to execute template, %v", err) return nil, err } @@ -34,12 +35,12 @@ func MakeVerityIdentityMessage(to, code string) (*MessageInfo, error) { return m, nil } -func MakeTemporaryPasswordMessage(to, organizationId, accountId, randomPassword string) (*MessageInfo, error) { +func MakeTemporaryPasswordMessage(ctx context.Context, to, organizationId, accountId, randomPassword string) (*MessageInfo, error) { subject := "[TKS] 임시 비밀번호가 발급되었습니다." tmpl, err := template.ParseFS(templateFS, "contents/temporary_password.html") if err != nil { - log.Errorf("failed to parse template, %v", err) + log.Errorf(ctx, "failed to parse template, %v", err) return nil, err } @@ -47,7 +48,7 @@ func MakeTemporaryPasswordMessage(to, organizationId, accountId, randomPassword var tpl bytes.Buffer if err := tmpl.Execute(&tpl, data); err != nil { - log.Errorf("failed to execute template, %v", err) + log.Errorf(ctx, "failed to execute template, %v", err) return nil, err } @@ -62,13 +63,14 @@ func MakeTemporaryPasswordMessage(to, organizationId, accountId, randomPassword } func MakeGeneratingOrganizationMessage( + ctx context.Context, organizationId string, organizationName string, to string, userAccountId string, randomPassword string) (*MessageInfo, error) { subject := "[TKS] 조직이 생성되었습니다." tmpl, err := template.ParseFS(templateFS, "contents/organization_creation.html") if err != nil { - log.Errorf("failed to parse template, %v", err) + log.Errorf(ctx, "failed to parse template, %v", err) return nil, err } @@ -82,7 +84,7 @@ func MakeGeneratingOrganizationMessage( var tpl bytes.Buffer if err := tmpl.Execute(&tpl, data); err != nil { - log.Errorf("failed to execute template, %v", err) + log.Errorf(ctx, "failed to execute template, %v", err) return nil, err } diff --git a/internal/mail/ses.go b/internal/mail/ses.go index 98e9a429..eb7a4f0a 100644 --- a/internal/mail/ses.go +++ b/internal/mail/ses.go @@ -20,7 +20,7 @@ type AwsMailer struct { message *MessageInfo } -func (a *AwsMailer) SendMail() error { +func (a *AwsMailer) SendMail(ctx context.Context) error { input := &awsSes.SendEmailInput{ Destination: &types.Destination{ ToAddresses: []string{a.message.To}, @@ -39,16 +39,16 @@ func (a *AwsMailer) SendMail() error { } if _, err := a.client.SendEmail(context.Background(), input); err != nil { - log.Errorf("failed to send email, %v", err) + log.Errorf(ctx, "failed to send email, %v", err) return err } return nil } -func initialize() error { +func initialize(ctx context.Context) error { if viper.GetString("aws-access-key-id") != "" || viper.GetString("aws-secret-access-key") != "" { - log.Warn("aws access key information is used on env. Be aware of security") + log.Warn(ctx, "aws access key information is used on env. Be aware of security") } if viper.GetString("aws-access-key-id") != "" { err := os.Setenv("AWS_ACCESS_KEY_ID", viper.GetString("aws-access-key-id")) diff --git a/internal/mail/smtp.go b/internal/mail/smtp.go index 12a401ec..23714e50 100644 --- a/internal/mail/smtp.go +++ b/internal/mail/smtp.go @@ -2,6 +2,7 @@ package mail import ( "bytes" + "context" "crypto/tls" "embed" "errors" @@ -27,7 +28,7 @@ var ( ) type Mailer interface { - SendMail() error + SendMail(ctx context.Context) error } type MessageInfo struct { @@ -47,7 +48,7 @@ type SmtpMailer struct { message *MessageInfo } -func (s *SmtpMailer) SendMail() error { +func (s *SmtpMailer) SendMail(ctx context.Context) error { s.client.SetHeader("From", s.message.From) s.client.SetHeader("To", s.message.To) s.client.SetHeader("Subject", s.message.Subject) @@ -55,14 +56,14 @@ func (s *SmtpMailer) SendMail() error { d := NewDialer(s.Host, s.Port, s.Username, s.Password) if err := d.DialAndSend(s.client); err != nil { - log.Errorf("failed to send email, %v", err) + log.Errorf(ctx, "failed to send email, %v", err) return err } return nil } -func Initialize() error { +func Initialize(ctx context.Context) error { mailProvider = viper.GetString("mail-provider") if mailProvider != "smtp" { mailProvider = "aws" @@ -70,8 +71,8 @@ func Initialize() error { switch mailProvider { case "aws": - if err := initialize(); err != nil { - log.Errorf("aws config initialize error, %v", err) + if err := initialize(ctx); err != nil { + log.Errorf(ctx, "aws config initialize error, %v", err) return err } from = "tks-dev@sktelecom.com" @@ -83,23 +84,23 @@ func Initialize() error { from = viper.GetString("smtp-from-email") if host == "" { - log.Error("smtp-host is not set") + log.Error(ctx, "smtp-host is not set") return fmt.Errorf("smtp-host is not set") } if port == 0 { - log.Error("smtp-port is not set") + log.Error(ctx, "smtp-port is not set") return fmt.Errorf("smtp-port is not set") } if username == "" { - log.Error("smtp-username is not set") + log.Error(ctx, "smtp-username is not set") return fmt.Errorf("smtp-username is not set") } if password == "" { - log.Error("smtp-password is not set") + log.Error(ctx, "smtp-password is not set") return fmt.Errorf("smtp-password is not set") } if from == "" { - log.Error("smtp-from-email is not set") + log.Error(ctx, "smtp-from-email is not set") return fmt.Errorf("smtp-from-email is not set") } @@ -115,11 +116,11 @@ func New(m *MessageInfo) Mailer { switch mailProvider { case "aws": mailer = NewAwsMailer(m) - log.Infof("aws ses mailer, %v", mailer) + log.Infof(nil, "aws ses mailer, %v", mailer) case "smtp": mailer = NewSmtpMailer(m) - log.Infof("smtp mailer, %v", mailer) + log.Infof(nil, "smtp mailer, %v", mailer) } return mailer diff --git a/internal/middleware/audit/audit-map.go b/internal/middleware/audit/audit-map.go index 863b71fd..a5fead14 100644 --- a/internal/middleware/audit/audit-map.go +++ b/internal/middleware/audit/audit-map.go @@ -2,6 +2,7 @@ package audit import ( "bytes" + "context" "encoding/json" "fmt" @@ -11,127 +12,127 @@ import ( "github.com/openinfradev/tks-api/pkg/log" ) -type fnAudit = func(out *bytes.Buffer, in []byte, statusCode int) (message string, description string) +type fnAudit = func(ctx context.Context, out *bytes.Buffer, in []byte, statusCode int) (message string, description string) var auditMap = map[internalApi.Endpoint]fnAudit{ - internalApi.CreateStack: func(out *bytes.Buffer, in []byte, statusCode int) (message string, description string) { + internalApi.CreateStack: func(ctx context.Context, out *bytes.Buffer, in []byte, statusCode int) (message string, description string) { input := domain.CreateStackRequest{} if err := json.Unmarshal(in, &input); err != nil { - log.Error(err) + log.Error(ctx, err) } if isSuccess(statusCode) { return fmt.Sprintf("스택 [%s]을 생성하였습니다.", input.Name), "" } else { - return fmt.Sprintf("스택 [%s]을 생성하는데 실패하였습니다.", input.Name), errorText(out) + return fmt.Sprintf("스택 [%s]을 생성하는데 실패하였습니다.", input.Name), errorText(ctx, out) } - }, internalApi.CreateProject: func(out *bytes.Buffer, in []byte, statusCode int) (message string, description string) { + }, internalApi.CreateProject: func(ctx context.Context, out *bytes.Buffer, in []byte, statusCode int) (message string, description string) { input := domain.CreateProjectRequest{} if err := json.Unmarshal(in, &input); err != nil { - log.Error(err) + log.Error(ctx, err) } if isSuccess(statusCode) { return fmt.Sprintf("프로젝트 [%s]를 생성하였습니다.", input.Name), "" } else { - return fmt.Sprintf("프로젝트 [%s]을 생성하는데 실패하였습니다.", input.Name), errorText(out) + return fmt.Sprintf("프로젝트 [%s]을 생성하는데 실패하였습니다.", input.Name), errorText(ctx, out) } - }, internalApi.CreateCloudAccount: func(out *bytes.Buffer, in []byte, statusCode int) (message string, description string) { + }, internalApi.CreateCloudAccount: func(ctx context.Context, 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) + log.Error(ctx, err) } if isSuccess(statusCode) { return fmt.Sprintf("클라우드 어카운트 [%s]를 생성하였습니다.", input.Name), "" } else { - return fmt.Sprintf("클라우드 어카운트 [%s]을 생성하는데 실패하였습니다.", input.Name), errorText(out) + return fmt.Sprintf("클라우드 어카운트 [%s]을 생성하는데 실패하였습니다.", input.Name), errorText(ctx, out) } - }, internalApi.DeleteCloudAccount: func(out *bytes.Buffer, in []byte, statusCode int) (message string, description string) { + }, internalApi.DeleteCloudAccount: func(ctx context.Context,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) + log.Error(ctx, err) } return fmt.Sprintf("클라우드어카운트 [ID:%s]를 삭제하였습니다.", output.ID), "" } else { - return "클라우드어카운트 [%s]를 삭제하는데 실패하였습니다. ", errorText(out) + return "클라우드어카운트 [%s]를 삭제하는데 실패하였습니다. ", errorText(ctx, out) } - }, internalApi.CreateUser: func(out *bytes.Buffer, in []byte, statusCode int) (message string, description string) { + }, internalApi.CreateUser: func(ctx context.Context,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) + log.Error(ctx, err) } if isSuccess(statusCode) { return fmt.Sprintf("사용자 [%s]를 생성하였습니다.", input.Name), "" } else { - return fmt.Sprintf("사용자 [%s]을 생성하는데 실패하였습니다.", input.Name), errorText(out) + return fmt.Sprintf("사용자 [%s]을 생성하는데 실패하였습니다.", input.Name), errorText(ctx, out) } - }, internalApi.CreateOrganization: func(out *bytes.Buffer, in []byte, statusCode int) (message string, description string) { + }, internalApi.CreateOrganization: func(ctx context.Context,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) + log.Error(ctx, err) } if isSuccess(statusCode) { return fmt.Sprintf("조직 [%s]를 생성하였습니다.", input.Name), "" } else { - return fmt.Sprintf("조직 [%s]을 생성하는데 실패하였습니다.", input.Name), errorText(out) + return fmt.Sprintf("조직 [%s]을 생성하는데 실패하였습니다.", input.Name), errorText(ctx, out) } - }, internalApi.DeleteOrganization: func(out *bytes.Buffer, in []byte, statusCode int) (message string, description string) { + }, internalApi.DeleteOrganization: func(ctx context.Context,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) + log.Error(ctx, err) } return fmt.Sprintf("조직 [ID:%s]를 삭제하였습니다.", output.ID), "" } else { - return "조직 [%s]를 삭제하는데 실패하였습니다. ", errorText(out) + return "조직 [%s]를 삭제하는데 실패하였습니다. ", errorText(ctx, out) } - }, internalApi.CreateAppServeApp: func(out *bytes.Buffer, in []byte, statusCode int) (message string, description string) { + }, internalApi.CreateAppServeApp: func(ctx context.Context,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) + log.Error(ctx, err) } if isSuccess(statusCode) { return fmt.Sprintf("앱서빙 [%s]를 생성하였습니다.", input.Name), "" } else { - return fmt.Sprintf("앱서빙 [%s]을 생성하는데 실패하였습니다.", input.Name), errorText(out) + return fmt.Sprintf("앱서빙 [%s]을 생성하는데 실패하였습니다.", input.Name), errorText(ctx, out) } - }, internalApi.Admin_CreateStackTemplate: func(out *bytes.Buffer, in []byte, statusCode int) (message string, description string) { + }, internalApi.Admin_CreateStackTemplate: func(ctx context.Context,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.Error(ctx, err) } - log.Info(input) + log.Info(ctx, input) if isSuccess(statusCode) { return fmt.Sprintf("스택 템플릿 [%s]를 생성하였습니다.", input.Name), "" } else { - return fmt.Sprintf("스택 템플릿 [%s]을 생성하는데 실패하였습니다.", input.Name), errorText(out) + return fmt.Sprintf("스택 템플릿 [%s]을 생성하는데 실패하였습니다.", input.Name), errorText(ctx, out) } - }, internalApi.Admin_CreateUser: func(out *bytes.Buffer, in []byte, statusCode int) (message string, description string) { + }, internalApi.Admin_CreateUser: func(ctx context.Context,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) + log.Error(ctx, err) } if isSuccess(statusCode) { return fmt.Sprintf("어드민 [%s]를 생성하였습니다.", input.Name), "" } else { - return fmt.Sprintf("어드민 [%s]을 생성하는데 실패하였습니다.", input.Name), errorText(out) + return fmt.Sprintf("어드민 [%s]을 생성하는데 실패하였습니다.", input.Name), errorText(ctx, out) } - }, internalApi.CreatePolicyTemplate: func(out *bytes.Buffer, in []byte, statusCode int) (message string, description string) { + }, internalApi.CreatePolicyTemplate: func(ctx context.Context,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) + log.Error(ctx, err) } if isSuccess(statusCode) { return fmt.Sprintf("폴리시템플릿 [%s]를 생성하였습니다.", input.TemplateName), "" } else { - return fmt.Sprintf("폴리시템플릿 [%s]을 생성하는데 실패하였습니다.", input.TemplateName), errorText(out) + return fmt.Sprintf("폴리시템플릿 [%s]을 생성하는데 실패하였습니다.", input.TemplateName), errorText(ctx, out) } }, } -func errorText(out *bytes.Buffer) string { +func errorText(ctx context.Context, out *bytes.Buffer) string { var e httpErrors.RestError if err := json.NewDecoder(out).Decode(&e); err != nil { - log.Error(err) + log.Error(ctx, err) return "" } return e.Text() diff --git a/internal/middleware/audit/audit.go b/internal/middleware/audit/audit.go index fc06c80f..33162b5f 100644 --- a/internal/middleware/audit/audit.go +++ b/internal/middleware/audit/audit.go @@ -33,7 +33,7 @@ func (a *defaultAudit) WithAudit(endpoint internalApi.Endpoint, handler http.Han return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { user, ok := request.UserFrom(r.Context()) if !ok { - log.Error("Invalid user token") + log.Error(r.Context(), "Invalid user token") return } userId := user.GetUserId() @@ -54,9 +54,9 @@ func (a *defaultAudit) WithAudit(endpoint internalApi.Endpoint, handler http.Han if endpoint != internalApi.PingToken { body, err := io.ReadAll(r.Body) if err != nil { - log.Error(err) + log.Error(r.Context(), err) } - message, description = fn(lrw.GetBody(), body, statusCode) + message, description = fn(r.Context(), lrw.GetBody(), body, statusCode) r.Body = io.NopCloser(bytes.NewBuffer(body)) dto := model.Audit{ @@ -68,7 +68,7 @@ func (a *defaultAudit) WithAudit(endpoint internalApi.Endpoint, handler http.Han UserId: &userId, } if _, err := a.repo.Create(r.Context(), dto); err != nil { - log.Error(err) + log.Error(r.Context(), err) } } } diff --git a/internal/middleware/auth/authenticator/authenticator.go b/internal/middleware/auth/authenticator/authenticator.go index 976850ac..80ea6bba 100644 --- a/internal/middleware/auth/authenticator/authenticator.go +++ b/internal/middleware/auth/authenticator/authenticator.go @@ -32,7 +32,7 @@ func (a *defaultAuthenticator) WithAuthentication(handler http.Handler) http.Han return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { resp, ok, err := a.auth.AuthenticateRequest(r) if !ok { - log.Error(err) + log.Error(r.Context(), err) internalHttp.ErrorJSON(w, r, err) return } diff --git a/internal/middleware/auth/authenticator/keycloak/keycloak.go b/internal/middleware/auth/authenticator/keycloak/keycloak.go index 49c337be..8f0ee136 100644 --- a/internal/middleware/auth/authenticator/keycloak/keycloak.go +++ b/internal/middleware/auth/authenticator/keycloak/keycloak.go @@ -40,7 +40,7 @@ func (a *keycloakAuthenticator) AuthenticateRequest(r *http.Request) (*authentic if len(token) == 0 { // The space before the token case if len(parts) == 3 { - log.Warn("the provided Authorization header contains extra space before the bearer token, and is ignored") + log.Warn(r.Context(), "the provided Authorization header contains extra space before the bearer token, and is ignored") } return nil, false, fmt.Errorf("token is empty") } @@ -59,9 +59,9 @@ func (a *keycloakAuthenticator) AuthenticateToken(r *http.Request, token string) return nil, false, httpErrors.NewUnauthorizedError(fmt.Errorf("organization is not found in token"), "A_INVALID_TOKEN", "토큰이 유효하지 않습니다.") } - isActive, err := a.kc.VerifyAccessToken(token, organizationId) + isActive, err := a.kc.VerifyAccessToken(r.Context(), token, organizationId) if err != nil { - log.Errorf("failed to verify access token: %v", err) + log.Errorf(r.Context(), "failed to verify access token: %v", err) return nil, false, httpErrors.NewUnauthorizedError(err, "C_INTERNAL_ERROR", "") } if !isActive { @@ -71,14 +71,14 @@ func (a *keycloakAuthenticator) AuthenticateToken(r *http.Request, token string) // tks role extraction roleOrganizationMapping := make(map[string]string) if roles, ok := parsedToken.Claims.(jwtWithouKey.MapClaims)["tks-role"]; !ok { - log.Errorf("tks-role is not found in token") + log.Errorf(r.Context(), "tks-role is not found in token") return nil, false, httpErrors.NewUnauthorizedError(fmt.Errorf("tks-role is not found in token"), "A_INVALID_TOKEN", "토큰이 유효하지 않습니다.") } else { for _, role := range roles.([]interface{}) { slice := strings.Split(role.(string), "@") if len(slice) != 2 { - log.Errorf("invalid tks-role format: %v", role) + log.Errorf(r.Context(), "invalid tks-role format: %v", role) return nil, false, httpErrors.NewUnauthorizedError(fmt.Errorf("invalid tks-role format"), "A_INVALID_TOKEN", "토큰이 유효하지 않습니다.") } @@ -94,7 +94,7 @@ func (a *keycloakAuthenticator) AuthenticateToken(r *http.Request, token string) for _, role := range roles.([]interface{}) { slice := strings.Split(role.(string), "@") if len(slice) != 2 { - log.Errorf("invalid project-role format: %v", role) + log.Errorf(r.Context(), "invalid project-role format: %v", role) return nil, false, httpErrors.NewUnauthorizedError(fmt.Errorf("invalid project-role format"), "A_INVALID_TOKEN", "토큰이 유효하지 않습니다.") } @@ -106,7 +106,7 @@ func (a *keycloakAuthenticator) AuthenticateToken(r *http.Request, token string) userId, err := uuid.Parse(parsedToken.Claims.(jwtWithouKey.MapClaims)["sub"].(string)) if err != nil { - log.Errorf("failed to verify access token: %v", err) + log.Errorf(r.Context(), "failed to verify access token: %v", err) return nil, false, httpErrors.NewUnauthorizedError(err, "C_INTERNAL_ERROR", "") } diff --git a/internal/middleware/auth/authorizer/rbac.go b/internal/middleware/auth/authorizer/rbac.go index 9c16508b..9813558e 100644 --- a/internal/middleware/auth/authorizer/rbac.go +++ b/internal/middleware/auth/authorizer/rbac.go @@ -38,7 +38,7 @@ func RBACFilter(handler http.Handler, repo repository.Repository) http.Handler { return } } else { - log.Warn("RBACFilter: organizationId not found. Passing through unsafely.") + log.Warn(r.Context(), "RBACFilter: organizationId not found. Passing through unsafely.") } } @@ -130,7 +130,7 @@ func RequestOrganizationValidationFilter(handler http.Handler, repo repository.R if !ok { //internalHttp.ErrorJSON(w, r, httpErrors.NewInternalServerError(fmt.Errorf("organizationId not found"), "", "")) //return - log.Warn("RequestOrganizationValidationFilter: organizationId not found. Passing through unsafely.") + log.Warn(r.Context(), "RequestOrganizationValidationFilter: organizationId not found. Passing through unsafely.") } if organizationId != requestUserInfo.GetOrganizationId() { internalHttp.ErrorJSON(w, r, httpErrors.NewForbiddenError(fmt.Errorf("permission denied"), "", "")) diff --git a/internal/middleware/auth/role/default.go b/internal/middleware/auth/role/default.go index 41bf5652..9b69bdaa 100644 --- a/internal/middleware/auth/role/default.go +++ b/internal/middleware/auth/role/default.go @@ -109,13 +109,6 @@ var defaultPermissionOfAdmin = defaultPermission{ internalApi.DeleteForceCloudAccount, internalApi.GetResourceQuota, - // StackTemplate - internalApi.GetStackTemplates, - internalApi.CreateStackTemplate, - internalApi.GetStackTemplate, - internalApi.UpdateStackTemplate, - internalApi.DeleteStackTemplate, - // Dashboard internalApi.GetChartsDashboard, internalApi.GetChartDashboard, @@ -225,8 +218,8 @@ var defaultPermissionOfUser = defaultPermission{ internalApi.GetResourceQuota, // StackTemplate - internalApi.GetStackTemplates, - internalApi.GetStackTemplate, + internalApi.Admin_GetStackTemplates, + internalApi.Admin_GetStackTemplate, // Dashboard internalApi.GetChartsDashboard, diff --git a/internal/middleware/logging/logging.go b/internal/middleware/logging/logging.go index da5fcc35..feee3af4 100644 --- a/internal/middleware/logging/logging.go +++ b/internal/middleware/logging/logging.go @@ -29,7 +29,7 @@ func LoggingMiddleware(next http.Handler) http.Handler { next.ServeHTTP(lrw, r) statusCode := lrw.GetStatusCode() - log.InfofWithContext(r.Context(), "[API_RESPONSE] [%d][%s][%s]", statusCode, http.StatusText(statusCode), lrw.GetBody().String()) - log.InfofWithContext(r.Context(), "***** END [%s %s] *****", r.Method, r.RequestURI) + log.Infof(r.Context(), "[API_RESPONSE] [%d][%s][%s]", statusCode, http.StatusText(statusCode), lrw.GetBody().String()) + log.Infof(r.Context(), "***** END [%s %s] *****", r.Method, r.RequestURI) }) } diff --git a/internal/repository/app-group.go b/internal/repository/app-group.go index edaf6a37..df2b76af 100644 --- a/internal/repository/app-group.go +++ b/internal/repository/app-group.go @@ -71,7 +71,7 @@ func (r *AppGroupRepository) Create(ctx context.Context, dto model.AppGroup) (ap } res := r.db.WithContext(ctx).Create(&appGroup) if res.Error != nil { - log.Error(res.Error) + log.Error(ctx, res.Error) return "", res.Error } diff --git a/internal/repository/app-serve-app.go b/internal/repository/app-serve-app.go index d2089fe2..53460c70 100644 --- a/internal/repository/app-serve-app.go +++ b/internal/repository/app-serve-app.go @@ -104,7 +104,7 @@ func (r *AppServeAppRepository) GetAppServeAppById(ctx context.Context, appId st res := r.db.WithContext(ctx).Where("id = ?", appId).First(&app) if res.Error != nil { - log.Debug(res.Error) + log.Debug(ctx, res.Error) return nil, res.Error } if res.RowsAffected == 0 { @@ -113,7 +113,7 @@ func (r *AppServeAppRepository) GetAppServeAppById(ctx context.Context, appId st // Populate tasks into app object if err := r.db.WithContext(ctx).Model(&app).Order("created_at desc").Association("AppServeAppTasks").Find(&app.AppServeAppTasks); err != nil { - log.Debug(err) + log.Debug(ctx, err) return nil, err } @@ -151,7 +151,7 @@ func (r *AppServeAppRepository) GetAppServeAppTaskById(ctx context.Context, task // Retrieve task info res := r.db.WithContext(ctx).Where("id = ?", taskId).First(&task) if res.Error != nil { - log.Debug(res.Error) + log.Debug(ctx, res.Error) return nil, nil, res.Error } if res.RowsAffected == 0 { @@ -161,7 +161,7 @@ func (r *AppServeAppRepository) GetAppServeAppTaskById(ctx context.Context, task // Retrieve app info res = r.db.WithContext(ctx).Where("id = ?", task.AppServeAppId).First(&app) if res.Error != nil { - log.Debug(res.Error) + log.Debug(ctx, res.Error) return nil, nil, res.Error } if res.RowsAffected == 0 { @@ -177,7 +177,7 @@ func (r *AppServeAppRepository) GetAppServeAppLatestTask(ctx context.Context, ap // TODO: Does this work?? where's app ID here? res := r.db.WithContext(ctx).Order("created_at desc").First(&task) if res.Error != nil { - log.Debug(res.Error) + log.Debug(ctx, res.Error) return nil, res.Error } if res.RowsAffected == 0 { @@ -204,7 +204,7 @@ func (r *AppServeAppRepository) IsAppServeAppExist(ctx context.Context, appId st res := r.db.WithContext(ctx).Table("app_serve_apps").Where("id = ? AND status <> 'DELETE_SUCCESS'", appId).Count(&result) if res.Error != nil { - log.Debug(res.Error) + log.Debug(ctx, res.Error) return 0, res.Error } return result, nil @@ -217,10 +217,10 @@ func (r *AppServeAppRepository) IsAppServeAppNameExist(ctx context.Context, orgI "AND name = '%v' "+ "AND status <> 'DELETE_SUCCESS'", orgId, appName) - log.Info("query = ", queryString) + log.Info(ctx, "query = ", queryString) res := r.db.WithContext(ctx).Table("app_serve_apps").Where(queryString).Count(&result) if res.Error != nil { - log.Debug(res.Error) + log.Debug(ctx, res.Error) return 0, res.Error } return result, nil diff --git a/internal/repository/cluster.go b/internal/repository/cluster.go index 7d92bdc5..02acaa2f 100644 --- a/internal/repository/cluster.go +++ b/internal/repository/cluster.go @@ -49,7 +49,7 @@ func NewClusterRepository(db *gorm.DB) IClusterRepository { // Logics func (r *ClusterRepository) WithTrx(trxHandle *gorm.DB) IClusterRepository { if trxHandle == nil { - log.Info("Transaction Database not found") + log.Info(nil, "Transaction Database not found") return r } r.tx = trxHandle @@ -150,7 +150,7 @@ func (r *ClusterRepository) Create(ctx context.Context, dto model.Cluster) (clus res := r.db.WithContext(ctx).Create(&cluster) if res.Error != nil { - log.Error(res.Error) + log.Error(ctx, res.Error) return "", res.Error } @@ -203,7 +203,7 @@ func (r *ClusterRepository) SetFavorite(ctx context.Context, clusterId domain.Cl var clusterFavorites []model.ClusterFavorite res := r.db.WithContext(ctx).Where("cluster_id = ? AND user_id = ?", clusterId, userId).Find(&clusterFavorites) if res.Error != nil { - log.Info(res.Error) + log.Info(ctx, res.Error) return res.Error } @@ -217,7 +217,7 @@ func (r *ClusterRepository) SetFavorite(ctx context.Context, clusterId domain.Cl } resCreate := r.db.Create(&clusterFavorite) if resCreate.Error != nil { - log.Error(resCreate.Error) + log.Error(ctx, resCreate.Error) return fmt.Errorf("could not create cluster favorite for clusterId %s, userId %s", clusterId, userId) } @@ -227,7 +227,7 @@ func (r *ClusterRepository) SetFavorite(ctx context.Context, clusterId domain.Cl func (r *ClusterRepository) DeleteFavorite(ctx context.Context, clusterId domain.ClusterId, userId uuid.UUID) error { res := r.db.WithContext(ctx).Unscoped().Delete(&model.ClusterFavorite{}, "cluster_id = ? AND user_id = ?", clusterId, userId) if res.Error != nil { - log.Error(res.Error) + log.Error(ctx, res.Error) return fmt.Errorf("could not delete cluster favorite for clusterId %s, userId %s", clusterId, userId) } return nil diff --git a/internal/repository/mapper.go b/internal/repository/mapper.go index c7f7583c..4436142b 100644 --- a/internal/repository/mapper.go +++ b/internal/repository/mapper.go @@ -6,7 +6,6 @@ import ( "github.com/google/uuid" "github.com/openinfradev/tks-api/pkg/domain" - "github.com/openinfradev/tks-api/pkg/log" ) type ConverterMap map[compositeKey]func(interface{}) (interface{}, error) @@ -47,7 +46,7 @@ func recursiveMap(src interface{}, dst interface{}, converterMap ConverterMap) e dstField.Set(reflect.ValueOf(converted)) } } else { - log.Errorf("no converter found for %s -> %s", srcField.Type(), dstField.Type()) + //log.Errorf("no converter found for %s -> %s", srcField.Type(), dstField.Type()) continue } } diff --git a/internal/repository/organization.go b/internal/repository/organization.go index 072b2d6a..e98cd899 100644 --- a/internal/repository/organization.go +++ b/internal/repository/organization.go @@ -65,7 +65,7 @@ func (r *OrganizationRepository) Create(ctx context.Context, dto *model.Organiza } res := r.db.WithContext(ctx).Create(&organization) if res.Error != nil { - log.Errorf("error is :%s(%T)", res.Error.Error(), res.Error) + log.Errorf(ctx, "error is :%s(%T)", res.Error.Error(), res.Error) return model.Organization{}, res.Error } @@ -88,7 +88,7 @@ func (r *OrganizationRepository) Get(ctx context.Context, id string) (out model. res := r.db.WithContext(ctx).Preload(clause.Associations). First(&out, "id = ?", id) if res.Error != nil { - log.Errorf("error is :%s(%T)", res.Error.Error(), res.Error) + log.Errorf(ctx, "error is :%s(%T)", res.Error.Error(), res.Error) return model.Organization{}, res.Error } return @@ -104,12 +104,12 @@ func (r *OrganizationRepository) Update(ctx context.Context, organizationId stri }) if res.Error != nil { - log.Errorf("error is :%s(%T)", res.Error.Error(), res.Error) + log.Errorf(ctx, "error is :%s(%T)", res.Error.Error(), res.Error) return model.Organization{}, res.Error } 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) + log.Errorf(ctx, "error is :%s(%T)", res.Error.Error(), res.Error) return model.Organization{}, res.Error } return @@ -123,7 +123,7 @@ func (r *OrganizationRepository) UpdatePrimaryClusterId(ctx context.Context, org }) if res.Error != nil { - log.Errorf("error is :%s(%T)", res.Error.Error(), res.Error) + log.Errorf(ctx, "error is :%s(%T)", res.Error.Error(), res.Error) return res.Error } return nil @@ -137,7 +137,7 @@ func (r *OrganizationRepository) UpdateAdminId(ctx context.Context, organization }) if res.Error != nil { - log.Errorf("error is :%s(%T)", res.Error.Error(), res.Error) + log.Errorf(ctx, "error is :%s(%T)", res.Error.Error(), res.Error) return res.Error } return nil @@ -146,7 +146,7 @@ func (r *OrganizationRepository) UpdateAdminId(ctx context.Context, organization func (r *OrganizationRepository) Delete(ctx context.Context, organizationId string) error { res := r.db.WithContext(ctx).Delete(&model.Organization{}, "id = ?", organizationId) if res.Error != nil { - log.Errorf("error is :%s(%T)", res.Error.Error(), res.Error) + log.Errorf(ctx, "error is :%s(%T)", res.Error.Error(), res.Error) return res.Error } @@ -158,7 +158,7 @@ func (r *OrganizationRepository) InitWorkflow(ctx context.Context, organizationI Where("ID = ?", organizationId). Updates(map[string]interface{}{"Status": status, "WorkflowId": workflowId}) if res.Error != nil { - log.Errorf("error is :%s(%T)", res.Error.Error(), res.Error) + log.Errorf(ctx, "error is :%s(%T)", res.Error.Error(), res.Error) return res.Error } return nil diff --git a/internal/repository/project.go b/internal/repository/project.go index 4260ea6a..ccd54b60 100644 --- a/internal/repository/project.go +++ b/internal/repository/project.go @@ -151,7 +151,7 @@ func (r *ProjectRepository) GetProjects(ctx context.Context, organizationId stri Scan(&pr) if res.Error != nil { if errors.Is(res.Error, gorm.ErrRecordNotFound) { - log.Info("Cannot find project") + log.Info(ctx, "Cannot find project") } } return pr, nil @@ -203,10 +203,10 @@ func (r *ProjectRepository) GetProjectsByUserId(ctx context.Context, organizatio if res.Error != nil { if errors.Is(res.Error, gorm.ErrRecordNotFound) { - log.Info("Cannot find project") + log.Info(ctx, "Cannot find project") return nil, nil } else { - log.Error(res.Error) + log.Error(ctx, res.Error) return nil, res.Error } } @@ -256,10 +256,10 @@ func (r *ProjectRepository) GetAllProjects(ctx context.Context, organizationId s if res.Error != nil { if errors.Is(res.Error, gorm.ErrRecordNotFound) { - log.Info("Cannot find project") + log.Info(ctx, "Cannot find project") return nil, nil } else { - log.Error(res.Error) + log.Error(ctx, res.Error) return nil, res.Error } } @@ -271,10 +271,10 @@ func (r *ProjectRepository) GetProjectById(ctx context.Context, organizationId s res := r.db.WithContext(ctx).Limit(1).Where("organization_id = ? and id = ?", organizationId, projectId).First(&p) if res.Error != nil { if errors.Is(res.Error, gorm.ErrRecordNotFound) { - log.Info("Cannot find project") + log.Info(ctx, "Cannot find project") return nil, nil } else { - log.Error(res.Error) + log.Error(ctx, res.Error) return nil, res.Error } } @@ -291,10 +291,10 @@ func (r *ProjectRepository) GetProjectByIdAndLeader(ctx context.Context, organiz if res.Error != nil { if errors.Is(res.Error, gorm.ErrRecordNotFound) { - log.Info("Cannot find project") + log.Info(ctx, "Cannot find project") return nil, nil } else { - log.Error(res.Error) + log.Error(ctx, res.Error) return nil, res.Error } } @@ -308,10 +308,10 @@ func (r *ProjectRepository) GetProjectByName(ctx context.Context, organizationId First(&p) if res.Error != nil { if errors.Is(res.Error, gorm.ErrRecordNotFound) { - log.Info("Not found project name") + log.Info(ctx, "Not found project name") return nil, nil } else { - log.Error(res.Error) + log.Error(ctx, res.Error) return nil, res.Error } } @@ -333,10 +333,10 @@ func (r *ProjectRepository) GetProjectRoleById(ctx context.Context, id string) ( res := r.db.WithContext(ctx).First(pr) if res.Error != nil { if errors.Is(res.Error, gorm.ErrRecordNotFound) { - log.Info("Cannot find project role") + log.Info(ctx, "Cannot find project role") return nil, nil } else { - log.Error(res.Error) + log.Error(ctx, res.Error) return nil, res.Error } } @@ -348,10 +348,10 @@ func (r *ProjectRepository) GetAllProjectRoles(ctx context.Context) (prs []model res := r.db.WithContext(ctx).Find(&prs) if res.Error != nil { if errors.Is(res.Error, gorm.ErrRecordNotFound) { - log.Info("Cannot find project roles") + log.Info(ctx, "Cannot find project roles") return nil, nil } else { - log.Error(res.Error) + log.Error(ctx, res.Error) return nil, res.Error } } @@ -363,10 +363,10 @@ func (r *ProjectRepository) GetProjectRoleByName(ctx context.Context, name strin res := r.db.WithContext(ctx).Where("name = ?", name).First(&pr) if res.Error != nil { if errors.Is(res.Error, gorm.ErrRecordNotFound) { - log.Info("Cannot find project roles") + log.Info(ctx, "Cannot find project roles") return nil, nil } else { - log.Error(res.Error) + log.Error(ctx, res.Error) return nil, res.Error } } @@ -393,10 +393,10 @@ func (r *ProjectRepository) GetProjectMembersByProjectId(ctx context.Context, pr Order("project_members.created_at ASC"), &pms) if res.Error != nil { if errors.Is(res.Error, gorm.ErrRecordNotFound) { - log.Info("Cannot find project member") + log.Info(ctx, "Cannot find project member") return nil, nil } else { - log.Error(res.Error) + log.Error(ctx, res.Error) return nil, res.Error } } @@ -415,10 +415,10 @@ func (r *ProjectRepository) GetProjectMembersByProjectIdAndRoleName(ctx context. if res.Error != nil { if errors.Is(res.Error, gorm.ErrRecordNotFound) { - log.Info("Cannot find project member") + log.Info(ctx, "Cannot find project member") return nil, nil } else { - log.Error(res.Error) + log.Error(ctx, res.Error) return nil, res.Error } } @@ -450,10 +450,10 @@ func (r *ProjectRepository) GetProjectMemberCountByProjectId(ctx context.Context Scan(&pmcr) if res.Error != nil { if errors.Is(res.Error, gorm.ErrRecordNotFound) { - log.Info("Cannot find project member count") + log.Info(ctx, "Cannot find project member count") return nil, nil } else { - log.Error(res.Error) + log.Error(ctx, res.Error) return nil, res.Error } } @@ -466,10 +466,10 @@ func (r *ProjectRepository) GetProjectMemberById(ctx context.Context, projectMem Joins("ProjectRole").Where("project_members.id = ?", projectMemberId).First(&pm) if res.Error != nil { if errors.Is(res.Error, gorm.ErrRecordNotFound) { - log.Info("Cannot find project member") + log.Info(ctx, "Cannot find project member") return nil, nil } else { - log.Error(res.Error) + log.Error(ctx, res.Error) return nil, res.Error } } @@ -482,10 +482,10 @@ func (r *ProjectRepository) GetProjectMemberByUserId(ctx context.Context, projec Joins("ProjectRole").Where("project_id = ? and project_user_id = ?", projectId, projectUserId).First(&pm) if res.Error != nil { if errors.Is(res.Error, gorm.ErrRecordNotFound) { - log.Info("Cannot find project member") + log.Info(ctx, "Cannot find project member") return nil, nil } else { - log.Error(res.Error) + log.Error(ctx, res.Error) return nil, res.Error } } @@ -542,10 +542,10 @@ func (r *ProjectRepository) GetProjectNamespaceByName(ctx context.Context, organ First(&pn) if res.Error != nil { if errors.Is(res.Error, gorm.ErrRecordNotFound) { - log.Info("Not found project namespace") + log.Info(ctx, "Not found project namespace") return nil, nil } else { - log.Error(res.Error) + log.Error(ctx, res.Error) return nil, res.Error } } @@ -561,10 +561,10 @@ func (r *ProjectRepository) GetProjectNamespaces(ctx context.Context, organizati Preload("Stack"), &pns) if res.Error != nil { if errors.Is(res.Error, gorm.ErrRecordNotFound) { - log.Info("Not found project namespaces") + log.Info(ctx, "Not found project namespaces") return nil, nil } else { - log.Error(res.Error) + log.Error(ctx, res.Error) return nil, res.Error } } @@ -580,10 +580,10 @@ func (r *ProjectRepository) GetProjectNamespaceByPrimaryKey(ctx context.Context, First(&pn) if res.Error != nil { if errors.Is(res.Error, gorm.ErrRecordNotFound) { - log.Info("Not found project namespace") + log.Info(ctx, "Not found project namespace") return nil, nil } else { - log.Error(res.Error) + log.Error(ctx, res.Error) return nil, res.Error } } @@ -617,7 +617,7 @@ func (r *ProjectRepository) GetAppCountByProjectId(ctx context.Context, organiza Where("organization_id = ? and project_Id = ?", organizationId, projectId). Find(&appCount) if res.Error != nil { - log.Error(res.Error) + log.Error(ctx, res.Error) return 0, res.Error } @@ -630,7 +630,7 @@ func (r *ProjectRepository) GetAppCountByNamespace(ctx context.Context, organiza Where("organization_id = ? and project_Id = ? and namespace = ?", organizationId, projectId, namespace). Find(&appCount) if res.Error != nil { - log.Error(res.Error) + log.Error(ctx, res.Error) return 0, res.Error } diff --git a/internal/repository/user.go b/internal/repository/user.go index 99a4b98e..59627743 100644 --- a/internal/repository/user.go +++ b/internal/repository/user.go @@ -39,7 +39,7 @@ type UserRepository struct { func (r *UserRepository) Flush(ctx context.Context, organizationId string) error { res := r.db.WithContext(ctx).Where("organization_id = ?", organizationId).Delete(&model.User{}) if res.Error != nil { - log.Errorf("error is :%s(%T)", res.Error.Error(), res.Error) + log.Errorf(ctx, "error is :%s(%T)", res.Error.Error(), res.Error) return res.Error } return nil @@ -66,7 +66,7 @@ func (r *UserRepository) CreateWithUuid(ctx context.Context, uuid uuid.UUID, acc } res := r.db.WithContext(ctx).Create(&newUser) if res.Error != nil { - log.Error(res.Error.Error()) + log.Error(ctx, res.Error.Error()) return model.User{}, res.Error } user, err := r.getUserByAccountId(nil, accountId, organizationId) @@ -97,7 +97,7 @@ func (r *UserRepository) List(ctx context.Context, filters ...FilterFunc) (*[]mo } if res.Error != nil { - log.Errorf("error is :%s(%T)", res.Error.Error(), res.Error) + log.Errorf(ctx, "error is :%s(%T)", res.Error.Error(), res.Error) return nil, res.Error } if res.RowsAffected == 0 { @@ -121,7 +121,7 @@ func (r *UserRepository) ListWithPagination(ctx context.Context, pg *pagination. _, res := pg.Fetch(r.db.WithContext(ctx).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) + log.Errorf(ctx, "error is :%s(%T)", res.Error.Error(), res.Error) return nil, res.Error } @@ -147,7 +147,7 @@ func (r *UserRepository) GetByUuid(ctx context.Context, userId uuid.UUID) (respU res := r.db.WithContext(ctx).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) + log.Errorf(ctx, "error is :%s(%T)", res.Error.Error(), res.Error) return model.User{}, res.Error } if res.RowsAffected == 0 { @@ -171,7 +171,7 @@ func (r *UserRepository) UpdateWithUuid(ctx context.Context, uuid uuid.UUID, acc return model.User{}, httpErrors.NewNotFoundError(httpErrors.NotFound, "", "") } if res.Error != nil { - log.Errorf("error is :%s(%T)", res.Error.Error(), res.Error) + log.Errorf(ctx, "error is :%s(%T)", res.Error.Error(), res.Error) return model.User{}, res.Error } res = r.db.Model(&model.User{}).Preload("Organization").Preload("Role").Where("id = ?", uuid).Find(&user) @@ -195,7 +195,7 @@ func (r *UserRepository) UpdatePasswordAt(ctx context.Context, userId uuid.UUID, return httpErrors.NewNotFoundError(httpErrors.NotFound, "", "") } if res.Error != nil { - log.Errorf("error is :%s(%T)", res.Error.Error(), res.Error) + log.Errorf(ctx, "error is :%s(%T)", res.Error.Error(), res.Error) return res.Error } @@ -205,7 +205,7 @@ func (r *UserRepository) UpdatePasswordAt(ctx context.Context, userId uuid.UUID, func (r *UserRepository) DeleteWithUuid(ctx context.Context, uuid uuid.UUID) error { res := r.db.WithContext(ctx).Unscoped().Delete(&model.User{}, "id = ?", uuid) if res.Error != nil { - log.Errorf("error is :%s(%T)", res.Error.Error(), res.Error) + log.Errorf(ctx, "error is :%s(%T)", res.Error.Error(), res.Error) return res.Error } return nil @@ -248,7 +248,7 @@ func (r *UserRepository) getUserByAccountId(ctx context.Context, accountId strin res := r.db.WithContext(ctx).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) + log.Errorf(ctx, "error is :%s(%T)", res.Error.Error(), res.Error) return model.User{}, res.Error } if res.RowsAffected == 0 { @@ -262,7 +262,7 @@ func (r *UserRepository) getRoleByName(ctx context.Context, roleName string) (mo role := model.Role{} res := r.db.WithContext(ctx).First(&role, "name = ?", roleName) if res.Error != nil { - log.Errorf("error is :%s(%T)", res.Error.Error(), res.Error) + log.Errorf(ctx, "error is :%s(%T)", res.Error.Error(), res.Error) return model.Role{}, res.Error } if res.RowsAffected == 0 { diff --git a/internal/route/route.go b/internal/route/route.go index b7d0b827..5989edba 100644 --- a/internal/route/route.go +++ b/internal/route/route.go @@ -305,7 +305,7 @@ func transactionMiddleware(db *gorm.DB) mux.MiddlewareFunc { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { ctx := r.Context() txHandle := db.Begin() - log.DebugWithContext(r.Context(),"beginning database transaction") + log.Debug(r.Context(),"beginning database transaction") defer func() { if r := recover(); r != nil { @@ -322,12 +322,12 @@ func transactionMiddleware(db *gorm.DB) mux.MiddlewareFunc { next.ServeHTTP(recorder, r) if StatusInList(recorder.Status, []int{http.StatusOK}) { - log.DebugWithContext(r.Context(),"committing transactions") + log.Debug(r.Context(),"committing transactions") if err := txHandle.Commit().Error; err != nil { - log.DebugWithContext(r.Context(),"trx commit error: ", err) + log.Debug(r.Context(),"trx commit error: ", err) } } else { - log.DebugWithContext(r.Context(),"rolling back transaction due to status code: ", recorder.Status) + log.Debug(r.Context(),"rolling back transaction due to status code: ", recorder.Status) txHandle.Rollback() } }) diff --git a/internal/usecase/alert.go b/internal/usecase/alert.go index c8397d07..7632170f 100644 --- a/internal/usecase/alert.go +++ b/internal/usecase/alert.go @@ -274,7 +274,7 @@ func (u *AlertUsecase) makeGrafanaUrl(ctx context.Context, primaryCluster model. case "pvc-full": url = primaryGrafanaEndpoint + "/d/tks_cluster_dashboard/tks-kubernetes-view-cluster-global?var-taco_cluster=" + clusterId.String() + "&kiosk" default: - log.ErrorfWithContext(ctx, "Invalid alert name %s", alert.Labels.AlertName) + log.Errorf(ctx, "Invalid alert name %s", alert.Labels.AlertName) } return diff --git a/internal/usecase/app-group.go b/internal/usecase/app-group.go index 8bf631ab..39d7c8ac 100644 --- a/internal/usecase/app-group.go +++ b/internal/usecase/app-group.go @@ -146,7 +146,7 @@ func (u *AppGroupUsecase) Create(ctx context.Context, dto model.AppGroup) (id do return "", errors.Wrap(err, fmt.Sprintf("Invalid appGroup type. %s", dto.AppGroupType.String())) } - workflowId, err := u.argo.SumbitWorkflowFromWftpl(workflowTemplate, opts) + workflowId, err := u.argo.SumbitWorkflowFromWftpl(ctx, workflowTemplate, opts) if err != nil { log.Error(ctx, "failed to submit argo workflow template. err : ", err) return "", httpErrors.NewInternalServerError(err, "AG_FAILED_TO_CALL_WORKFLOW", "") @@ -235,12 +235,12 @@ func (u *AppGroupUsecase) Delete(ctx context.Context, id domain.AppGroupId) (err "object_store=" + tksObjectStore, } - workflowId, err := u.argo.SumbitWorkflowFromWftpl(workflowTemplate, opts) + workflowId, err := u.argo.SumbitWorkflowFromWftpl(ctx, workflowTemplate, opts) if err != nil { return fmt.Errorf("Failed to call argo workflow : %s", err) } - log.DebugWithContext(ctx, "submited workflow name : ", workflowId) + log.Debug(ctx, "submited workflow name : ", workflowId) if err := u.repo.InitWorkflow(ctx, id, workflowId, domain.AppGroupStatus_DELETING); err != nil { return fmt.Errorf("Failed to initialize appGroup status. err : %s", err) diff --git a/internal/usecase/app-serve-app.go b/internal/usecase/app-serve-app.go index c58539c1..4fb12686 100644 --- a/internal/usecase/app-serve-app.go +++ b/internal/usecase/app-serve-app.go @@ -103,15 +103,15 @@ func (u *AppServeAppUsecase) CreateAppServeApp(ctx context.Context, app *model.A extEnv := app.AppServeAppTasks[0].ExtraEnv if extEnv != "" { /* Preprocess extraEnv param */ - log.Debug("extraEnv received: ", extEnv) + log.Debug(ctx, "extraEnv received: ", extEnv) tempMap := map[string]string{} err := json.Unmarshal([]byte(extEnv), &tempMap) if err != nil { - log.Error(err) + log.Error(ctx, err) return "", "", errors.Wrap(err, "Failed to process extraEnv param.") } - log.Debugf("extraEnv marshalled: %v", tempMap) + log.Debugf(ctx, "extraEnv marshalled: %v", tempMap) newExtEnv := map[string]string{} for key, val := range tempMap { @@ -122,12 +122,12 @@ func (u *AppServeAppUsecase) CreateAppServeApp(ctx context.Context, app *model.A mJson, _ := json.Marshal(newExtEnv) extEnv = string(mJson) - log.Debug("After transform, extraEnv: ", extEnv) + log.Debug(ctx, "After transform, extraEnv: ", extEnv) } appId, taskId, err := u.repo.CreateAppServeApp(ctx, app) if err != nil { - log.Error(err) + log.Error(ctx, err) return "", "", errors.Wrap(err, "Failed to create app.") } @@ -168,14 +168,14 @@ func (u *AppServeAppUsecase) CreateAppServeApp(ctx context.Context, app *model.A "tks_api_url=" + viper.GetString("external-address"), } - log.Info("Submitting workflow: ", workflow) + log.Info(ctx, "Submitting workflow: ", workflow) - workflowId, err := u.argo.SumbitWorkflowFromWftpl(workflow, opts) + workflowId, err := u.argo.SumbitWorkflowFromWftpl(ctx, workflow, opts) if err != nil { - log.Error(err) + log.Error(ctx, err) return "", "", errors.Wrap(err, fmt.Sprintf("failed to submit workflow. %s", workflow)) } - log.Info("Successfully submitted workflow: ", workflowId) + log.Info(ctx, "Successfully submitted workflow: ", workflowId) return appId, app.Name, nil } @@ -226,7 +226,7 @@ func (u *AppServeAppUsecase) GetAppServeAppById(ctx context.Context, appId strin func (u *AppServeAppUsecase) GetAppServeAppTasks(ctx context.Context, appId string, pg *pagination.Pagination) ([]model.AppServeAppTask, error) { tasks, err := u.repo.GetAppServeAppTasksByAppId(ctx, appId, pg) if err != nil { - log.Debugf("Tasks: %v", tasks) + log.Debugf(ctx, "Tasks: %v", tasks) } return tasks, nil @@ -286,36 +286,36 @@ func (u *AppServeAppUsecase) IsAppServeAppNameExist(ctx context.Context, orgId s } func (u *AppServeAppUsecase) IsAppServeAppNamespaceExist(ctx context.Context, clusterId string, new_ns string) (bool, error) { - clientset, err := kubernetes.GetClientFromClusterId(clusterId) + clientset, err := kubernetes.GetClientFromClusterId(ctx, clusterId) if err != nil { - log.Error(err) + log.Error(ctx, err) return false, err } namespaces, err := clientset.CoreV1().Namespaces().List(context.TODO(), metav1.ListOptions{}) if err != nil { - log.Error(err) + log.Error(ctx, err) return false, err } for _, ns := range namespaces.Items { if new_ns == ns.ObjectMeta.Name { - log.Debugf("Namespace %s already exists.", new_ns) + log.Debugf(ctx, "Namespace %s already exists.", new_ns) return true, nil } } - log.Debugf("Namespace %s is available", new_ns) + log.Debugf(ctx, "Namespace %s is available", new_ns) return false, nil } func (u *AppServeAppUsecase) UpdateAppServeAppStatus(ctx context.Context, appId string, taskId string, status string, output string) (string, error) { - log.Info("Starting status update process..") + log.Info(ctx, "Starting status update process..") err := u.repo.UpdateStatus(ctx, appId, taskId, status, output) if err != nil { - log.Info("appId = ", appId) - log.Info("taskId = ", taskId) + log.Info(ctx, "appId = ", appId) + log.Info(ctx, "taskId = ", taskId) return "", fmt.Errorf("failed to update app status. Err: %s", err) } return fmt.Sprintf("The appId '%s' status is being updated.", appId), nil @@ -329,12 +329,12 @@ func (u *AppServeAppUsecase) UpdateAppServeAppEndpoint( previewEndpoint string, helmRevision int32) (string, error) { - log.Info("Starting endpoint update process..") + log.Info(ctx, "Starting endpoint update process..") err := u.repo.UpdateEndpoint(ctx, appId, taskId, endpoint, previewEndpoint, helmRevision) if err != nil { - log.Info("appId = ", appId) - log.Info("taskId = ", taskId) + log.Info(ctx, "appId = ", appId) + log.Info(ctx, "taskId = ", taskId) return "", fmt.Errorf("failed to update endpoint. Err: %s", err) } return fmt.Sprintf("The appId '%s' endpoint is being updated.", appId), nil @@ -373,24 +373,24 @@ func (u *AppServeAppUsecase) DeleteAppServeApp(ctx context.Context, appId string taskId, err := u.repo.CreateTask(ctx, appTask) if err != nil { - log.Error("taskId = ", taskId) - log.Error("Failed to create delete task. Err:", err) + log.Error(ctx, "taskId = ", taskId) + log.Error(ctx, "Failed to create delete task. Err:", err) return "", errors.Wrap(err, "Failed to create delete task.") } - log.Info("Updating app status to 'DELETING'..") + log.Info(ctx, "Updating app status to 'DELETING'..") err = u.repo.UpdateStatus(ctx, appId, taskId, "DELETING", "") if err != nil { - log.Debug("appId = ", appId) - log.Debug("taskId = ", taskId) + log.Debug(ctx, "appId = ", appId) + log.Debug(ctx, "taskId = ", taskId) return "", fmt.Errorf("failed to update app status on DeleteAppServeApp. Err: %s", err) } workflow := "delete-java-app" - log.Info("Submitting workflow: ", workflow) + log.Info(ctx, "Submitting workflow: ", workflow) - workflowId, err := u.argo.SumbitWorkflowFromWftpl(workflow, argowf.SubmitOptions{ + workflowId, err := u.argo.SumbitWorkflowFromWftpl(ctx, workflow, argowf.SubmitOptions{ Parameters: []string{ "target_cluster_id=" + app.TargetClusterId, "app_name=" + app.Name, @@ -402,10 +402,10 @@ func (u *AppServeAppUsecase) DeleteAppServeApp(ctx context.Context, appId string }, }) if err != nil { - log.Error("Failed to submit workflow. Err:", err) + log.Error(ctx, "Failed to submit workflow. Err:", err) return "", errors.Wrap(err, "Failed to submit workflow.") } - log.Info("Successfully submitted workflow: ", workflowId) + log.Info(ctx, "Successfully submitted workflow: ", workflowId) return fmt.Sprintf("The app %s is being deleted. "+ "Confirm result by checking the app status after a while.", app.Name), nil @@ -426,7 +426,7 @@ func (u *AppServeAppUsecase) UpdateAppServeApp(ctx context.Context, app *model.A return "승인대기 또는 프로모트 작업 중에는 업그레이드를 수행할 수 없습니다", fmt.Errorf("Update not possible. The app is waiting for promote or in the middle of promote process.") } - log.Info("Starting normal update process..") + log.Info(ctx, "Starting normal update process..") // TODO: for more strict validation, check if immutable fields are provided by user // and those values are changed or not. (name, type, app_type, target_cluster) @@ -456,15 +456,15 @@ func (u *AppServeAppUsecase) UpdateAppServeApp(ctx context.Context, app *model.A extEnv := appTask.ExtraEnv if extEnv != "" { /* Preprocess extraEnv param */ - log.Debug("extraEnv received: ", extEnv) + log.Debug(ctx, "extraEnv received: ", extEnv) tempMap := map[string]string{} err = json.Unmarshal([]byte(extEnv), &tempMap) if err != nil { - log.Error(err) + log.Error(ctx, err) return "", errors.Wrap(err, "Failed to process extraEnv param.") } - log.Debugf("extraEnv marshalled: %v", tempMap) + log.Debugf(ctx, "extraEnv marshalled: %v", tempMap) newExtEnv := map[string]string{} for key, val := range tempMap { @@ -475,31 +475,31 @@ func (u *AppServeAppUsecase) UpdateAppServeApp(ctx context.Context, app *model.A mJson, _ := json.Marshal(newExtEnv) extEnv = string(mJson) - log.Debug("After transform, extraEnv: ", extEnv) + log.Debug(ctx, "After transform, extraEnv: ", extEnv) } taskId, err := u.repo.CreateTask(ctx, appTask) if err != nil { - log.Info("taskId = ", taskId) + log.Info(ctx, "taskId = ", taskId) return "", fmt.Errorf("failed to update app-serve application. Err: %s", err) } // Sync new task status to the parent app - log.Info("Updating app status to 'PREPARING'..") + log.Info(ctx, "Updating app status to 'PREPARING'..") err = u.repo.UpdateStatus(ctx, app.ID, taskId, "PREPARING", "") if err != nil { - log.Debug("appId = ", app.ID) - log.Debug("taskId = ", taskId) + log.Debug(ctx, "appId = ", app.ID) + log.Debug(ctx, "taskId = ", taskId) return "", fmt.Errorf("failed to update app status on UpdateAppServeApp. Err: %s", err) } // Call argo workflow workflow := "serve-java-app" - log.Info("Submitting workflow: ", workflow) + log.Info(ctx, "Submitting workflow: ", workflow) - workflowId, err := u.argo.SumbitWorkflowFromWftpl(workflow, argowf.SubmitOptions{ + workflowId, err := u.argo.SumbitWorkflowFromWftpl(ctx, workflow, argowf.SubmitOptions{ Parameters: []string{ "type=" + app.Type, "strategy=" + appTask.Strategy, @@ -530,10 +530,10 @@ func (u *AppServeAppUsecase) UpdateAppServeApp(ctx context.Context, app *model.A }, }) if err != nil { - log.Error("Failed to submit workflow. Err:", err) + log.Error(ctx, "Failed to submit workflow. Err:", err) return "", fmt.Errorf("failed to submit workflow. Err: %s", err) } - log.Info("Successfully submitted workflow: ", workflowId) + log.Info(ctx, "Successfully submitted workflow: ", workflowId) var message string if appTask.Strategy == "rolling-update" { @@ -558,24 +558,24 @@ func (u *AppServeAppUsecase) PromoteAppServeApp(ctx context.Context, appId strin // Get the latest task ID so that the task status can be modified inside workflow once the promotion is done. latestTaskId := app.AppServeAppTasks[0].ID strategy := app.AppServeAppTasks[0].Strategy - log.Info("latestTaskId = ", latestTaskId) - log.Info("strategy = ", strategy) + log.Info(ctx, "latestTaskId = ", latestTaskId) + log.Info(ctx, "strategy = ", strategy) - log.Info("Updating app status to 'PROMOTING'..") + log.Info(ctx, "Updating app status to 'PROMOTING'..") err = u.repo.UpdateStatus(ctx, appId, latestTaskId, "PROMOTING", "") if err != nil { - log.Debug("appId = ", appId) - log.Debug("taskId = ", latestTaskId) + log.Debug(ctx, "appId = ", appId) + log.Debug(ctx, "taskId = ", latestTaskId) return "", fmt.Errorf("failed to update app status on PromoteAppServeApp. Err: %s", err) } // Call argo workflow workflow := "promote-java-app" - log.Info("Submitting workflow: ", workflow) + log.Info(ctx, "Submitting workflow: ", workflow) - workflowId, err := u.argo.SumbitWorkflowFromWftpl(workflow, argowf.SubmitOptions{ + workflowId, err := u.argo.SumbitWorkflowFromWftpl(ctx, workflow, argowf.SubmitOptions{ Parameters: []string{ "organization_id=" + app.OrganizationId, "target_cluster_id=" + app.TargetClusterId, @@ -588,10 +588,10 @@ func (u *AppServeAppUsecase) PromoteAppServeApp(ctx context.Context, appId strin }, }) if err != nil { - log.Error("failed to submit workflow. Err:", err) + log.Error(ctx, "failed to submit workflow. Err:", err) return "", fmt.Errorf("failed to submit workflow. Err: %s", err) } - log.Info("Successfully submitted workflow: ", workflowId) + log.Info(ctx, "Successfully submitted workflow: ", workflowId) return fmt.Sprintf("The app '%s' is being promoted. "+ "Confirm result by checking the app status after a while.", app.Name), nil @@ -610,25 +610,25 @@ func (u *AppServeAppUsecase) AbortAppServeApp(ctx context.Context, appId string) // Get the latest task ID so that the task status can be modified inside workflow once the abort process is done. latestTaskId := app.AppServeAppTasks[0].ID strategy := app.AppServeAppTasks[0].Strategy - log.Info("latestTaskId = ", latestTaskId) - log.Info("strategy = ", strategy) + log.Info(ctx, "latestTaskId = ", latestTaskId) + log.Info(ctx, "strategy = ", strategy) - log.Info("Updating app status to 'ABORTING'..") + log.Info(ctx, "Updating app status to 'ABORTING'..") err = u.repo.UpdateStatus(ctx, appId, latestTaskId, "ABORTING", "") if err != nil { - log.Debug("appId = ", appId) - log.Debug("taskId = ", latestTaskId) + log.Debug(ctx, "appId = ", appId) + log.Debug(ctx, "taskId = ", latestTaskId) return "", fmt.Errorf("failed to update app status on AbortAppServeApp. Err: %s", err) } // Call argo workflow workflow := "abort-java-app" - log.Info("Submitting workflow: ", workflow) + log.Info(ctx, "Submitting workflow: ", workflow) // Call argo workflow - workflowId, err := u.argo.SumbitWorkflowFromWftpl(workflow, argowf.SubmitOptions{ + workflowId, err := u.argo.SumbitWorkflowFromWftpl(ctx, workflow, argowf.SubmitOptions{ Parameters: []string{ "organization_id=" + app.OrganizationId, "target_cluster_id=" + app.TargetClusterId, @@ -643,14 +643,14 @@ func (u *AppServeAppUsecase) AbortAppServeApp(ctx context.Context, appId string) if err != nil { return "", fmt.Errorf("failed to submit workflow. Err: %s", err) } - log.Info("Successfully submitted workflow: ", workflowId) + log.Info(ctx, "Successfully submitted workflow: ", workflowId) return fmt.Sprintf("The app '%s' is being promoted. "+ "Confirm result by checking the app status after a while.", app.Name), nil } func (u *AppServeAppUsecase) RollbackAppServeApp(ctx context.Context, appId string, taskId string) (ret string, err error) { - log.Info("Starting rollback process..") + log.Info(ctx, "Starting rollback process..") app, err := u.repo.GetAppServeAppById(ctx, appId) if err != nil { @@ -683,25 +683,25 @@ func (u *AppServeAppUsecase) RollbackAppServeApp(ctx context.Context, appId stri // Creates new task record from the target task newTaskId, err := u.repo.CreateTask(ctx, &task) if err != nil { - log.Info("taskId = ", newTaskId) + log.Info(ctx, "taskId = ", newTaskId) return "", fmt.Errorf("failed to rollback app-serve application. Err: %s", err) } - log.Info("Updating app status to 'ROLLBACKING'..") + log.Info(ctx, "Updating app status to 'ROLLBACKING'..") err = u.repo.UpdateStatus(ctx, appId, newTaskId, "ROLLBACKING", "") if err != nil { - log.Debug("appId = ", appId) - log.Debug("taskId = ", newTaskId) + log.Debug(ctx, "appId = ", appId) + log.Debug(ctx, "taskId = ", newTaskId) return "", fmt.Errorf("failed to update app status on RollbackAppServeApp. Err: %s", err) } // Call argo workflow workflow := "rollback-java-app" - log.Info("Submitting workflow: ", workflow) + log.Info(ctx, "Submitting workflow: ", workflow) - workflowId, err := u.argo.SumbitWorkflowFromWftpl(workflow, argowf.SubmitOptions{ + workflowId, err := u.argo.SumbitWorkflowFromWftpl(ctx, workflow, argowf.SubmitOptions{ Parameters: []string{ "organization_id=" + app.OrganizationId, "target_cluster_id=" + app.TargetClusterId, @@ -714,10 +714,10 @@ func (u *AppServeAppUsecase) RollbackAppServeApp(ctx context.Context, appId stri }, }) if err != nil { - log.Error("Failed to submit workflow. Err:", err) + log.Error(ctx, "Failed to submit workflow. Err:", err) return "", fmt.Errorf("failed to submit workflow. Err: %s", err) } - log.Info("Successfully submitted workflow: ", workflowId) + log.Info(ctx, "Successfully submitted workflow: ", workflowId) return fmt.Sprintf("Rollback app Request '%v' is successfully submitted", taskId), nil } diff --git a/internal/usecase/auth.go b/internal/usecase/auth.go index a85c2c09..485a60a6 100644 --- a/internal/usecase/auth.go +++ b/internal/usecase/auth.go @@ -75,7 +75,7 @@ func (u *AuthUsecase) Login(ctx context.Context, accountId string, password stri } var accountToken *model.User - accountToken, err = u.kc.Login(accountId, password, organizationId) + accountToken, err = u.kc.Login(ctx, accountId, password, organizationId) if err != nil { apiErr, ok := err.(*gocloak.APIError) if ok { @@ -85,11 +85,6 @@ func (u *AuthUsecase) Login(ctx context.Context, accountId string, password stri } return model.User{}, httpErrors.NewInternalServerError(err, "", "") } - log.Errorf("err: %v", err) - if err != nil { - //TODO: implement not found handling - return model.User{}, err - } // Insert token user.Token = accountToken.Token @@ -103,7 +98,7 @@ func (u *AuthUsecase) Login(ctx context.Context, accountId string, password stri func (u *AuthUsecase) Logout(ctx context.Context, accessToken string, organizationName string) error { // [TODO] refresh token 을 추가하고, session timeout 을 줄이는 방향으로 고려할 것 - err := u.kc.Logout(accessToken, organizationName) + err := u.kc.Logout(ctx, accessToken, organizationName) if err != nil { return err } @@ -159,7 +154,7 @@ func (u *AuthUsecase) FindPassword(ctx context.Context, code string, accountId s } randomPassword := helper.GenerateRandomString(passwordLength) - originUser, err := u.kc.GetUser(organizationId, accountId) + originUser, err := u.kc.GetUser(ctx, organizationId, accountId) if err != nil { return httpErrors.NewInternalServerError(err, "", "") } @@ -170,7 +165,7 @@ func (u *AuthUsecase) FindPassword(ctx context.Context, code string, accountId s Temporary: gocloak.BoolP(false), }, } - if err = u.kc.UpdateUser(organizationId, originUser); err != nil { + if err = u.kc.UpdateUser(ctx, organizationId, originUser); err != nil { return httpErrors.NewInternalServerError(err, "", "") } @@ -178,15 +173,15 @@ func (u *AuthUsecase) FindPassword(ctx context.Context, code string, accountId s return httpErrors.NewInternalServerError(err, "", "") } - message, err := mail.MakeTemporaryPasswordMessage(email, organizationId, accountId, randomPassword) + message, err := mail.MakeTemporaryPasswordMessage(ctx, email, organizationId, accountId, randomPassword) if err != nil { - log.Errorf("mail.MakeVerityIdentityMessage error. %v", err) + log.Errorf(ctx, "mail.MakeVerityIdentityMessage error. %v", err) return httpErrors.NewInternalServerError(err, "", "") } mailer := mail.New(message) - if err := mailer.SendMail(); err != nil { + if err := mailer.SendMail(ctx); err != nil { return httpErrors.NewInternalServerError(err, "", "") } @@ -216,7 +211,7 @@ func (u *AuthUsecase) VerifyIdentity(ctx context.Context, accountId string, emai return httpErrors.NewInternalServerError(err, "", "") } - code, err := helper.GenerateEmailCode() + code, err := helper.GenerateEmailCode(ctx) if err != nil { return httpErrors.NewInternalServerError(err, "", "") } @@ -231,16 +226,16 @@ func (u *AuthUsecase) VerifyIdentity(ctx context.Context, accountId string, emai } } - message, err := mail.MakeVerityIdentityMessage(email, code) + message, err := mail.MakeVerityIdentityMessage(ctx, email, code) if err != nil { - log.Errorf("mail.MakeVerityIdentityMessage error. %v", err) + log.Errorf(ctx, "mail.MakeVerityIdentityMessage error. %v", err) return httpErrors.NewInternalServerError(err, "", "") } mailer := mail.New(message) - if err := mailer.SendMail(); err != nil { - log.Errorf("mailer.SendMail error. %v", err) + if err := mailer.SendMail(ctx); err != nil { + log.Errorf(ctx, "mailer.SendMail error. %v", err) return httpErrors.NewInternalServerError(err, "", "") } @@ -248,7 +243,7 @@ func (u *AuthUsecase) VerifyIdentity(ctx context.Context, accountId string, emai } func (u *AuthUsecase) SingleSignIn(ctx context.Context, organizationId, accountId, password string) ([]*http.Cookie, error) { - cookies, err := makingCookie(organizationId, accountId, password) + cookies, err := makingCookie(ctx, organizationId, accountId, password) if err != nil { return nil, err } @@ -319,7 +314,7 @@ func (u *AuthUsecase) VerifyToken(ctx context.Context, token string) (bool, erro return false, fmt.Errorf("organization is not found in token") } - isActive, err := u.kc.VerifyAccessToken(token, org) + isActive, err := u.kc.VerifyAccessToken(ctx, token, org) if err != nil { return false, err } @@ -364,7 +359,7 @@ func extractFormAction(htmlContent string) (string, error) { return f(doc), nil } -func makingCookie(organizationId, userName, password string) ([]*http.Cookie, error) { +func makingCookie(ctx context.Context, organizationId, userName, password string) ([]*http.Cookie, error) { stateCode, err := genStateString() if err != nil { return nil, err @@ -394,7 +389,7 @@ func makingCookie(organizationId, userName, password string) ([]*http.Cookie, er req.Header.Add("Accept", "text/html") resp, err := client.Do(req) if err != nil { - log.Errorf("Error while creating new request: %v", err) + log.Errorf(ctx, "Error while creating new request: %v", err) return nil, err } cookies := resp.Cookies() @@ -410,7 +405,7 @@ func makingCookie(organizationId, userName, password string) ([]*http.Cookie, er s, err := extractFormAction(htmlContent) if err != nil { - log.Errorf("Error while creating new request: %v", err) + log.Errorf(ctx, "Error while creating new request: %v", err) return nil, err } diff --git a/internal/usecase/cloud-account.go b/internal/usecase/cloud-account.go index 9763c2bd..5de5c4f2 100644 --- a/internal/usecase/cloud-account.go +++ b/internal/usecase/cloud-account.go @@ -91,6 +91,7 @@ func (u *CloudAccountUsecase) Create(ctx context.Context, dto model.CloudAccount } workflowId, err := u.argo.SumbitWorkflowFromWftpl( + ctx, "tks-create-aws-cloud-account", argowf.SubmitOptions{ Parameters: []string{ @@ -196,6 +197,7 @@ func (u *CloudAccountUsecase) Delete(ctx context.Context, dto model.CloudAccount } workflowId, err := u.argo.SumbitWorkflowFromWftpl( + ctx, "tks-delete-aws-cloud-account", argowf.SubmitOptions{ Parameters: []string{ @@ -249,7 +251,7 @@ func (u *CloudAccountUsecase) GetResourceQuota(ctx context.Context, cloudAccount return false, out, err } - awsAccessKeyId, awsSecretAccessKey, _ := kubernetes.GetAwsSecret() + awsAccessKeyId, awsSecretAccessKey, _ := kubernetes.GetAwsSecret(ctx) if err != nil || awsAccessKeyId == "" || awsSecretAccessKey == "" { log.Error(ctx, err) return false, out, httpErrors.NewInternalServerError(fmt.Errorf("Invalid aws secret."), "", "") @@ -368,7 +370,7 @@ func (u *CloudAccountUsecase) GetResourceQuota(ctx context.Context, cloudAccount if err != nil { return false, out, err } - log.DebugfWithContext(ctx, "%s %s %v", *res.Quota.QuotaName, *res.Quota.QuotaCode, *res.Quota.Value) + log.Debugf(ctx, "%s %s %v", *res.Quota.QuotaName, *res.Quota.QuotaCode, *res.Quota.Value) quotaValue := int(*res.Quota.Value) @@ -380,7 +382,7 @@ func (u *CloudAccountUsecase) GetResourceQuota(ctx context.Context, cloudAccount // Cluster 1 switch key { case "L-69A177A2": // NLB - log.InfofWithContext(ctx, "NLB : usage %d, quota %d", currentUsage.NLB, quotaValue) + log.Infof(ctx, "NLB : usage %d, quota %d", currentUsage.NLB, quotaValue) out.Quotas = append(out.Quotas, domain.ResourceQuotaAttr{ Type: "NLB", Usage: currentUsage.NLB, @@ -391,7 +393,7 @@ func (u *CloudAccountUsecase) GetResourceQuota(ctx context.Context, cloudAccount available = false } case "L-E9E9831D": // Classic - log.InfofWithContext(ctx, "CLB : usage %d, quota %d", currentUsage.CLB, quotaValue) + log.Infof(ctx, "CLB : usage %d, quota %d", currentUsage.CLB, quotaValue) out.Quotas = append(out.Quotas, domain.ResourceQuotaAttr{ Type: "CLB", Usage: currentUsage.CLB, @@ -402,7 +404,7 @@ func (u *CloudAccountUsecase) GetResourceQuota(ctx context.Context, cloudAccount available = false } case "L-A4707A72": // IGW - log.InfofWithContext(ctx, "IGW : usage %d, quota %d", currentUsage.IGW, quotaValue) + log.Infof(ctx, "IGW : usage %d, quota %d", currentUsage.IGW, quotaValue) out.Quotas = append(out.Quotas, domain.ResourceQuotaAttr{ Type: "IGW", Usage: currentUsage.IGW, @@ -413,7 +415,7 @@ func (u *CloudAccountUsecase) GetResourceQuota(ctx context.Context, cloudAccount available = false } case "L-1194D53C": // Cluster - log.InfofWithContext(ctx, "Cluster : usage %d, quota %d", currentUsage.Cluster, quotaValue) + log.Infof(ctx, "Cluster : usage %d, quota %d", currentUsage.Cluster, quotaValue) out.Quotas = append(out.Quotas, domain.ResourceQuotaAttr{ Type: "EKS", Usage: currentUsage.Cluster, @@ -424,7 +426,7 @@ func (u *CloudAccountUsecase) GetResourceQuota(ctx context.Context, cloudAccount available = false } case "L-0263D0A3": // Elastic IP - log.InfofWithContext(ctx, "Elastic IP : usage %d, quota %d", currentUsage.EIP, quotaValue) + log.Infof(ctx, "Elastic IP : usage %d, quota %d", currentUsage.EIP, quotaValue) out.Quotas = append(out.Quotas, domain.ResourceQuotaAttr{ Type: "EIP", Usage: currentUsage.EIP, @@ -447,7 +449,7 @@ func (u *CloudAccountUsecase) getClusterCnt(ctx context.Context, cloudAccountId clusters, err := u.clusterRepo.FetchByCloudAccountId(ctx, cloudAccountId, nil) if err != nil { - log.Error("Failed to get clusters by cloudAccountId. err : ", err) + log.Error(ctx, "Failed to get clusters by cloudAccountId. err : ", err) return cnt } diff --git a/internal/usecase/cluster.go b/internal/usecase/cluster.go index 4fdb01b5..52fb3287 100644 --- a/internal/usecase/cluster.go +++ b/internal/usecase/cluster.go @@ -184,6 +184,7 @@ func (u *ClusterUsecase) Create(ctx context.Context, dto model.Cluster) (cluster } workflowId, err := u.argo.SumbitWorkflowFromWftpl( + ctx, "create-tks-usercluster", argowf.SubmitOptions{ Parameters: []string{ @@ -249,6 +250,7 @@ func (u *ClusterUsecase) Import(ctx context.Context, dto model.Cluster) (cluster kubeconfigBase64 := base64.StdEncoding.EncodeToString([]byte(dto.Kubeconfig)) workflowId, err := u.argo.SumbitWorkflowFromWftpl( + ctx, "import-tks-usercluster", argowf.SubmitOptions{ Parameters: []string{ @@ -290,7 +292,7 @@ func (u *ClusterUsecase) Bootstrap(ctx context.Context, dto model.Cluster) (clus if err != nil { return "", httpErrors.NewBadRequestError(errors.Wrap(err, "Invalid stackTemplateId"), "", "") } - log.InfofWithContext(ctx, "%s %s", stackTemplate.CloudService, dto.CloudService) + log.Infof(ctx, "%s %s", stackTemplate.CloudService, dto.CloudService) if stackTemplate.CloudService != dto.CloudService { return "", httpErrors.NewBadRequestError(fmt.Errorf("Invalid cloudService for stackTemplate "), "", "") } @@ -303,7 +305,7 @@ func (u *ClusterUsecase) Bootstrap(ctx context.Context, dto model.Cluster) (clus } workflow := "create-byoh-bootstrapkubeconfig" - workflowId, err := u.argo.SumbitWorkflowFromWftpl(workflow, argowf.SubmitOptions{ + workflowId, err := u.argo.SumbitWorkflowFromWftpl(ctx, workflow, argowf.SubmitOptions{ Parameters: []string{ fmt.Sprintf("tks_api_url=%s", viper.GetString("external-address")), "cluster_id=" + clusterId.String(), @@ -345,6 +347,7 @@ func (u *ClusterUsecase) Install(ctx context.Context, clusterId domain.ClusterId } workflowId, err := u.argo.SumbitWorkflowFromWftpl( + ctx, "create-tks-usercluster", argowf.SubmitOptions{ Parameters: []string{ @@ -419,6 +422,7 @@ func (u *ClusterUsecase) Delete(ctx context.Context, clusterId domain.ClusterId) } workflowId, err := u.argo.SumbitWorkflowFromWftpl( + ctx, "tks-remove-usercluster", argowf.SubmitOptions{ Parameters: []string{ @@ -435,7 +439,7 @@ func (u *ClusterUsecase) Delete(ctx context.Context, clusterId domain.ClusterId) return errors.Wrap(err, "Failed to call argo workflow") } - log.DebugWithContext(ctx, "submited workflow name : ", workflowId) + log.Debug(ctx, "submited workflow name : ", workflowId) if err := u.repo.InitWorkflow(ctx, clusterId, workflowId, domain.ClusterStatus_DELETING); err != nil { return errors.Wrap(err, "Failed to initialize status") @@ -489,7 +493,7 @@ func (u *ClusterUsecase) CreateBootstrapKubeconfig(ctx context.Context, clusterI } workflow := "create-byoh-bootstrapkubeconfig" - workflowId, err := u.argo.SumbitWorkflowFromWftpl(workflow, argowf.SubmitOptions{ + workflowId, err := u.argo.SumbitWorkflowFromWftpl(ctx, workflow, argowf.SubmitOptions{ Parameters: []string{ fmt.Sprintf("tks_api_url=%s", viper.GetString("external-address")), "cluster_id=" + clusterId.String(), @@ -499,17 +503,17 @@ func (u *ClusterUsecase) CreateBootstrapKubeconfig(ctx context.Context, clusterI log.Error(ctx, err) return out, httpErrors.NewInternalServerError(err, "S_FAILED_TO_CALL_WORKFLOW", "") } - log.DebugWithContext(ctx, "Submitted workflow: ", workflowId) + log.Debug(ctx, "Submitted workflow: ", workflowId) // wait & get clusterId ( max 1min ) for i := 0; i < 60; i++ { time.Sleep(time.Second * 3) - workflow, err := u.argo.GetWorkflow("argo", workflowId) + workflow, err := u.argo.GetWorkflow(ctx, "argo", workflowId) if err != nil { return out, err } - log.DebugWithContext(ctx, "workflow ", workflow) + log.Debug(ctx, "workflow ", workflow) if workflow.Status.Phase == "Succeeded" { break @@ -532,7 +536,7 @@ func (u *ClusterUsecase) GetBootstrapKubeconfig(ctx context.Context, clusterId d if err != nil { return out, httpErrors.NewNotFoundError(err, "", "") } - client, err := kubernetes.GetClientAdminCluster() + client, err := kubernetes.GetClientAdminCluster(ctx) if err != nil { return out, err } @@ -553,7 +557,7 @@ func (u *ClusterUsecase) GetBootstrapKubeconfig(ctx context.Context, clusterId d return out, err } - log.DebugWithContext(ctx, helper.ModelToJson(kubeconfig.Status.BootstrapKubeconfigData)) + log.Debug(ctx, helper.ModelToJson(kubeconfig.Status.BootstrapKubeconfigData)) type BootstrapKubeconfigUser struct { Users []struct { @@ -580,7 +584,7 @@ func (u *ClusterUsecase) GetBootstrapKubeconfig(ctx context.Context, clusterId d return out, err } - log.Info(secrets.Data["expiration"][:]) + log.Info(ctx, secrets.Data["expiration"][:]) // 2023-10-17T11:05:33Z now := time.Now() @@ -610,7 +614,7 @@ func (u *ClusterUsecase) GetNodes(ctx context.Context, clusterId domain.ClusterI return out, httpErrors.NewBadRequestError(fmt.Errorf("Invalid cloud service"), "", "") } - client, err := kubernetes.GetClientAdminCluster() + client, err := kubernetes.GetClientAdminCluster(ctx) if err != nil { return out, err } @@ -815,9 +819,9 @@ func (u *ClusterUsecase) constructClusterConf(rawConf *model.ClusterConf) (clust var found bool = false for key, val := range azPerRegion { if strings.Contains(key, region) { - log.DebugWithContext(ctx,"Found region : ", key) + log.Debug(ctx,"Found region : ", key) maxAzForSelectedRegion = val - log.DebugWithContext(ctx,"Trimmed azNum var: ", maxAzForSelectedRegion) + log.Debug(ctx,"Trimmed azNum var: ", maxAzForSelectedRegion) found = true } } @@ -835,14 +839,14 @@ func (u *ClusterUsecase) constructClusterConf(rawConf *model.ClusterConf) (clust // Validate if machineReplicas is multiple of number of AZ replicas := int(rawConf.MachineReplicas) if replicas == 0 { - log.DebugWithContext(ctx,"No machineReplicas param. Using default values..") + log.Debug(ctx,"No machineReplicas param. Using default values..") } else { if remainder := replicas % numOfAz; remainder != 0 { log.Error(ctx,"Invalid machineReplicas: it should be multiple of numOfAz ", numOfAz) temp_err := fmt.Errorf("Invalid machineReplicas: it should be multiple of numOfAz %d", numOfAz) return nil, temp_err } else { - log.DebugWithContext(ctx,"Valid replicas and numOfAz. Caculating minSize & maxSize..") + log.Debug(ctx,"Valid replicas and numOfAz. Caculating minSize & maxSize..") minSizePerAz = int(replicas / numOfAz) maxSizePerAz = minSizePerAz * 5 @@ -851,8 +855,8 @@ func (u *ClusterUsecase) constructClusterConf(rawConf *model.ClusterConf) (clust fmt.Printf("maxSizePerAz exceeded maximum value %d, so adjusted to %d", MAX_SIZE_PER_AZ, MAX_SIZE_PER_AZ) maxSizePerAz = MAX_SIZE_PER_AZ } - log.DebugWithContext(ctx,"Derived minSizePerAz: ", minSizePerAz) - log.DebugWithContext(ctx,"Derived maxSizePerAz: ", maxSizePerAz) + log.Debug(ctx,"Derived minSizePerAz: ", minSizePerAz) + log.Debug(ctx,"Derived maxSizePerAz: ", maxSizePerAz) } } diff --git a/internal/usecase/dashboard.go b/internal/usecase/dashboard.go index 0e40c7d2..12d15d91 100644 --- a/internal/usecase/dashboard.go +++ b/internal/usecase/dashboard.go @@ -83,17 +83,17 @@ func (u *DashboardUsecase) GetStacks(ctx context.Context, organizationId string) log.Error(ctx, err) return out, httpErrors.NewInternalServerError(err, "D_INVALID_PRIMARY_STACK", "") } - address, port := helper.SplitAddress(thanosUrl) + address, port := helper.SplitAddress(ctx, thanosUrl) thanosClient, err := thanos.New(address, port, false, "") if err != nil { return out, errors.Wrap(err, "failed to create thanos client") } - stackMemoryDisk, err := thanosClient.Get("sum by (__name__, taco_cluster) ({__name__=~\"node_memory_MemFree_bytes|machine_memory_bytes|kubelet_volume_stats_used_bytes|kubelet_volume_stats_capacity_bytes\"})") + stackMemoryDisk, err := thanosClient.Get(ctx, "sum by (__name__, taco_cluster) ({__name__=~\"node_memory_MemFree_bytes|machine_memory_bytes|kubelet_volume_stats_used_bytes|kubelet_volume_stats_capacity_bytes\"})") if err != nil { return out, err } - stackCpu, err := thanosClient.Get("avg by (taco_cluster) (instance:node_cpu:ratio*100)") + stackCpu, err := thanosClient.Get(ctx, "avg by (taco_cluster) (instance:node_cpu:ratio*100)") if err != nil { return out, err } @@ -103,7 +103,7 @@ func (u *DashboardUsecase) GetStacks(ctx context.Context, organizationId string) if err != nil { return nil, err } - stack := reflectClusterToStack(cluster, appGroups) + stack := reflectClusterToStack(ctx, cluster, appGroups) dashboardStack := domain.DashboardStack{} if err := serializer.Map(stack, &dashboardStack); err != nil { log.Info(ctx, err) @@ -142,7 +142,7 @@ func (u *DashboardUsecase) GetResources(ctx context.Context, organizationId stri log.Error(ctx, err) return out, httpErrors.NewInternalServerError(err, "D_INVALID_PRIMARY_STACK", "") } - address, port := helper.SplitAddress(thanosUrl) + address, port := helper.SplitAddress(ctx, thanosUrl) thanosClient, err := thanos.New(address, port, false, "") if err != nil { return out, errors.Wrap(err, "failed to create thanos client") @@ -167,7 +167,7 @@ func (u *DashboardUsecase) GetResources(ctx context.Context, organizationId stri /* {"data":{"result":[{"metric":{"taco_cluster":"cmsai5k5l"},"value":[1683608185.65,"32"]},{"metric":{"taco_cluster":"crjfh12oc"},"value":[1683608185.65,"12"]}],"vector":""},"status":"success"} */ - result, err := thanosClient.Get("sum by (taco_cluster) (machine_cpu_cores)") + result, err := thanosClient.Get(ctx, "sum by (taco_cluster) (machine_cpu_cores)") if err != nil { return out, err } @@ -184,7 +184,7 @@ func (u *DashboardUsecase) GetResources(ctx context.Context, organizationId stri out.Cpu = fmt.Sprintf("%d 개", cpu) // Memory - result, err = thanosClient.Get("sum by (taco_cluster) (machine_memory_bytes)") + result, err = thanosClient.Get(ctx, "sum by (taco_cluster) (machine_memory_bytes)") if err != nil { return out, err } @@ -202,7 +202,7 @@ func (u *DashboardUsecase) GetResources(ctx context.Context, organizationId stri out.Memory = fmt.Sprintf("%v GiB", math.Round(memory)) // Storage - result, err = thanosClient.Get("sum by (taco_cluster) (kubelet_volume_stats_capacity_bytes)") + result, err = thanosClient.Get(ctx, "sum by (taco_cluster) (kubelet_volume_stats_capacity_bytes)") if err != nil { return out, err } @@ -225,10 +225,10 @@ func (u *DashboardUsecase) GetResources(ctx context.Context, organizationId stri func (u *DashboardUsecase) getChartFromPrometheus(ctx context.Context, organizationId string, chartType string, duration string, interval string, year string, month string) (res domain.DashboardChart, err error) { thanosUrl, err := u.getThanosUrl(ctx, organizationId) if err != nil { - log.Error(err) + log.Error(ctx, err) return res, httpErrors.NewInternalServerError(err, "D_INVALID_PRIMARY_STACK", "") } - address, port := helper.SplitAddress(thanosUrl) + address, port := helper.SplitAddress(ctx, thanosUrl) thanosClient, err := thanos.New(address, port, false, "") if err != nil { return res, errors.Wrap(err, "failed to create thanos client") @@ -296,7 +296,7 @@ func (u *DashboardUsecase) getChartFromPrometheus(ctx context.Context, organizat return res, err } - log.Info(organization.CreatedAt.Format("2006-01-02")) + log.Info(ctx, organization.CreatedAt.Format("2006-01-02")) podCounts := []domain.PodCount{} for day := rangeDate(startDate, endDate); ; { @@ -341,7 +341,7 @@ func (u *DashboardUsecase) getChartFromPrometheus(ctx context.Context, organizat return domain.DashboardChart{}, fmt.Errorf("No data") } - result, err := thanosClient.FetchRange(query, int(now.Unix())-durationSec, int(now.Unix()), intervalSec) + result, err := thanosClient.FetchRange(ctx, query, int(now.Unix())-durationSec, int(now.Unix()), intervalSec) if err != nil { return res, err } @@ -419,7 +419,7 @@ func (u *DashboardUsecase) getThanosUrl(ctx context.Context, organizationId stri return out, fmt.Errorf("Invalid primary clusterId") } - clientset_admin, err := kubernetes.GetClientAdminCluster() + clientset_admin, err := kubernetes.GetClientAdminCluster(ctx) if err != nil { return out, errors.Wrap(err, "Failed to get client set for user cluster") } @@ -427,9 +427,9 @@ func (u *DashboardUsecase) getThanosUrl(ctx context.Context, organizationId stri // tks-endpoint-secret 이 있다면 그 secret 내의 endpoint 를 사용한다. secrets, err := clientset_admin.CoreV1().Secrets(organization.PrimaryClusterId).Get(context.TODO(), "tks-endpoint-secret", metav1.GetOptions{}) if err != nil { - log.Info("cannot found tks-endpoint-secret. so use LoadBalancer...") + log.Info(ctx, "cannot found tks-endpoint-secret. so use LoadBalancer...") - clientset_user, err := kubernetes.GetClientFromClusterId(organization.PrimaryClusterId) + clientset_user, err := kubernetes.GetClientFromClusterId(ctx, organization.PrimaryClusterId) if err != nil { return out, errors.Wrap(err, "Failed to get client set for user cluster") } @@ -456,7 +456,7 @@ func (u *DashboardUsecase) getThanosUrl(ctx context.Context, organizationId stri } } else { out = "http://" + string(secrets.Data["thanos"]) - log.Info("thanosUrl : ", out) + log.Info(ctx, "thanosUrl : ", out) u.cache.Set(prefix+organizationId, out, gcache.DefaultExpiration) return out, nil } diff --git a/internal/usecase/organization.go b/internal/usecase/organization.go index 72d30e3c..7fe6ea4f 100644 --- a/internal/usecase/organization.go +++ b/internal/usecase/organization.go @@ -57,7 +57,7 @@ func (u *OrganizationUsecase) Create(ctx context.Context, in *model.Organization in.CreatorId = &userId // Create realm in keycloak - if organizationId, err = u.kc.CreateRealm(helper.GenerateOrganizationId()); err != nil { + if organizationId, err = u.kc.CreateRealm(ctx, helper.GenerateOrganizationId()); err != nil { return "", err } in.ID = organizationId @@ -69,6 +69,7 @@ func (u *OrganizationUsecase) Create(ctx context.Context, in *model.Organization } workflowId, err := u.argo.SumbitWorkflowFromWftpl( + ctx, "tks-create-contract-repo", argowf.SubmitOptions{ Parameters: []string{ @@ -119,7 +120,7 @@ func (u *OrganizationUsecase) Delete(ctx context.Context, organizationId string, } // Delete realm in keycloak - if err := u.kc.DeleteRealm(organizationId); err != nil { + if err := u.kc.DeleteRealm(ctx, organizationId); err != nil { return err } diff --git a/internal/usecase/project.go b/internal/usecase/project.go index b3d0e1a3..2fa7d364 100644 --- a/internal/usecase/project.go +++ b/internal/usecase/project.go @@ -199,7 +199,7 @@ func (u *ProjectUsecase) UpdateProject(ctx context.Context, p *model.Project, ne if err != nil { return err } - log.Infof("Added project member: %s", res) + log.Infof(ctx, "Added project member: %s", res) } else { pm.ProjectUserId = pu.ID pm.ProjectRoleId = projectRoleId @@ -498,7 +498,7 @@ func (u *ProjectUsecase) MayRemoveRequiredSetupForCluster(ctx context.Context, o return nil } func (u *ProjectUsecase) createK8SInitialResource(ctx context.Context, organizationId string, projectId string, stackId string) error { - kubeconfig, err := kubernetes.GetKubeConfig(stackId) + kubeconfig, err := kubernetes.GetKubeConfig(ctx, stackId) if err != nil { log.Error(ctx, err) return errors.Wrap(err, "Failed to create project namespace.") @@ -510,19 +510,19 @@ func (u *ProjectUsecase) createK8SInitialResource(ctx context.Context, organizat return errors.Wrap(err, "Failed to create project namespace.") } - err = kubernetes.EnsureClusterRole(kubeconfig, pr.Name) + err = kubernetes.EnsureClusterRole(ctx, kubeconfig, pr.Name) if err != nil { log.Error(ctx, err) return errors.Wrap(err, "Failed to create project namespace.") } - err = kubernetes.EnsureCommonClusterRole(kubeconfig, pr.Name) + err = kubernetes.EnsureCommonClusterRole(ctx, kubeconfig, pr.Name) if err != nil { log.Error(ctx, err) return errors.Wrap(err, "Failed to create project namespace.") } - err = kubernetes.EnsureCommonClusterRoleBinding(kubeconfig, pr.Name) + err = kubernetes.EnsureCommonClusterRoleBinding(ctx, kubeconfig, pr.Name) if err != nil { log.Error(ctx, err) return errors.Wrap(err, "Failed to create project namespace.") @@ -531,7 +531,7 @@ func (u *ProjectUsecase) createK8SInitialResource(ctx context.Context, organizat return nil } func (u *ProjectUsecase) deleteK8SInitialResource(ctx context.Context, organizationId string, projectId string, stackId string) error { - kubeconfig, err := kubernetes.GetKubeConfig(stackId) + kubeconfig, err := kubernetes.GetKubeConfig(ctx, stackId) if err != nil { log.Error(ctx, err) return errors.Wrap(err, "Failed to create project namespace.") @@ -543,19 +543,19 @@ func (u *ProjectUsecase) deleteK8SInitialResource(ctx context.Context, organizat return errors.Wrap(err, "Failed to create project namespace.") } - err = kubernetes.RemoveClusterRole(kubeconfig, pr.Name) + err = kubernetes.RemoveClusterRole(ctx, kubeconfig, pr.Name) if err != nil { log.Error(ctx, err) return errors.Wrap(err, "Failed to create project namespace.") } - err = kubernetes.RemoveCommonClusterRole(kubeconfig, pr.Name) + err = kubernetes.RemoveCommonClusterRole(ctx, kubeconfig, pr.Name) if err != nil { log.Error(ctx, err) return errors.Wrap(err, "Failed to create project namespace.") } - err = kubernetes.RemoveCommonClusterRoleBinding(kubeconfig, pr.Name) + err = kubernetes.RemoveCommonClusterRoleBinding(ctx, kubeconfig, pr.Name) if err != nil { log.Error(ctx, err) return errors.Wrap(err, "Failed to create project namespace.") @@ -566,7 +566,7 @@ func (u *ProjectUsecase) deleteK8SInitialResource(ctx context.Context, organizat func (u *ProjectUsecase) createKeycloakClientRoles(ctx context.Context, organizationId string, projectId string, stackId string) error { // create Roles in keycloak for _, role := range []string{strconv.Itoa(ProjectLeader), strconv.Itoa(ProjectMember), strconv.Itoa(ProjectViewer)} { - err := u.kc.EnsureClientRoleWithClientName(organizationId, stackId+"-k8s-api", role+"@"+projectId) + err := u.kc.EnsureClientRoleWithClientName(ctx, organizationId, stackId+"-k8s-api", role+"@"+projectId) if err != nil { log.Error(ctx, err) return errors.Wrap(err, "Failed to create project namespace.") @@ -579,7 +579,7 @@ func (u *ProjectUsecase) deleteKeycloakClientRoles(ctx context.Context, organiza // delete Roles in keycloak for _, role := range []string{strconv.Itoa(ProjectLeader), strconv.Itoa(ProjectMember), strconv.Itoa(ProjectViewer)} { - err := u.kc.DeleteClientRoleWithClientName(organizationId, stackId+"-k8s-api", role+"@"+projectId) + err := u.kc.DeleteClientRoleWithClientName(ctx, organizationId, stackId+"-k8s-api", role+"@"+projectId) if err != nil { log.Error(ctx, err) return errors.Wrap(err, "Failed to create project namespace.") @@ -588,7 +588,7 @@ func (u *ProjectUsecase) deleteKeycloakClientRoles(ctx context.Context, organiza return nil } func (u *ProjectUsecase) CreateK8SNSRoleBinding(ctx context.Context, organizationId string, projectId string, stackId string, namespace string) error { - kubeconfig, err := kubernetes.GetKubeConfig(stackId) + kubeconfig, err := kubernetes.GetKubeConfig(ctx, stackId) if err != nil { log.Error(ctx, err) return errors.Wrap(err, "Failed to create project namespace.") @@ -600,7 +600,7 @@ func (u *ProjectUsecase) CreateK8SNSRoleBinding(ctx context.Context, organizatio return errors.Wrap(err, "Failed to create project namespace.") } - err = kubernetes.EnsureRoleBinding(kubeconfig, pr.Name, namespace) + err = kubernetes.EnsureRoleBinding(ctx, kubeconfig, pr.Name, namespace) if err != nil { log.Error(ctx, err) return errors.Wrap(err, "Failed to create project namespace.") @@ -624,7 +624,7 @@ func (u *ProjectUsecase) AssignKeycloakClientRoleToMember(ctx context.Context, o } func (u *ProjectUsecase) assignEachKeycloakClientRoleToMember(ctx context.Context, organizationId string, projectId string, stackId string, userId string, roleName string) error { - err := u.kc.AssignClientRoleToUser(organizationId, userId, stackId+"-k8s-api", roleName+"@"+projectId) + err := u.kc.AssignClientRoleToUser(ctx, organizationId, userId, stackId+"-k8s-api", roleName+"@"+projectId) if err != nil { log.Error(ctx, err) return errors.Wrap(err, "Failed to create project namespace.") @@ -643,7 +643,7 @@ func (u *ProjectUsecase) UnassignKeycloakClientRoleToMember(ctx context.Context, } func (u *ProjectUsecase) unassignKeycloakClientRoleToMember(ctx context.Context, organizationId string, projectId string, stackId string, userId string, roleName string) error { - err := u.kc.UnassignClientRoleToUser(organizationId, userId, stackId+"-k8s-api", roleName+"@"+projectId) + err := u.kc.UnassignClientRoleToUser(ctx, organizationId, userId, stackId+"-k8s-api", roleName+"@"+projectId) if err != nil { log.Error(ctx, err) return errors.Wrap(err, "Failed to create project namespace.") @@ -682,7 +682,7 @@ func (u *ProjectUsecase) GetProjectKubeconfig(ctx context.Context, organizationI kubeconfigs := make([]string, 0) for _, pn := range projectNamespaces { - kubeconfig, err := kubernetes.GetKubeConfig(pn.StackId) + kubeconfig, err := kubernetes.GetKubeConfig(ctx, pn.StackId) if err != nil { log.Error(ctx, err) return "", errors.Wrap(err, "Failed to retrieve kubeconfig.") @@ -714,7 +714,7 @@ func (u *ProjectUsecase) GetK8sResources(ctx context.Context, organizationId str return out, errors.Wrap(err, fmt.Sprintf("Failed to get cluster : stackId %s", stackId)) } - clientset_user, err := kubernetes.GetClientFromClusterId(stackId.String()) + clientset_user, err := kubernetes.GetClientFromClusterId(ctx, stackId.String()) if err != nil { return out, errors.Wrap(err, fmt.Sprintf("Failed to get clientset : stackId %s", stackId)) } diff --git a/internal/usecase/stack.go b/internal/usecase/stack.go index e27bfd56..f49dc70c 100644 --- a/internal/usecase/stack.go +++ b/internal/usecase/stack.go @@ -86,7 +86,7 @@ func (u *StackUsecase) Create(ctx context.Context, dto model.Stack) (stackId dom if len(clusters) == 0 { isPrimary = true } - log.DebugWithContext(ctx, "isPrimary ", isPrimary) + log.Debug(ctx, "isPrimary ", isPrimary) if dto.CloudService == domain.CloudService_BYOH { if dto.ClusterEndpoint == "" { @@ -122,7 +122,7 @@ func (u *StackUsecase) Create(ctx context.Context, dto model.Stack) (stackId dom } workflow := "tks-stack-create" - workflowId, err := u.argo.SumbitWorkflowFromWftpl(workflow, argowf.SubmitOptions{ + workflowId, err := u.argo.SumbitWorkflowFromWftpl(ctx, workflow, argowf.SubmitOptions{ Parameters: []string{ fmt.Sprintf("tks_api_url=%s", viper.GetString("external-address")), "cluster_name=" + dto.Name, @@ -141,18 +141,18 @@ func (u *StackUsecase) Create(ctx context.Context, dto model.Stack) (stackId dom log.Error(ctx, err) return "", httpErrors.NewInternalServerError(err, "S_FAILED_TO_CALL_WORKFLOW", "") } - log.DebugWithContext(ctx, "Submitted workflow: ", workflowId) + log.Debug(ctx, "Submitted workflow: ", workflowId) // wait & get clusterId ( max 1min ) dto.ID = domain.StackId("") for i := 0; i < 60; i++ { time.Sleep(time.Second * 5) - workflow, err := u.argo.GetWorkflow("argo", workflowId) + workflow, err := u.argo.GetWorkflow(ctx, "argo", workflowId) if err != nil { return "", err } - log.DebugWithContext(ctx, "workflow ", workflow) + log.Debug(ctx, "workflow ", workflow) if workflow.Status.Phase != "" && workflow.Status.Phase != "Running" { return "", fmt.Errorf("Invalid workflow status [%s]", workflow.Status.Phase) } @@ -189,7 +189,7 @@ func (u *StackUsecase) Install(ctx context.Context, stackId domain.StackId) (err if len(clusters) == 0 { isPrimary = true } - log.DebugWithContext(ctx, "isPrimary ", isPrimary) + log.Debug(ctx, "isPrimary ", isPrimary) if cluster.CloudService != domain.CloudService_BYOH { return httpErrors.NewBadRequestError(fmt.Errorf("Invalid cloud service"), "S_INVALID_CLOUD_SERVICE", "") @@ -202,7 +202,7 @@ func (u *StackUsecase) Install(ctx context.Context, stackId domain.StackId) (err } workflow := "tks-stack-install" - workflowId, err := u.argo.SumbitWorkflowFromWftpl(workflow, argowf.SubmitOptions{ + workflowId, err := u.argo.SumbitWorkflowFromWftpl(ctx, workflow, argowf.SubmitOptions{ Parameters: []string{ fmt.Sprintf("tks_api_url=%s", viper.GetString("external-address")), "cluster_id=" + cluster.ID.String(), @@ -217,7 +217,7 @@ func (u *StackUsecase) Install(ctx context.Context, stackId domain.StackId) (err log.Error(ctx, err) return httpErrors.NewInternalServerError(err, "S_FAILED_TO_CALL_WORKFLOW", "") } - log.DebugWithContext(ctx, "Submitted workflow: ", workflowId) + log.Debug(ctx, "Submitted workflow: ", workflowId) return nil } @@ -242,7 +242,7 @@ func (u *StackUsecase) Get(ctx context.Context, stackId domain.StackId) (out mod } stackResources, _ := u.dashbordUsecase.GetStacks(ctx, cluster.OrganizationId) - out = reflectClusterToStack(cluster, appGroups) + out = reflectClusterToStack(ctx, cluster, appGroups) if organization.PrimaryClusterId == cluster.ID.String() { out.PrimaryCluster = true @@ -251,7 +251,7 @@ func (u *StackUsecase) Get(ctx context.Context, stackId domain.StackId) (out mod for _, resource := range stackResources { if resource.ID == domain.StackId(cluster.ID) { if err := serializer.Map(resource, &out.Resource); err != nil { - log.Error(err) + log.Error(ctx, err) } } } @@ -290,7 +290,7 @@ func (u *StackUsecase) GetByName(ctx context.Context, organizationId string, nam return out, err } - out = reflectClusterToStack(cluster, appGroups) + out = reflectClusterToStack(ctx, cluster, appGroups) return } @@ -318,7 +318,7 @@ func (u *StackUsecase) Fetch(ctx context.Context, organizationId string, pg *pag return nil, err } - outStack := reflectClusterToStack(cluster, appGroups) + outStack := reflectClusterToStack(ctx, cluster, appGroups) if organization.PrimaryClusterId == cluster.ID.String() { outStack.PrimaryCluster = true } @@ -338,7 +338,7 @@ func (u *StackUsecase) Fetch(ctx context.Context, organizationId string, pg *pag for _, resource := range stackResources { if resource.ID == domain.StackId(cluster.ID) { if err := serializer.Map(resource, &outStack.Resource); err != nil { - log.Error(err) + log.Error(ctx, err) } } } @@ -437,7 +437,7 @@ func (u *StackUsecase) Delete(ctx context.Context, dto model.Stack) (err error) // [TODO] BYOH 삭제는 어떻게 처리하는게 좋은가? workflow := "tks-stack-delete" - workflowId, err := u.argo.SumbitWorkflowFromWftpl(workflow, argowf.SubmitOptions{ + workflowId, err := u.argo.SumbitWorkflowFromWftpl(ctx, workflow, argowf.SubmitOptions{ Parameters: []string{ fmt.Sprintf("tks_api_url=%s", viper.GetString("external-address")), "organization_id=" + dto.OrganizationId, @@ -450,7 +450,7 @@ func (u *StackUsecase) Delete(ctx context.Context, dto model.Stack) (err error) log.Error(ctx, err) return err } - log.DebugWithContext(ctx, "Submitted workflow: ", workflowId) + log.Debug(ctx, "Submitted workflow: ", workflowId) // Remove Cluster & AppGroup status description if err := u.appGroupRepo.InitWorkflowDescription(ctx, cluster.ID); err != nil { @@ -463,7 +463,7 @@ func (u *StackUsecase) Delete(ctx context.Context, dto model.Stack) (err error) // wait & get clusterId ( max 1min ) for i := 0; i < 60; i++ { time.Sleep(time.Second * 2) - workflow, err := u.argo.GetWorkflow("argo", workflowId) + workflow, err := u.argo.GetWorkflow(ctx, "argo", workflowId) if err != nil { return err } @@ -482,7 +482,7 @@ func (u *StackUsecase) Delete(ctx context.Context, dto model.Stack) (err error) } func (u *StackUsecase) GetKubeConfig(ctx context.Context, stackId domain.StackId) (kubeConfig string, err error) { - kubeconfig, err := kubernetes.GetKubeConfig(stackId.String()) + kubeconfig, err := kubernetes.GetKubeConfig(ctx, stackId.String()) //kubeconfig, err := kubernetes.GetKubeConfig("cmsai5k5l") if err != nil { return "", err @@ -618,9 +618,9 @@ func (u *StackUsecase) DeleteFavorite(ctx context.Context, stackId domain.StackI return nil } -func reflectClusterToStack(cluster model.Cluster, appGroups []model.AppGroup) (out model.Stack) { +func reflectClusterToStack(ctx context.Context, cluster model.Cluster, appGroups []model.AppGroup) (out model.Stack) { if err := serializer.Map(cluster, &out); err != nil { - log.Error(err) + log.Error(ctx, err) } status, statusDesc := getStackStatus(cluster, appGroups) diff --git a/internal/usecase/user.go b/internal/usecase/user.go index 92cb6fe4..5730e87d 100644 --- a/internal/usecase/user.go +++ b/internal/usecase/user.go @@ -64,7 +64,7 @@ func (u *UserUsecase) RenewalPasswordExpiredTime(ctx context.Context, userId uui err = u.userRepository.UpdatePasswordAt(ctx, userId, user.Organization.ID, false) if err != nil { - log.ErrorfWithContext(ctx, "failed to update password expired time: %v", err) + log.Errorf(ctx, "failed to update password expired time: %v", err) return httpErrors.NewInternalServerError(err, "", "") } @@ -89,7 +89,7 @@ func (u *UserUsecase) ResetPassword(ctx context.Context, userId uuid.UUID) error return httpErrors.NewBadRequestError(fmt.Errorf("user not found"), "U_NO_USER", "") } } - userInKeycloak, err := u.kc.GetUser(user.Organization.ID, user.AccountId) + userInKeycloak, err := u.kc.GetUser(ctx, user.Organization.ID, user.AccountId) if err != nil { if _, status := httpErrors.ErrorResponse(err); status == http.StatusNotFound { return httpErrors.NewBadRequestError(fmt.Errorf("user not found"), "U_NO_USER", "") @@ -105,7 +105,7 @@ func (u *UserUsecase) ResetPassword(ctx context.Context, userId uuid.UUID) error Temporary: gocloak.BoolP(false), }, } - if err = u.kc.UpdateUser(user.Organization.ID, userInKeycloak); err != nil { + if err = u.kc.UpdateUser(ctx, user.Organization.ID, userInKeycloak); err != nil { return httpErrors.NewInternalServerError(err, "", "") } @@ -113,15 +113,15 @@ func (u *UserUsecase) ResetPassword(ctx context.Context, userId uuid.UUID) error return httpErrors.NewInternalServerError(err, "", "") } - message, err := mail.MakeTemporaryPasswordMessage(user.Email, user.Organization.ID, user.AccountId, randomPassword) + message, err := mail.MakeTemporaryPasswordMessage(ctx, user.Email, user.Organization.ID, user.AccountId, randomPassword) if err != nil { - log.Errorf("mail.MakeVerityIdentityMessage error. %v", err) + log.Errorf(ctx, "mail.MakeVerityIdentityMessage error. %v", err) return httpErrors.NewInternalServerError(err, "", "") } mailer := mail.New(message) - if err := mailer.SendMail(); err != nil { + if err := mailer.SendMail(ctx); err != nil { return httpErrors.NewInternalServerError(err, "", "") } @@ -148,7 +148,7 @@ func (u *UserUsecase) ValidateAccount(ctx context.Context, userId uuid.UUID, pas if err != nil { return httpErrors.NewBadRequestError(fmt.Errorf("user not found"), "U_NO_USER", "") } - _, err = u.kc.Login(user.AccountId, password, organizationId) + _, err = u.kc.Login(ctx, user.AccountId, password, organizationId) if err != nil { return httpErrors.NewBadRequestError(fmt.Errorf("invalid password"), "A_INVALID_PASSWORD", "") } @@ -156,7 +156,7 @@ func (u *UserUsecase) ValidateAccount(ctx context.Context, userId uuid.UUID, pas } func (u *UserUsecase) ValidateAccountByAccountId(ctx context.Context, accountId string, password string, organizationId string) error { - _, err := u.kc.Login(organizationId, accountId, password) + _, err := u.kc.Login(ctx, organizationId, accountId, password) return err } @@ -173,12 +173,12 @@ func (u *UserUsecase) DeleteAll(ctx context.Context, organizationId string) erro } func (u *UserUsecase) DeleteAdmin(ctx context.Context, organizationId string) error { - user, err := u.kc.GetUser(organizationId, "admin") + user, err := u.kc.GetUser(ctx, organizationId, "admin") if err != nil { return errors.Wrap(err, "get user failed") } - err = u.kc.DeleteUser(organizationId, "admin") + err = u.kc.DeleteUser(ctx, organizationId, "admin") if err != nil { return errors.Wrap(err, "delete user failed") } @@ -223,12 +223,12 @@ func (u *UserUsecase) CreateAdmin(ctx context.Context, organizationId string, ac if err != nil { return nil, err } - message, err := mail.MakeGeneratingOrganizationMessage(organizationId, organizationInfo.Name, user.Email, user.AccountId, randomPassword) + message, err := mail.MakeGeneratingOrganizationMessage(ctx, organizationId, organizationInfo.Name, user.Email, user.AccountId, randomPassword) if err != nil { return nil, httpErrors.NewInternalServerError(err, "", "") } mailer := mail.New(message) - if err := mailer.SendMail(); err != nil { + if err := mailer.SendMail(ctx); err != nil { return nil, httpErrors.NewInternalServerError(err, "", "") } @@ -241,14 +241,14 @@ func (u *UserUsecase) SendEmailForTemporaryPassword(ctx context.Context, account return err } - message, err := mail.MakeTemporaryPasswordMessage(user.Email, organizationId, accountId, password) + message, err := mail.MakeTemporaryPasswordMessage(ctx, user.Email, organizationId, accountId, password) if err != nil { return err } mailer := mail.New(message) - if err := mailer.SendMail(); err != nil { + if err := mailer.SendMail(ctx); err != nil { return err } @@ -261,10 +261,10 @@ func (u *UserUsecase) UpdatePasswordByAccountId(ctx context.Context, accountId s if originPassword == newPassword { return httpErrors.NewBadRequestError(fmt.Errorf("new password is same with origin password"), "A_SAME_OLD_PASSWORD", "") } - if _, err := u.kc.Login(accountId, originPassword, organizationId); err != nil { + if _, err := u.kc.Login(ctx, accountId, originPassword, organizationId); err != nil { return httpErrors.NewBadRequestError(fmt.Errorf("invalid origin password"), "A_INVALID_PASSWORD", "") } - originUser, err := u.kc.GetUser(organizationId, accountId) + originUser, err := u.kc.GetUser(ctx, organizationId, accountId) if err != nil { return err } @@ -276,7 +276,7 @@ func (u *UserUsecase) UpdatePasswordByAccountId(ctx context.Context, accountId s }, } - err = u.kc.UpdateUser(organizationId, originUser) + err = u.kc.UpdateUser(ctx, organizationId, originUser) if err != nil { return errors.Wrap(err, "updating user in keycloak failed") } @@ -358,7 +358,7 @@ func (u *UserUsecase) Update(ctx context.Context, userId uuid.UUID, user *model. 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) + originUser, err := u.kc.GetUser(ctx, user.Organization.ID, accountId) if err != nil { return nil, err } @@ -366,7 +366,7 @@ func (u *UserUsecase) UpdateByAccountId(ctx context.Context, accountId string, u if (originUser.Email == nil || *originUser.Email != user.Email) || (originUser.FirstName == nil || *originUser.FirstName != user.Name) { originUser.Email = gocloak.StringP(user.Email) originUser.FirstName = gocloak.StringP(user.Name) - err = u.kc.UpdateUser(user.Organization.ID, originUser) + err = u.kc.UpdateUser(ctx, user.Organization.ID, originUser) if err != nil { return nil, err } @@ -411,7 +411,7 @@ func (u *UserUsecase) Delete(ctx context.Context, userId uuid.UUID, organization } // Delete user in keycloak - err = u.kc.DeleteUser(organizationId, user.AccountId) + err = u.kc.DeleteUser(ctx, organizationId, user.AccountId) if err != nil { return err } @@ -430,7 +430,7 @@ func (u *UserUsecase) DeleteByAccountId(ctx context.Context, accountId string, o } // Delete user in keycloak - err = u.kc.DeleteUser(organizationId, accountId) + err = u.kc.DeleteUser(ctx, organizationId, accountId) if err != nil { return err } @@ -441,7 +441,7 @@ func (u *UserUsecase) DeleteByAccountId(ctx context.Context, accountId string, o 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{ + userUuidStr, err := u.kc.CreateUser(ctx, user.Organization.ID, &gocloak.User{ Username: gocloak.StringP(user.AccountId), Credentials: &[]gocloak.CredentialRepresentation{ { @@ -502,12 +502,12 @@ func (u *UserUsecase) UpdateByAccountIdByAdmin(ctx context.Context, accountId st if newUser.Role.Name != user.Role.Name { originGroupName := fmt.Sprintf("%s@%s", user.Role.Name, newUser.Organization.ID) newGroupName := fmt.Sprintf("%s@%s", newUser.Role.Name, newUser.Organization.ID) - if err := u.kc.LeaveGroup(newUser.Organization.ID, user.ID.String(), originGroupName); err != nil { - log.ErrorfWithContext(ctx, "leave group in keycloak failed: %v", err) + if err := u.kc.LeaveGroup(ctx, newUser.Organization.ID, user.ID.String(), originGroupName); err != nil { + log.Errorf(ctx, "leave group in keycloak failed: %v", err) return nil, httpErrors.NewInternalServerError(err, "", "") } - if err := u.kc.JoinGroup(newUser.Organization.ID, user.ID.String(), newGroupName); err != nil { - log.ErrorfWithContext(ctx, "join group in keycloak failed: %v", err) + if err := u.kc.JoinGroup(ctx, newUser.Organization.ID, user.ID.String(), newGroupName); err != nil { + log.Errorf(ctx, "join group in keycloak failed: %v", err) return nil, httpErrors.NewInternalServerError(err, "", "") } } diff --git a/pkg/argo-client/client-mock.go b/pkg/argo-client/client-mock.go index d3a22de5..47891107 100644 --- a/pkg/argo-client/client-mock.go +++ b/pkg/argo-client/client-mock.go @@ -1,6 +1,7 @@ package argowf import ( + "context" "net/http" "time" ) @@ -23,22 +24,22 @@ func NewMock() (ArgoClient, error) { }, nil } -func (c *ArgoClientMockImpl) GetWorkflowTemplates(namespace string) (*GetWorkflowTemplatesResponse, error) { +func (c *ArgoClientMockImpl) GetWorkflowTemplates(ctx context.Context, namespace string) (*GetWorkflowTemplatesResponse, error) { return nil, nil } -func (c *ArgoClientMockImpl) GetWorkflow(namespace string, workflowName string) (*Workflow, error) { +func (c *ArgoClientMockImpl) GetWorkflow(ctx context.Context, namespace string, workflowName string) (*Workflow, error) { return nil, nil } -func (c *ArgoClientMockImpl) GetWorkflowLog(namespace string, container string, workflowName string) (string, error) { +func (c *ArgoClientMockImpl) GetWorkflowLog(ctx context.Context, namespace string, container string, workflowName string) (string, error) { return "", nil } -func (c *ArgoClientMockImpl) GetWorkflows(namespace string) (*GetWorkflowsResponse, error) { +func (c *ArgoClientMockImpl) GetWorkflows(ctx context.Context, namespace string) (*GetWorkflowsResponse, error) { return nil, nil } -func (c *ArgoClientMockImpl) SumbitWorkflowFromWftpl(wftplName string, opts SubmitOptions) (string, error) { +func (c *ArgoClientMockImpl) SumbitWorkflowFromWftpl(ctx context.Context, wftplName string, opts SubmitOptions) (string, error) { return "", nil } diff --git a/pkg/argo-client/client.go b/pkg/argo-client/client.go index b100b5a4..3b10eb50 100644 --- a/pkg/argo-client/client.go +++ b/pkg/argo-client/client.go @@ -2,6 +2,7 @@ package argowf import ( "bytes" + "context" "encoding/json" "fmt" "io" @@ -12,11 +13,11 @@ import ( ) type ArgoClient interface { - GetWorkflowTemplates(namespace string) (*GetWorkflowTemplatesResponse, error) - GetWorkflow(namespace string, workflowName string) (*Workflow, error) - GetWorkflowLog(namespace string, container string, workflowName string) (logs string, err error) - GetWorkflows(namespace string) (*GetWorkflowsResponse, error) - SumbitWorkflowFromWftpl(wftplName string, opts SubmitOptions) (string, error) + GetWorkflowTemplates(ctx context.Context, namespace string) (*GetWorkflowTemplatesResponse, error) + GetWorkflow(ctx context.Context, namespace string, workflowName string) (*Workflow, error) + GetWorkflowLog(ctx context.Context, namespace string, container string, workflowName string) (logs string, err error) + GetWorkflows(ctx context.Context, namespace string) (*GetWorkflowsResponse, error) + SumbitWorkflowFromWftpl(ctx context.Context, wftplName string, opts SubmitOptions) (string, error) } type ArgoClientImpl struct { @@ -46,7 +47,7 @@ func New(host string, port int, ssl bool, token string) (ArgoClient, error) { }, nil } -func (c *ArgoClientImpl) GetWorkflowTemplates(namespace string) (*GetWorkflowTemplatesResponse, error) { +func (c *ArgoClientImpl) GetWorkflowTemplates(ctx context.Context, namespace string) (*GetWorkflowTemplatesResponse, error) { res, err := c.client.Get(fmt.Sprintf("%s/api/v1/workflow-templates/%s", c.url, namespace)) if err != nil { return nil, err @@ -60,7 +61,7 @@ func (c *ArgoClientImpl) GetWorkflowTemplates(namespace string) (*GetWorkflowTem defer func() { if err := res.Body.Close(); err != nil { - log.Error("error closing http body") + log.Error(ctx, "error closing http body") } }() @@ -71,13 +72,13 @@ func (c *ArgoClientImpl) GetWorkflowTemplates(namespace string) (*GetWorkflowTem wftplRes := GetWorkflowTemplatesResponse{} if err := json.Unmarshal(body, &wftplRes); err != nil { - log.Error("an error was unexpected while parsing response from api /workflow template.") + log.Error(ctx, "an error was unexpected while parsing response from api /workflow template.") return nil, err } return &wftplRes, nil } -func (c *ArgoClientImpl) GetWorkflow(namespace string, workflowName string) (*Workflow, error) { +func (c *ArgoClientImpl) GetWorkflow(ctx context.Context, namespace string, workflowName string) (*Workflow, error) { res, err := c.client.Get(fmt.Sprintf("%s/api/v1/workflows/%s/%s", c.url, namespace, workflowName)) if err != nil { return nil, err @@ -91,7 +92,7 @@ func (c *ArgoClientImpl) GetWorkflow(namespace string, workflowName string) (*Wo defer func() { if err := res.Body.Close(); err != nil { - log.Error("error closing http body") + log.Error(ctx, "error closing http body") } }() @@ -102,15 +103,15 @@ func (c *ArgoClientImpl) GetWorkflow(namespace string, workflowName string) (*Wo workflowRes := Workflow{} if err := json.Unmarshal(body, &workflowRes); err != nil { - log.Error("an error was unexpected while parsing response from api /workflow template.") + log.Error(ctx, "an error was unexpected while parsing response from api /workflow template.") return nil, err } return &workflowRes, nil } -func (c *ArgoClientImpl) GetWorkflowLog(namespace string, container string, workflowName string) (logs string, err error) { - log.Info(fmt.Sprintf("%s/api/v1/workflows/%s/%s/log?logOptions.container=%s", c.url, namespace, workflowName, container)) +func (c *ArgoClientImpl) GetWorkflowLog(ctx context.Context, namespace string, container string, workflowName string) (logs string, err error) { + log.Info(ctx, fmt.Sprintf("%s/api/v1/workflows/%s/%s/log?logOptions.container=%s", c.url, namespace, workflowName, container)) res, err := c.client.Get(fmt.Sprintf("%s/api/v1/workflows/%s/%s/log?logOptions.container=%s", c.url, namespace, workflowName, container)) if err != nil { return logs, err @@ -124,7 +125,7 @@ func (c *ArgoClientImpl) GetWorkflowLog(namespace string, container string, work defer func() { if err := res.Body.Close(); err != nil { - log.Error("error closing http body") + log.Error(ctx, "error closing http body") } }() @@ -136,7 +137,7 @@ func (c *ArgoClientImpl) GetWorkflowLog(namespace string, container string, work return string(body[:]), nil } -func (c *ArgoClientImpl) GetWorkflows(namespace string) (*GetWorkflowsResponse, error) { +func (c *ArgoClientImpl) GetWorkflows(ctx context.Context, namespace string) (*GetWorkflowsResponse, error) { res, err := c.client.Get(fmt.Sprintf("%s/api/v1/workflows/%s", c.url, namespace)) if err != nil { return nil, err @@ -150,7 +151,7 @@ func (c *ArgoClientImpl) GetWorkflows(namespace string) (*GetWorkflowsResponse, defer func() { if err := res.Body.Close(); err != nil { - log.Error("error closing http body") + log.Error(ctx, "error closing http body") } }() @@ -161,21 +162,21 @@ func (c *ArgoClientImpl) GetWorkflows(namespace string) (*GetWorkflowsResponse, workflowsRes := GetWorkflowsResponse{} if err := json.Unmarshal(body, &workflowsRes); err != nil { - log.Error("an error was unexpected while parsing response from api /workflow template.") + log.Error(ctx, "an error was unexpected while parsing response from api /workflow template.") return nil, err } return &workflowsRes, nil } -func (c *ArgoClientImpl) SumbitWorkflowFromWftpl(wftplName string, opts SubmitOptions) (string, error) { +func (c *ArgoClientImpl) SumbitWorkflowFromWftpl(ctx context.Context, wftplName string, opts SubmitOptions) (string, error) { reqBody := submitWorkflowRequestBody{ Namespace: "argo", ResourceKind: "WorkflowTemplate", ResourceName: wftplName, SubmitOptions: opts, } - log.Debug("SumbitWorkflowFromWftpl reqBody ", reqBody) + log.Debug(ctx, "SumbitWorkflowFromWftpl reqBody ", reqBody) reqBodyBytes, err := json.Marshal(reqBody) if err != nil { @@ -199,7 +200,7 @@ func (c *ArgoClientImpl) SumbitWorkflowFromWftpl(wftplName string, opts SubmitOp defer func() { if res != nil { if err := res.Body.Close(); err != nil { - log.Error("error closing http body") + log.Error(ctx, "error closing http body") } } }() @@ -211,7 +212,7 @@ func (c *ArgoClientImpl) SumbitWorkflowFromWftpl(wftplName string, opts SubmitOp submitRes := SubmitWorkflowResponse{} if err := json.Unmarshal(body, &submitRes); err != nil { - log.Error("an error was unexpected while parsing response from api /submit.") + log.Error(ctx, "an error was unexpected while parsing response from api /submit.") return "", err } return submitRes.Metadata.Name, nil diff --git a/pkg/domain/mapper.go b/pkg/domain/mapper.go new file mode 100644 index 00000000..e69de29b diff --git a/pkg/httpErrors/httpErrors.go b/pkg/httpErrors/httpErrors.go index 6e5b4464..bde4fd68 100644 --- a/pkg/httpErrors/httpErrors.go +++ b/pkg/httpErrors/httpErrors.go @@ -4,7 +4,6 @@ import ( "net/http" "strings" - "github.com/openinfradev/tks-api/pkg/log" "github.com/pkg/errors" ) @@ -71,7 +70,6 @@ func NewRestError(status int, err error, code ErrorCode, text string) IRestError if text != "" { t = text } - log.Info(t) return RestError{ ErrStatus: status, diff --git a/pkg/thanos-client/client.go b/pkg/thanos-client/client.go index 1a6994a5..bb9e360c 100644 --- a/pkg/thanos-client/client.go +++ b/pkg/thanos-client/client.go @@ -1,6 +1,7 @@ package thanos import ( + "context" "encoding/json" "fmt" "io" @@ -13,8 +14,8 @@ import ( ) type ThanosClient interface { - Get(query string) (Metric, error) - FetchRange(query string, start int, end int, step int) (out Metric, err error) + Get(ctx context.Context, query string) (Metric, error) + FetchRange(ctx context.Context, query string, start int, end int, step int) (out Metric, err error) } type ThanosClientImpl struct { @@ -44,10 +45,10 @@ func New(host string, port int, ssl bool, token string) (ThanosClient, error) { }, nil } -func (c *ThanosClientImpl) Get(query string) (out Metric, err error) { +func (c *ThanosClientImpl) Get(ctx context.Context, query string) (out Metric, err error) { url := c.url + "/api/v1/query?query=" + url.QueryEscape(query) - log.Info("url : ", url) + log.Info(ctx, "url : ", url) res, err := c.client.Get(url) if err != nil { return out, err @@ -61,7 +62,7 @@ func (c *ThanosClientImpl) Get(query string) (out Metric, err error) { defer func() { if err := res.Body.Close(); err != nil { - log.Error("error closing http body") + log.Error(ctx, "error closing http body") } }() @@ -75,16 +76,16 @@ func (c *ThanosClientImpl) Get(query string) (out Metric, err error) { return out, err } - log.Info(helper.ModelToJson(out)) + log.Info(ctx, helper.ModelToJson(out)) return } -func (c *ThanosClientImpl) FetchRange(query string, start int, end int, step int) (out Metric, err error) { +func (c *ThanosClientImpl) FetchRange(ctx context.Context, query string, start int, end int, step int) (out Metric, err error) { rangeParam := fmt.Sprintf("&dedup=true&partial_response=false&start=%d&end=%d&step=%d&max_source_resolution=0s", start, end, step) query = url.QueryEscape(query) + rangeParam url := c.url + "/api/v1/query_range?query=" + query - log.Info("url : ", url) + log.Info(ctx, "url : ", url) res, err := c.client.Get(url) if err != nil { return out, err @@ -98,7 +99,7 @@ func (c *ThanosClientImpl) FetchRange(query string, start int, end int, step int defer func() { if err := res.Body.Close(); err != nil { - log.Error("error closing http body") + log.Error(ctx, "error closing http body") } }() From d63313ee5e3025bcec3bccc156d12407922afcd2 Mon Sep 17 00:00:00 2001 From: donggyu Date: Wed, 13 Mar 2024 11:25:02 +0900 Subject: [PATCH 09/11] apply context to policy-template APIs --- internal/delivery/http/policy-template.go | 44 ++++---- internal/repository/policy-template.go | 129 +++++++++++----------- internal/usecase/policy-template.go | 40 +++---- 3 files changed, 107 insertions(+), 106 deletions(-) diff --git a/internal/delivery/http/policy-template.go b/internal/delivery/http/policy-template.go index e747a98f..20590ece 100644 --- a/internal/delivery/http/policy-template.go +++ b/internal/delivery/http/policy-template.go @@ -63,14 +63,14 @@ func (h *PolicyTemplateHandler) CreatePolicyTemplate(w http.ResponseWriter, r *h err := UnmarshalRequestInput(r, &input) if err != nil { - log.ErrorfWithContext(r.Context(), "error is :%s(%T)", err.Error(), err) + log.Errorf(r.Context(), "error is :%s(%T)", err.Error(), err) ErrorJSON(w, r, err) return } var dto model.PolicyTemplate if err = serializer.Map(input, &dto); err != nil { - log.InfoWithContext(r.Context(), err) + log.Info(r.Context(), err) } policyTemplateId, err := h.usecase.Create(r.Context(), dto) @@ -107,7 +107,7 @@ func (h *PolicyTemplateHandler) UpdatePolicyTemplate(w http.ResponseWriter, r *h id, err := uuid.Parse(policyTemplateId) if err != nil { - log.ErrorfWithContext(r.Context(), "error is :%s(%T)", err.Error(), err) + log.Errorf(r.Context(), "error is :%s(%T)", err.Error(), err) ErrorJSON(w, r, httpErrors.NewBadRequestError(fmt.Errorf("invalid policyTemplateId"), "C_INVALID_POLICY_TEMPLATE_ID", "")) return } @@ -117,7 +117,7 @@ func (h *PolicyTemplateHandler) UpdatePolicyTemplate(w http.ResponseWriter, r *h err = UnmarshalRequestInput(r, &input) if err != nil { - log.ErrorfWithContext(r.Context(), "error is :%s(%T)", err.Error(), err) + log.Errorf(r.Context(), "error is :%s(%T)", err.Error(), err) ErrorJSON(w, r, err) return } @@ -125,7 +125,7 @@ func (h *PolicyTemplateHandler) UpdatePolicyTemplate(w http.ResponseWriter, r *h err = h.usecase.Update(r.Context(), id, input) if err != nil { - log.ErrorfWithContext(r.Context(), "error is :%s(%T)", err.Error(), err) + log.Errorf(r.Context(), "error is :%s(%T)", err.Error(), err) if _, status := httpErrors.ErrorResponse(err); status == http.StatusNotFound { ErrorJSON(w, r, httpErrors.NewBadRequestError(err, "", "")) return @@ -159,7 +159,7 @@ func (h *PolicyTemplateHandler) DeletePolicyTemplate(w http.ResponseWriter, r *h id, err := uuid.Parse(policyTemplateId) if err != nil { - log.ErrorfWithContext(r.Context(), "error is :%s(%T)", err.Error(), err) + log.Errorf(r.Context(), "error is :%s(%T)", err.Error(), err) if _, status := httpErrors.ErrorResponse(err); status == http.StatusNotFound { ErrorJSON(w, r, httpErrors.NewBadRequestError(err, "", "")) return @@ -172,7 +172,7 @@ func (h *PolicyTemplateHandler) DeletePolicyTemplate(w http.ResponseWriter, r *h err = h.usecase.Delete(r.Context(), id) if err != nil { - log.ErrorfWithContext(r.Context(), "error is :%s(%T)", err.Error(), err) + log.Errorf(r.Context(), "error is :%s(%T)", err.Error(), err) if _, status := httpErrors.ErrorResponse(err); status == http.StatusNotFound { ErrorJSON(w, r, httpErrors.NewBadRequestError(err, "", "")) return @@ -206,7 +206,7 @@ func (h *PolicyTemplateHandler) GetPolicyTemplate(w http.ResponseWriter, r *http id, err := uuid.Parse(policyTemplateId) if err != nil { - log.ErrorfWithContext(r.Context(), "error is :%s(%T)", err.Error(), err) + log.Errorf(r.Context(), "error is :%s(%T)", err.Error(), err) if _, status := httpErrors.ErrorResponse(err); status == http.StatusNotFound { ErrorJSON(w, r, httpErrors.NewBadRequestError(err, "C_INVALID_POLICY_TEMPLATE_ID", "")) return @@ -218,7 +218,7 @@ func (h *PolicyTemplateHandler) GetPolicyTemplate(w http.ResponseWriter, r *http policyTemplate, err := h.usecase.Get(r.Context(), id) if err != nil { - log.ErrorfWithContext(r.Context(), "error is :%s(%T)", err.Error(), err) + log.Errorf(r.Context(), "error is :%s(%T)", err.Error(), err) if _, status := httpErrors.ErrorResponse(err); status == http.StatusNotFound { ErrorJSON(w, r, httpErrors.NewBadRequestError(err, "PT_NOT_FOUND_POLICY_TEMPLATE", "")) return @@ -230,7 +230,7 @@ func (h *PolicyTemplateHandler) GetPolicyTemplate(w http.ResponseWriter, r *http var out domain.GetPolicyTemplateResponse if err = serializer.Map(*policyTemplate, &out.PolicyTemplate); err != nil { - log.ErrorWithContext(r.Context(), err) + log.Error(r.Context(), err) } ResponseJSON(w, r, http.StatusOK, out) @@ -266,13 +266,13 @@ func (h *PolicyTemplateHandler) ListPolicyTemplate(w http.ResponseWriter, r *htt out.PolicyTemplates = make([]domain.PolicyTemplateResponse, len(policyTemplates)) for i, policyTemplate := range policyTemplates { if err := serializer.Map(policyTemplate, &out.PolicyTemplates[i]); err != nil { - log.InfoWithContext(r.Context(), err) + log.Info(r.Context(), err) continue } } if out.Pagination, err = pg.Response(); err != nil { - log.InfoWithContext(r.Context(), err) + log.Info(r.Context(), err) } ResponseJSON(w, r, http.StatusOK, out) @@ -300,7 +300,7 @@ func (h *PolicyTemplateHandler) ListPolicyTemplateVersions(w http.ResponseWriter id, err := uuid.Parse(policyTemplateId) if err != nil { - log.ErrorfWithContext(r.Context(), "error is :%s(%T)", err.Error(), err) + log.Errorf(r.Context(), "error is :%s(%T)", err.Error(), err) ErrorJSON(w, r, httpErrors.NewBadRequestError(err, "C_INVALID_POLICY_TEMPLATE_ID", "")) return } @@ -308,7 +308,7 @@ func (h *PolicyTemplateHandler) ListPolicyTemplateVersions(w http.ResponseWriter policyTemplateVersions, err := h.usecase.ListPolicyTemplateVersions(r.Context(), id) if err != nil { - log.ErrorfWithContext(r.Context(), "error is :%s(%T)", err.Error(), err) + log.Errorf(r.Context(), "error is :%s(%T)", err.Error(), err) if _, status := httpErrors.ErrorResponse(err); status == http.StatusNotFound { ErrorJSON(w, r, httpErrors.NewBadRequestError(err, "PT_NOT_FOUND_POLICY_TEMPLATE_VERSION", "")) return @@ -320,7 +320,7 @@ func (h *PolicyTemplateHandler) ListPolicyTemplateVersions(w http.ResponseWriter var out domain.ListPolicyTemplateVersionsResponse if err = serializer.Map(*policyTemplateVersions, &out); err != nil { - log.ErrorWithContext(r.Context(), err) + log.Error(r.Context(), err) } ResponseJSON(w, r, http.StatusOK, out) @@ -415,7 +415,7 @@ func (h *PolicyTemplateHandler) GetPolicyTemplateVersion(w http.ResponseWriter, policyTemplate, err := h.usecase.GetPolicyTemplateVersion(r.Context(), id, version) if err != nil { - log.ErrorfWithContext(r.Context(), "error is :%s(%T)", err.Error(), err) + log.Errorf(r.Context(), "error is :%s(%T)", err.Error(), err) if _, status := httpErrors.ErrorResponse(err); status == http.StatusNotFound { ErrorJSON(w, r, httpErrors.NewBadRequestError(err, "PT_NOT_FOUND_POLICY_TEMPLATE_VERSION", "")) return @@ -427,7 +427,7 @@ func (h *PolicyTemplateHandler) GetPolicyTemplateVersion(w http.ResponseWriter, var out domain.GetPolicyTemplateVersionResponse if err = serializer.Map(*policyTemplate, &out.PolicyTemplate); err != nil { - log.ErrorWithContext(r.Context(), err) + log.Error(r.Context(), err) } ResponseJSON(w, r, http.StatusOK, out) @@ -464,7 +464,7 @@ func (h *PolicyTemplateHandler) CreatePolicyTemplateVersion(w http.ResponseWrite err = UnmarshalRequestInput(r, &input) if err != nil { - log.ErrorfWithContext(r.Context(), "error is :%s(%T)", err.Error(), err) + log.Errorf(r.Context(), "error is :%s(%T)", err.Error(), err) ErrorJSON(w, r, err) return } @@ -537,7 +537,7 @@ func (h *PolicyTemplateHandler) DeletePolicyTemplateVersion(w http.ResponseWrite id, err := uuid.Parse(policyTemplateId) if err != nil { - log.ErrorfWithContext(r.Context(), "error is :%s(%T)", err.Error(), err) + log.Errorf(r.Context(), "error is :%s(%T)", err.Error(), err) ErrorJSON(w, r, httpErrors.NewBadRequestError(err, "PT_INVALID_POLICY_TEMPLATE_VERSION", "")) return } @@ -545,7 +545,7 @@ func (h *PolicyTemplateHandler) DeletePolicyTemplateVersion(w http.ResponseWrite err = h.usecase.DeletePolicyTemplateVersion(r.Context(), id, version) if err != nil { - log.ErrorfWithContext(r.Context(), "error is :%s(%T)", err.Error(), err) + log.Errorf(r.Context(), "error is :%s(%T)", err.Error(), err) if _, status := httpErrors.ErrorResponse(err); status == http.StatusNotFound { ErrorJSON(w, r, httpErrors.NewBadRequestError(err, "PT_NOT_FOUND_POLICY_TEMPLATE_VERSION", "")) return @@ -651,7 +651,7 @@ func (h *PolicyTemplateHandler) RegoCompile(w http.ResponseWriter, r *http.Reque input := domain.RegoCompileRequest{} err := UnmarshalRequestInput(r, &input) if err != nil { - log.ErrorfWithContext(r.Context(), "error is :%s(%T)", err.Error(), err) + log.Errorf(r.Context(), "error is :%s(%T)", err.Error(), err) ErrorJSON(w, r, err) return @@ -659,7 +659,7 @@ func (h *PolicyTemplateHandler) RegoCompile(w http.ResponseWriter, r *http.Reque response, err := h.usecase.RegoCompile(&input, parseParameter) if err != nil { - log.ErrorfWithContext(r.Context(), "error is :%s(%T)", err.Error(), err) + log.Errorf(r.Context(), "error is :%s(%T)", err.Error(), err) ErrorJSON(w, r, err) return diff --git a/internal/repository/policy-template.go b/internal/repository/policy-template.go index 7500369b..dcd45c22 100644 --- a/internal/repository/policy-template.go +++ b/internal/repository/policy-template.go @@ -1,6 +1,7 @@ package repository import ( + "context" "encoding/json" "fmt" "strings" @@ -17,20 +18,20 @@ import ( ) type IPolicyTemplateRepository interface { - Create(dto model.PolicyTemplate) (policyTemplateId uuid.UUID, err error) - Update(dto domain.UpdatePolicyTemplateUpdate) (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 *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) + Create(ctx context.Context, dto model.PolicyTemplate) (policyTemplateId uuid.UUID, err error) + Update(ctx context.Context, dto domain.UpdatePolicyTemplateUpdate) (err error) + Fetch(ctx context.Context, pg *pagination.Pagination) (out []model.PolicyTemplate, err error) + GetByName(ctx context.Context, policyTemplateName string) (out *model.PolicyTemplate, err error) + GetByKind(ctx context.Context, policyTemplateKind string) (out *model.PolicyTemplate, err error) + GetByID(ctx context.Context, policyTemplateId uuid.UUID) (out *model.PolicyTemplate, err error) + Delete(ctx context.Context, policyTemplateId uuid.UUID) (err error) + ExistByName(ctx context.Context, policyTemplateName string) (exist bool, err error) + ExistByKind(ctx context.Context, policyTemplateKind string) (exist bool, err error) + ExistByID(ctx context.Context, policyTemplateId uuid.UUID) (exist bool, err error) + ListPolicyTemplateVersions(ctx context.Context, policyTemplateId uuid.UUID) (policyTemplateVersionsReponse *domain.ListPolicyTemplateVersionsResponse, err error) + GetPolicyTemplateVersion(ctx context.Context, policyTemplateId uuid.UUID, version string) (policyTemplateVersionsReponse *model.PolicyTemplate, 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) } type PolicyTemplateRepository struct { @@ -43,7 +44,7 @@ func NewPolicyTemplateRepository(db *gorm.DB) IPolicyTemplateRepository { } } -func (r *PolicyTemplateRepository) Create(dto model.PolicyTemplate) (policyTemplateId uuid.UUID, err error) { +func (r *PolicyTemplateRepository) Create(ctx context.Context, dto model.PolicyTemplate) (policyTemplateId uuid.UUID, err error) { jsonByte, err := json.Marshal(dto.ParametersSchema) if err != nil { @@ -98,7 +99,7 @@ func (r *PolicyTemplateRepository) Create(dto model.PolicyTemplate) (policyTempl return policyTemplate.ID, nil } -func (r *PolicyTemplateRepository) Update(dto domain.UpdatePolicyTemplateUpdate) (err error) { +func (r *PolicyTemplateRepository) Update(ctx context.Context, dto domain.UpdatePolicyTemplateUpdate) (err error) { updateMap := make(map[string]interface{}) updateMap["updator_id"] = dto.UpdatorId @@ -154,7 +155,7 @@ func (r *PolicyTemplateRepository) Update(dto domain.UpdatePolicyTemplateUpdate) }) } -func (r *PolicyTemplateRepository) Fetch(pg *pagination.Pagination) (out []model.PolicyTemplate, err error) { +func (r *PolicyTemplateRepository) Fetch(ctx context.Context, pg *pagination.Pagination) (out []model.PolicyTemplate, err error) { var policyTemplates []model.PolicyTemplate if pg == nil { pg = pagination.NewPagination(nil) @@ -174,24 +175,24 @@ func (r *PolicyTemplateRepository) Fetch(pg *pagination.Pagination) (out []model if res.Error != nil { if errors.Is(res.Error, gorm.ErrRecordNotFound) { - log.Info("Not found policyTemplate version") + log.Info(ctx, "Not found policyTemplate version") } else { - log.Error(res.Error) + log.Error(ctx, res.Error) } } - outPolicyTemplate := r.reflectPolicyTemplate(policyTemplate, policyTemplateVersion) + outPolicyTemplate := r.reflectPolicyTemplate(ctx, policyTemplate, policyTemplateVersion) out = append(out, outPolicyTemplate) } return out, nil } -func (r *PolicyTemplateRepository) reflectPolicyTemplate(policyTemplate model.PolicyTemplate, policyTemplateVersion model.PolicyTemplateSupportedVersion) (out model.PolicyTemplate) { +func (r *PolicyTemplateRepository) reflectPolicyTemplate(ctx context.Context, policyTemplate model.PolicyTemplate, policyTemplateVersion model.PolicyTemplateSupportedVersion) (out model.PolicyTemplate) { if err := serializer.Map(policyTemplate.Model, &out); err != nil { - log.Error(err) + log.Error(ctx, err) } if err := serializer.Map(policyTemplate, &out); err != nil { - log.Error(err) + log.Error(ctx, err) } out.TemplateName = policyTemplate.Name out.ID = policyTemplate.ID @@ -200,7 +201,7 @@ func (r *PolicyTemplateRepository) reflectPolicyTemplate(policyTemplate model.Po if len(policyTemplateVersion.ParameterSchema) > 0 { if err := json.Unmarshal([]byte(policyTemplateVersion.ParameterSchema), &schemas); err != nil { - log.Error(err) + log.Error(ctx, err) } else { out.ParametersSchema = schemas } @@ -227,7 +228,7 @@ func (r *PolicyTemplateRepository) reflectPolicyTemplate(policyTemplate model.Po return } -func (r *PolicyTemplateRepository) ExistsBy(key string, value interface{}) (exists bool, err error) { +func (r *PolicyTemplateRepository) ExistsBy(ctx context.Context, key string, value interface{}) (exists bool, err error) { query := fmt.Sprintf("%s = ?", key) var policyTemplate model.PolicyTemplate @@ -236,10 +237,10 @@ func (r *PolicyTemplateRepository) ExistsBy(key string, value interface{}) (exis if res.Error != nil { if errors.Is(res.Error, gorm.ErrRecordNotFound) { - log.Infof("Not found policyTemplate %s='%v'", key, value) + log.Infof(ctx, "Not found policyTemplate %s='%v'", key, value) return false, nil } else { - log.Error(res.Error) + log.Error(ctx, res.Error) return false, res.Error } } @@ -247,19 +248,19 @@ func (r *PolicyTemplateRepository) ExistsBy(key string, value interface{}) (exis return true, nil } -func (r *PolicyTemplateRepository) ExistByName(policyTemplateName string) (exist bool, err error) { - return r.ExistsBy("name", policyTemplateName) +func (r *PolicyTemplateRepository) ExistByName(ctx context.Context, policyTemplateName string) (exist bool, err error) { + return r.ExistsBy(ctx, "name", policyTemplateName) } -func (r *PolicyTemplateRepository) ExistByKind(policyTemplateKind string) (exist bool, err error) { - return r.ExistsBy("kind", policyTemplateKind) +func (r *PolicyTemplateRepository) ExistByKind(ctx context.Context, policyTemplateKind string) (exist bool, err error) { + return r.ExistsBy(ctx, "kind", policyTemplateKind) } -func (r *PolicyTemplateRepository) ExistByID(policyTemplateId uuid.UUID) (exist bool, err error) { - return r.ExistsBy("id", policyTemplateId) +func (r *PolicyTemplateRepository) ExistByID(ctx context.Context, policyTemplateId uuid.UUID) (exist bool, err error) { + return r.ExistsBy(ctx, "id", policyTemplateId) } -func (r *PolicyTemplateRepository) GetBy(key string, value interface{}) (out *model.PolicyTemplate, err error) { +func (r *PolicyTemplateRepository) GetBy(ctx context.Context, key string, value interface{}) (out *model.PolicyTemplate, err error) { query := fmt.Sprintf("%s = ?", key) var policyTemplate model.PolicyTemplate @@ -268,10 +269,10 @@ func (r *PolicyTemplateRepository) GetBy(key string, value interface{}) (out *mo if res.Error != nil { if errors.Is(res.Error, gorm.ErrRecordNotFound) { - log.Infof("Not found policyTemplate %s='%v'", key, value) + log.Infof(ctx, "Not found policyTemplate %s='%v'", key, value) return nil, nil } else { - log.Error(res.Error) + log.Error(ctx, res.Error) return nil, res.Error } } @@ -282,24 +283,24 @@ func (r *PolicyTemplateRepository) GetBy(key string, value interface{}) (out *mo First(&policyTemplateVersion) if res.Error != nil { if errors.Is(res.Error, gorm.ErrRecordNotFound) { - log.Info("Not found policyTemplate version") + log.Info(ctx, "Not found policyTemplate version") return nil, nil } else { - log.Error(res.Error) + log.Error(ctx, res.Error) return nil, res.Error } } fmt.Printf("BBBB %+v\n", policyTemplate.PermittedOrganizations) - result := r.reflectPolicyTemplate(policyTemplate, policyTemplateVersion) + result := r.reflectPolicyTemplate(ctx, policyTemplate, policyTemplateVersion) fmt.Printf("2222BBBB %+v\n", result.PermittedOrganizations) return &result, nil } -func (r *PolicyTemplateRepository) GetByID(policyTemplateId uuid.UUID) (out *model.PolicyTemplate, err error) { - return r.GetBy("id", policyTemplateId) +func (r *PolicyTemplateRepository) GetByID(ctx context.Context, policyTemplateId uuid.UUID) (out *model.PolicyTemplate, err error) { + return r.GetBy(ctx, "id", policyTemplateId) // var policyTemplate PolicyTemplate // res := r.db.Preload(clause.Associations).Where("id = ?", policyTemplateId). @@ -320,8 +321,8 @@ func (r *PolicyTemplateRepository) GetByID(policyTemplateId uuid.UUID) (out *mod // return &result, nil } -func (r *PolicyTemplateRepository) GetByName(policyTemplateName string) (out *model.PolicyTemplate, err error) { - return r.GetBy("name", policyTemplateName) +func (r *PolicyTemplateRepository) GetByName(ctx context.Context, policyTemplateName string) (out *model.PolicyTemplate, err error) { + return r.GetBy(ctx, "name", policyTemplateName) // var policyTemplate PolicyTemplate // res := r.db.Limit(1). @@ -342,11 +343,11 @@ func (r *PolicyTemplateRepository) GetByName(policyTemplateName string) (out *mo // return &result, nil } -func (r *PolicyTemplateRepository) GetByKind(policyTemplateKind string) (out *model.PolicyTemplate, err error) { - return r.GetBy("kind", policyTemplateKind) +func (r *PolicyTemplateRepository) GetByKind(ctx context.Context, policyTemplateKind string) (out *model.PolicyTemplate, err error) { + return r.GetBy(ctx, "kind", policyTemplateKind) } -func (r *PolicyTemplateRepository) Delete(policyTemplateId uuid.UUID) (err error) { +func (r *PolicyTemplateRepository) Delete(ctx context.Context, policyTemplateId uuid.UUID) (err error) { return r.db.Transaction(func(tx *gorm.DB) error { if err := tx.Where("policy_template_id = ?", policyTemplateId).Delete(&model.PolicyTemplateSupportedVersion{}).Error; err != nil { return err @@ -364,16 +365,16 @@ func (r *PolicyTemplateRepository) Delete(policyTemplateId uuid.UUID) (err error }) } -func (r *PolicyTemplateRepository) ListPolicyTemplateVersions(policyTemplateId uuid.UUID) (policyTemplateVersionsReponse *domain.ListPolicyTemplateVersionsResponse, err error) { +func (r *PolicyTemplateRepository) ListPolicyTemplateVersions(ctx context.Context, policyTemplateId uuid.UUID) (policyTemplateVersionsReponse *domain.ListPolicyTemplateVersionsResponse, err error) { var supportedVersions []model.PolicyTemplateSupportedVersion res := r.db.Where("policy_template_id = ?", policyTemplateId).Find(&supportedVersions) if res.Error != nil { if errors.Is(res.Error, gorm.ErrRecordNotFound) { - log.Info("Not found policyTemplate kind") + log.Info(ctx, "Not found policyTemplate kind") return nil, nil } else { - log.Error(res.Error) + log.Error(ctx, res.Error) return nil, res.Error } } @@ -391,17 +392,17 @@ func (r *PolicyTemplateRepository) ListPolicyTemplateVersions(policyTemplateId u return result, nil } -func (r *PolicyTemplateRepository) GetPolicyTemplateVersion(policyTemplateId uuid.UUID, version string) (policyTemplateVersionsReponse *model.PolicyTemplate, err error) { +func (r *PolicyTemplateRepository) GetPolicyTemplateVersion(ctx context.Context, 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) if res.Error != nil { if errors.Is(res.Error, gorm.ErrRecordNotFound) { - log.Info("Not found policyTemplate version") + log.Info(ctx, "Not found policyTemplate version") return nil, nil } else { - log.Error(res.Error) + log.Error(ctx, res.Error) return nil, res.Error } } @@ -412,29 +413,29 @@ func (r *PolicyTemplateRepository) GetPolicyTemplateVersion(policyTemplateId uui First(&policyTemplate) if res.Error != nil { if errors.Is(res.Error, gorm.ErrRecordNotFound) { - log.Info("Not found policyTemplate id") + log.Info(ctx, "Not found policyTemplate id") return nil, nil } else { - log.Error(res.Error) + log.Error(ctx, res.Error) return nil, res.Error } } - result := r.reflectPolicyTemplate(policyTemplate, policyTemplateVersion) + result := r.reflectPolicyTemplate(ctx, policyTemplate, policyTemplateVersion) return &result, nil } -func (r *PolicyTemplateRepository) DeletePolicyTemplateVersion(policyTemplateId uuid.UUID, version string) (err error) { +func (r *PolicyTemplateRepository) DeletePolicyTemplateVersion(ctx context.Context, policyTemplateId uuid.UUID, version string) (err error) { var policyTemplate model.PolicyTemplate res := r.db.Select("version").First(&policyTemplate) if res.Error != nil { if errors.Is(res.Error, gorm.ErrRecordNotFound) { - log.Info("Not found policyTemplate id") + log.Info(ctx, "Not found policyTemplate id") return nil } else { - log.Error(res.Error) + log.Error(ctx, res.Error) return res.Error } } @@ -451,10 +452,10 @@ func (r *PolicyTemplateRepository) DeletePolicyTemplateVersion(policyTemplateId Delete(&policyTemplateVersion) if res.Error != nil { if errors.Is(res.Error, gorm.ErrRecordNotFound) { - log.Info("Not found policyTemplate version") + log.Info(ctx, "Not found policyTemplate version") return nil } else { - log.Error(res.Error) + log.Error(ctx, res.Error) return res.Error } } @@ -462,7 +463,7 @@ func (r *PolicyTemplateRepository) DeletePolicyTemplateVersion(policyTemplateId return nil } -func (r *PolicyTemplateRepository) CreatePolicyTemplateVersion(policyTemplateId uuid.UUID, newVersion string, schema []domain.ParameterDef, rego string, libs []string) (version string, err error) { +func (r *PolicyTemplateRepository) CreatePolicyTemplateVersion(ctx context.Context, policyTemplateId uuid.UUID, newVersion string, schema []domain.ParameterDef, rego string, libs []string) (version string, err error) { var policyTemplateVersion model.PolicyTemplateSupportedVersion res := r.db.Limit(1). Where("policy_template_id = ? and version = ?", policyTemplateId, version). @@ -471,13 +472,13 @@ func (r *PolicyTemplateRepository) CreatePolicyTemplateVersion(policyTemplateId if res.Error == nil { err = errors.Errorf("Version %s already exists for the policyTemplate", newVersion) - log.Error(res.Error) + log.Error(ctx, res.Error) return "", err } if !errors.Is(res.Error, gorm.ErrRecordNotFound) { - log.Error(res.Error) + log.Error(ctx, res.Error) return "", res.Error } @@ -491,7 +492,7 @@ func (r *PolicyTemplateRepository) CreatePolicyTemplateVersion(policyTemplateId if err != nil { parseErr := errors.Errorf("Unable to parse parameter schema: %v", err) - log.Error(parseErr) + log.Error(ctx, parseErr) return "", parseErr } diff --git a/internal/usecase/policy-template.go b/internal/usecase/policy-template.go index 7c76a846..ed503e7a 100644 --- a/internal/usecase/policy-template.go +++ b/internal/usecase/policy-template.go @@ -53,18 +53,18 @@ func (u *PolicyTemplateUsecase) Create(ctx context.Context, dto model.PolicyTemp return "", httpErrors.NewUnauthorizedError(fmt.Errorf("invalid token"), "A_INVALID_TOKEN", "") } - exists, err := u.repo.ExistByName(dto.TemplateName) + exists, err := u.repo.ExistByName(ctx, dto.TemplateName) if err == nil && exists { return "", httpErrors.NewBadRequestError(httpErrors.DuplicateResource, "PT_CREATE_ALREADY_EXISTED_NAME", "policy template name already exists") } - exists, err = u.repo.ExistByKind(dto.Kind) + exists, err = u.repo.ExistByKind(ctx, dto.Kind) if err == nil && exists { return "", httpErrors.NewBadRequestError(httpErrors.DuplicateResource, "PT_CREATE_ALREADY_EXISTED_KIND", "policy template kind already exists") } for _, organizationId := range dto.PermittedOrganizationIds { - _, err = u.organizationRepo.Get(organizationId) + _, err = u.organizationRepo.Get(ctx, organizationId) if err != nil { return "", httpErrors.NewBadRequestError(fmt.Errorf("invalid organizationId"), "C_INVALID_ORGANIZATION_ID", "") } @@ -72,7 +72,7 @@ func (u *PolicyTemplateUsecase) Create(ctx context.Context, dto model.PolicyTemp userId := user.GetUserId() dto.CreatorId = &userId - id, err := u.repo.Create(dto) + id, err := u.repo.Create(ctx, dto) if err != nil { return "", err @@ -82,13 +82,13 @@ func (u *PolicyTemplateUsecase) Create(ctx context.Context, dto model.PolicyTemp } func (u *PolicyTemplateUsecase) Fetch(ctx context.Context, pg *pagination.Pagination) (policyTemplates []model.PolicyTemplate, err error) { - policyTemplates, err = u.repo.Fetch(pg) + policyTemplates, err = u.repo.Fetch(ctx, pg) if err != nil { return nil, err } - organizations, err := u.organizationRepo.Fetch(nil) + organizations, err := u.organizationRepo.Fetch(ctx, nil) if err == nil { for i, policyTemplate := range policyTemplates { permittedOrgIdSet := u.getPermittedOrganiationIdSet(&policyTemplate) @@ -102,7 +102,7 @@ func (u *PolicyTemplateUsecase) Fetch(ctx context.Context, pg *pagination.Pagina } func (u *PolicyTemplateUsecase) Get(ctx context.Context, policyTemplateID uuid.UUID) (policyTemplates *model.PolicyTemplate, err error) { - policyTemplate, err := u.repo.GetByID(policyTemplateID) + policyTemplate, err := u.repo.GetByID(ctx, policyTemplateID) if err != nil { return nil, err @@ -110,7 +110,7 @@ func (u *PolicyTemplateUsecase) Get(ctx context.Context, policyTemplateID uuid.U permittedOrgIdSet := u.getPermittedOrganiationIdSet(policyTemplate) - organizations, err := u.organizationRepo.Fetch(nil) + organizations, err := u.organizationRepo.Fetch(ctx, nil) if err == nil { u.updatePermittedOrganizations(organizations, permittedOrgIdSet, policyTemplate) } @@ -124,19 +124,19 @@ func (u *PolicyTemplateUsecase) Update(ctx context.Context, policyTemplateId uui return httpErrors.NewBadRequestError(fmt.Errorf("invalid token"), "A_INVALID_TOKEN", "") } - _, err = u.repo.GetByID(policyTemplateId) + _, err = u.repo.GetByID(ctx, policyTemplateId) if err != nil { return httpErrors.NewNotFoundError(err, "PT_FAILED_FETCH_POLICY_TEMPLATE", "") } - exists, err := u.repo.ExistByName(*update.TemplateName) + exists, err := u.repo.ExistByName(ctx, *update.TemplateName) if err == nil && exists { return httpErrors.NewBadRequestError(httpErrors.DuplicateResource, "P_INVALID_POLICY_TEMPLATE_NAME", "policy template name already exists") } if update.PermittedOrganizationIds != nil { for _, organizationId := range *update.PermittedOrganizationIds { - _, err = u.organizationRepo.Get(organizationId) + _, err = u.organizationRepo.Get(ctx, organizationId) if err != nil { return httpErrors.NewBadRequestError(fmt.Errorf("invalid organizationId"), "C_INVALID_ORGANIZATION_ID", "") } @@ -155,7 +155,7 @@ func (u *PolicyTemplateUsecase) Update(ctx context.Context, policyTemplateId uui PermittedOrganizationIds: update.PermittedOrganizationIds, } - err = u.repo.Update(dto) + err = u.repo.Update(ctx, dto) if err != nil { return err } @@ -164,19 +164,19 @@ func (u *PolicyTemplateUsecase) Update(ctx context.Context, policyTemplateId uui } func (u *PolicyTemplateUsecase) Delete(ctx context.Context, policyTemplateId uuid.UUID) (err error) { - return u.repo.Delete(policyTemplateId) + return u.repo.Delete(ctx, policyTemplateId) } func (u *PolicyTemplateUsecase) IsPolicyTemplateNameExist(ctx context.Context, policyTemplateName string) (bool, error) { - return u.repo.ExistByName(policyTemplateName) + return u.repo.ExistByName(ctx, policyTemplateName) } func (u *PolicyTemplateUsecase) IsPolicyTemplateKindExist(ctx context.Context, policyTemplateKind string) (bool, error) { - return u.repo.ExistByKind(policyTemplateKind) + return u.repo.ExistByKind(ctx, policyTemplateKind) } func (u *PolicyTemplateUsecase) GetPolicyTemplateVersion(ctx context.Context, policyTemplateId uuid.UUID, version string) (policyTemplateVersionsReponse *model.PolicyTemplate, err error) { - policyTemplate, err := u.repo.GetPolicyTemplateVersion(policyTemplateId, version) + policyTemplate, err := u.repo.GetPolicyTemplateVersion(ctx, policyTemplateId, version) if err != nil { return nil, err @@ -184,7 +184,7 @@ func (u *PolicyTemplateUsecase) GetPolicyTemplateVersion(ctx context.Context, po permittedOrgIdSet := u.getPermittedOrganiationIdSet(policyTemplate) - organizations, err := u.organizationRepo.Fetch(nil) + organizations, err := u.organizationRepo.Fetch(ctx, nil) if err == nil { u.updatePermittedOrganizations(organizations, permittedOrgIdSet, policyTemplate) } @@ -234,15 +234,15 @@ func (*PolicyTemplateUsecase) getPermittedOrganiationIdSet(policyTemplate *model } func (u *PolicyTemplateUsecase) ListPolicyTemplateVersions(ctx context.Context, policyTemplateId uuid.UUID) (policyTemplateVersionsReponse *domain.ListPolicyTemplateVersionsResponse, err error) { - return u.repo.ListPolicyTemplateVersions(policyTemplateId) + return u.repo.ListPolicyTemplateVersions(ctx, policyTemplateId) } func (u *PolicyTemplateUsecase) DeletePolicyTemplateVersion(ctx context.Context, policyTemplateId uuid.UUID, version string) (err error) { - return u.repo.DeletePolicyTemplateVersion(policyTemplateId, version) + return u.repo.DeletePolicyTemplateVersion(ctx, policyTemplateId, version) } func (u *PolicyTemplateUsecase) CreatePolicyTemplateVersion(ctx context.Context, policyTemplateId uuid.UUID, newVersion string, schema []domain.ParameterDef, rego string, libs []string) (version string, err error) { - return u.repo.CreatePolicyTemplateVersion(policyTemplateId, newVersion, schema, rego, libs) + return u.repo.CreatePolicyTemplateVersion(ctx, policyTemplateId, newVersion, schema, rego, libs) } func (u *PolicyTemplateUsecase) RegoCompile(request *domain.RegoCompileRequest, parseParameter bool) (response *domain.RegoCompileResponse, err error) { From 22acb2c035796fc13a7d551b58d7f844c65f4cfa Mon Sep 17 00:00:00 2001 From: donggyu Date: Wed, 13 Mar 2024 11:25:28 +0900 Subject: [PATCH 10/11] remove unnecessary log --- internal/database/database.go | 4 ---- 1 file changed, 4 deletions(-) diff --git a/internal/database/database.go b/internal/database/database.go index 043bd031..91cfd606 100644 --- a/internal/database/database.go +++ b/internal/database/database.go @@ -4,7 +4,6 @@ import ( "context" "fmt" "github.com/openinfradev/tks-api/internal/pagination" - "github.com/openinfradev/tks-api/pkg/log" "os" "strings" @@ -192,10 +191,7 @@ func EnsureDefaultRows(db *gorm.DB) error { for _, ep := range eps { storedEps[ep.Name] = struct{}{} } - log.Debugf(context.Background(), "storedEps: %+v", storedEps) for _, ep := range api.ApiMap { - log.Debug(context.Background(), "ep.Name", ep.Name) - log.Debug(context.Background(), "storedEps[ep.Name]", storedEps[ep.Name]) if _, ok := storedEps[ep.Name]; !ok { if err := repoFactory.Endpoint.Create(ctx, &model.Endpoint{ Name: ep.Name, From 481e0194504c55f38ae6ce6a614977eadaf43db4 Mon Sep 17 00:00:00 2001 From: donggyu Date: Fri, 15 Mar 2024 14:55:21 +0900 Subject: [PATCH 11/11] fix conflict during rebase --- internal/delivery/http/alert.go | 12 +++---- internal/delivery/http/app-group.go | 12 +++---- internal/delivery/http/app-serve-app.go | 28 ++++++++-------- internal/delivery/http/audit.go | 6 ++-- internal/delivery/http/auth.go | 2 +- internal/delivery/http/cloud-account.go | 14 ++++---- internal/delivery/http/cluster.go | 10 +++--- internal/delivery/http/dashboard.go | 8 ++--- internal/delivery/http/organization.go | 24 +++++++------- internal/delivery/http/permission.go | 6 ++-- internal/delivery/http/policy-template.go | 12 +++---- internal/delivery/http/project.go | 16 ++++----- internal/delivery/http/role.go | 4 +-- internal/delivery/http/stack-template.go | 40 +++++++++++------------ internal/delivery/http/stack.go | 14 ++++---- internal/delivery/http/user.go | 28 ++++++++-------- internal/pagination/pagination.go | 7 ++-- internal/repository/policy-template.go | 4 +-- internal/serializer/serializer.go | 21 ++++++------ internal/usecase/cluster.go | 4 +-- internal/usecase/dashboard.go | 2 +- internal/usecase/organization.go | 2 +- internal/usecase/policy-template.go | 20 ++++++------ internal/usecase/project.go | 2 +- internal/usecase/stack.go | 10 +++--- pkg/domain/mapper.go | 0 26 files changed, 155 insertions(+), 153 deletions(-) delete mode 100644 pkg/domain/mapper.go diff --git a/internal/delivery/http/alert.go b/internal/delivery/http/alert.go index 4829e8d3..5ec1fa9b 100644 --- a/internal/delivery/http/alert.go +++ b/internal/delivery/http/alert.go @@ -126,13 +126,13 @@ func (h *AlertHandler) GetAlerts(w http.ResponseWriter, r *http.Request) { var out domain.GetAlertsResponse out.Alerts = make([]domain.AlertResponse, len(alerts)) for i, alert := range alerts { - if err := serializer.Map(alert, &out.Alerts[i]); err != nil { + if err := serializer.Map(r.Context(), alert, &out.Alerts[i]); err != nil { log.Info(r.Context(), err) } outAlertActions := make([]domain.AlertActionResponse, len(alert.AlertActions)) for j, alertAction := range alert.AlertActions { - if err := serializer.Map(alertAction, &outAlertActions[j]); err != nil { + if err := serializer.Map(r.Context(), alertAction, &outAlertActions[j]); err != nil { log.Info(r.Context(), err) } } @@ -142,7 +142,7 @@ func (h *AlertHandler) GetAlerts(w http.ResponseWriter, r *http.Request) { } } - if out.Pagination, err = pg.Response(); err != nil { + if out.Pagination, err = pg.Response(r.Context()); err != nil { log.Info(r.Context(), err) } @@ -182,12 +182,12 @@ func (h *AlertHandler) GetAlert(w http.ResponseWriter, r *http.Request) { } var out domain.GetAlertResponse - if err := serializer.Map(alert, &out.Alert); err != nil { + if err := serializer.Map(r.Context(), alert, &out.Alert); err != nil { log.Info(r.Context(), err) } outAlertActions := make([]domain.AlertActionResponse, len(alert.AlertActions)) for j, alertAction := range alert.AlertActions { - if err := serializer.Map(alertAction, &outAlertActions[j]); err != nil { + if err := serializer.Map(r.Context(), alertAction, &outAlertActions[j]); err != nil { log.Info(r.Context(), err) continue } @@ -274,7 +274,7 @@ func (h *AlertHandler) CreateAlertAction(w http.ResponseWriter, r *http.Request) log.Info(r.Context(), "alert : ", helper.ModelToJson(input)) var dto model.AlertAction - if err = serializer.Map(input, &dto); err != nil { + if err = serializer.Map(r.Context(), input, &dto); err != nil { log.Info(r.Context(), err) } dto.AlertId = alertId diff --git a/internal/delivery/http/app-group.go b/internal/delivery/http/app-group.go index dd7142a3..0a497091 100644 --- a/internal/delivery/http/app-group.go +++ b/internal/delivery/http/app-group.go @@ -45,7 +45,7 @@ func (h *AppGroupHandler) CreateAppGroup(w http.ResponseWriter, r *http.Request) } var dto model.AppGroup - if err = serializer.Map(input, &dto); err != nil { + if err = serializer.Map(r.Context(), input, &dto); err != nil { log.Info(r.Context(), err) } @@ -96,13 +96,13 @@ func (h *AppGroupHandler) GetAppGroups(w http.ResponseWriter, r *http.Request) { var out domain.GetAppGroupsResponse out.AppGroups = make([]domain.AppGroupResponse, len(appGroups)) for i, appGroup := range appGroups { - if err := serializer.Map(appGroup, &out.AppGroups[i]); err != nil { + if err := serializer.Map(r.Context(), appGroup, &out.AppGroups[i]); err != nil { log.Info(r.Context(), err) continue } } - if out.Pagination, err = pg.Response(); err != nil { + if out.Pagination, err = pg.Response(r.Context()); err != nil { log.Info(r.Context(), err) } @@ -139,7 +139,7 @@ func (h *AppGroupHandler) GetAppGroup(w http.ResponseWriter, r *http.Request) { } var out domain.GetAppGroupResponse - if err := serializer.Map(appGroup, &out.AppGroup); err != nil { + if err := serializer.Map(r.Context(), appGroup, &out.AppGroup); err != nil { log.Info(r.Context(), err) } @@ -225,7 +225,7 @@ func (h *AppGroupHandler) GetApplications(w http.ResponseWriter, r *http.Request var out domain.GetApplicationsResponse out.Applications = make([]domain.ApplicationResponse, len(applications)) for i, application := range applications { - if err := serializer.Map(application, &out.Applications[i]); err != nil { + if err := serializer.Map(r.Context(), application, &out.Applications[i]); err != nil { log.Info(r.Context(), err) continue } @@ -266,7 +266,7 @@ func (h *AppGroupHandler) CreateApplication(w http.ResponseWriter, r *http.Reque } var dto model.Application - if err := serializer.Map(input, &dto); err != nil { + if err := serializer.Map(r.Context(), input, &dto); err != nil { log.Info(r.Context(), err) } dto.AppGroupId = appGroupId diff --git a/internal/delivery/http/app-serve-app.go b/internal/delivery/http/app-serve-app.go index f75ff95c..2430d0e9 100644 --- a/internal/delivery/http/app-serve-app.go +++ b/internal/delivery/http/app-serve-app.go @@ -118,7 +118,7 @@ func (h *AppServeAppHandler) CreateAppServeApp(w http.ResponseWriter, r *http.Re (appReq).SetDefaultValue() var app model.AppServeApp - if err = serializer.Map(appReq, &app); err != nil { + if err = serializer.Map(r.Context(), appReq, &app); err != nil { ErrorJSON(w, r, httpErrors.NewBadRequestError(err, "", "")) return } @@ -134,7 +134,7 @@ func (h *AppServeAppHandler) CreateAppServeApp(w http.ResponseWriter, r *http.Re app.CreatedAt = now var task model.AppServeAppTask - if err = serializer.Map(appReq, &task); err != nil { + if err = serializer.Map(r.Context(), appReq, &task); err != nil { ErrorJSON(w, r, httpErrors.NewBadRequestError(err, "", "")) return } @@ -209,7 +209,7 @@ func (h *AppServeAppHandler) CreateAppServeApp(w http.ResponseWriter, r *http.Re } var out domain.CreateAppServeAppResponse - if err = serializer.Map(app, &out); err != nil { + if err = serializer.Map(r.Context(), app, &out); err != nil { ErrorJSON(w, r, err) return } @@ -268,13 +268,13 @@ func (h *AppServeAppHandler) GetAppServeApps(w http.ResponseWriter, r *http.Requ var out domain.GetAppServeAppsResponse out.AppServeApps = make([]domain.AppServeAppResponse, len(apps)) for i, app := range apps { - if err := serializer.Map(app, &out.AppServeApps[i]); err != nil { + if err := serializer.Map(r.Context(), app, &out.AppServeApps[i]); err != nil { log.Info(r.Context(), err) continue } } - if out.Pagination, err = pg.Response(); err != nil { + if out.Pagination, err = pg.Response(r.Context()); err != nil { log.Info(r.Context(), err) } @@ -338,7 +338,7 @@ func (h *AppServeAppHandler) GetAppServeApp(w http.ResponseWriter, r *http.Reque app.AppServeAppTasks = newTasks var out domain.GetAppServeAppResponse - if err := serializer.Map(app, &out.AppServeApp); err != nil { + if err := serializer.Map(r.Context(), app, &out.AppServeApp); err != nil { log.Info(r.Context(), err) } @@ -388,7 +388,7 @@ func (h *AppServeAppHandler) GetAppServeAppLatestTask(w http.ResponseWriter, r * } var out domain.GetAppServeAppTaskResponse - if err := serializer.Map(task, &out.AppServeAppTask); err != nil { + if err := serializer.Map(r.Context(), task, &out.AppServeAppTask); err != nil { log.Info(r.Context(), err) } @@ -478,13 +478,13 @@ func (h *AppServeAppHandler) GetAppServeAppTasksByAppId(w http.ResponseWriter, r var out domain.GetAppServeAppTasksResponse out.AppServeAppTasks = make([]domain.AppServeAppTaskResponse, len(tasks)) for i, task := range tasks { - if err := serializer.Map(task, &out.AppServeAppTasks[i]); err != nil { + if err := serializer.Map(r.Context(), task, &out.AppServeAppTasks[i]); err != nil { log.Info(r.Context(), err) continue } } - if out.Pagination, err = pg.Response(); err != nil { + if out.Pagination, err = pg.Response(r.Context()); err != nil { log.Info(r.Context(), err) } @@ -552,10 +552,10 @@ func (h *AppServeAppHandler) GetAppServeAppTaskDetail(w http.ResponseWriter, r * } var out domain.GetAppServeAppTaskResponse - if err := serializer.Map(app, &out.AppServeApp); err != nil { + if err := serializer.Map(r.Context(), app, &out.AppServeApp); err != nil { log.Info(r.Context(), err) } - if err := serializer.Map(task, &out.AppServeAppTask); err != nil { + if err := serializer.Map(r.Context(), task, &out.AppServeAppTask); err != nil { log.Info(r.Context(), err) } @@ -809,18 +809,18 @@ func (h *AppServeAppHandler) UpdateAppServeApp(w http.ResponseWriter, r *http.Re // break // } //} - //if err = serializer.Map(latestTask, &task); err != nil { + //if err = serializer.Map(r.Context(), latestTask, &task); err != nil { // ErrorJSON(w, r, httpErrors.NewBadRequestError(err, "", "")) // return //} var latestTask = app.AppServeAppTasks[0] - if err = serializer.Map(latestTask, &task); err != nil { + if err = serializer.Map(r.Context(), latestTask, &task); err != nil { //ErrorJSON(w, r, httpErrors.NewBadRequestError(err, "", "")) return } - if err = serializer.Map(appReq, &task); err != nil { + if err = serializer.Map(r.Context(), appReq, &task); err != nil { //ErrorJSON(w, r, httpErrors.NewBadRequestError(err, "", "")) return } diff --git a/internal/delivery/http/audit.go b/internal/delivery/http/audit.go index 5b8defff..e95ae959 100644 --- a/internal/delivery/http/audit.go +++ b/internal/delivery/http/audit.go @@ -68,12 +68,12 @@ func (h *AuditHandler) GetAudits(w http.ResponseWriter, r *http.Request) { var out domain.GetAuditsResponse out.Audits = make([]domain.AuditResponse, len(audits)) for i, audit := range audits { - if err := serializer.Map(audit, &out.Audits[i]); err != nil { + if err := serializer.Map(r.Context(), audit, &out.Audits[i]); err != nil { log.Info(r.Context(), err) } } - if out.Pagination, err = pg.Response(); err != nil { + if out.Pagination, err = pg.Response(r.Context()); err != nil { log.Info(r.Context(), err) } @@ -113,7 +113,7 @@ func (h *AuditHandler) GetAudit(w http.ResponseWriter, r *http.Request) { log.Info(r.Context(), audit) var out domain.GetAuditResponse - if err := serializer.Map(audit, &out.Audit); err != nil { + if err := serializer.Map(r.Context(), audit, &out.Audit); err != nil { log.Info(r.Context(), err) } diff --git a/internal/delivery/http/auth.go b/internal/delivery/http/auth.go index 5208a42a..bf81e50e 100644 --- a/internal/delivery/http/auth.go +++ b/internal/delivery/http/auth.go @@ -97,7 +97,7 @@ func (h *AuthHandler) Login(w http.ResponseWriter, r *http.Request) { } var out domain.LoginResponse - if err = serializer.Map(user, &out.User); err != nil { + if err = serializer.Map(r.Context(), user, &out.User); err != nil { log.Error(r.Context(), err) } diff --git a/internal/delivery/http/cloud-account.go b/internal/delivery/http/cloud-account.go index c2685eb8..53295041 100644 --- a/internal/delivery/http/cloud-account.go +++ b/internal/delivery/http/cloud-account.go @@ -55,7 +55,7 @@ func (h *CloudAccountHandler) CreateCloudAccount(w http.ResponseWriter, r *http. } var dto model.CloudAccount - if err = serializer.Map(input, &dto); err != nil { + if err = serializer.Map(r.Context(), input, &dto); err != nil { log.Info(r.Context(), err) } dto.OrganizationId = organizationId @@ -107,13 +107,13 @@ func (h *CloudAccountHandler) GetCloudAccounts(w http.ResponseWriter, r *http.Re var out domain.GetCloudAccountsResponse out.CloudAccounts = make([]domain.CloudAccountResponse, len(cloudAccounts)) for i, cloudAccount := range cloudAccounts { - if err := serializer.Map(cloudAccount, &out.CloudAccounts[i]); err != nil { + if err := serializer.Map(r.Context(), cloudAccount, &out.CloudAccounts[i]); err != nil { log.Info(r.Context(), err) continue } } - if out.Pagination, err = pg.Response(); err != nil { + if out.Pagination, err = pg.Response(r.Context()); err != nil { log.Info(r.Context(), err) } @@ -153,7 +153,7 @@ func (h *CloudAccountHandler) GetCloudAccount(w http.ResponseWriter, r *http.Req } var out domain.GetCloudAccountResponse - if err := serializer.Map(cloudAccount, &out.CloudAccount); err != nil { + if err := serializer.Map(r.Context(), cloudAccount, &out.CloudAccount); err != nil { log.Info(r.Context(), err) } @@ -200,7 +200,7 @@ func (h *CloudAccountHandler) UpdateCloudAccount(w http.ResponseWriter, r *http. } var dto model.CloudAccount - if err = serializer.Map(input, &dto); err != nil { + if err = serializer.Map(r.Context(), input, &dto); err != nil { log.Info(r.Context(), err) } dto.ID = cloudAccountId @@ -250,7 +250,7 @@ func (h *CloudAccountHandler) DeleteCloudAccount(w http.ResponseWriter, r *http. } var dto model.CloudAccount - if err = serializer.Map(input, &dto); err != nil { + if err = serializer.Map(r.Context(), input, &dto); err != nil { log.Info(r.Context(), err) } dto.ID = parsedId @@ -416,7 +416,7 @@ func (h *CloudAccountHandler) GetResourceQuota(w http.ResponseWriter, r *http.Re } var out domain.GetCloudAccountResourceQuotaResponse - if err := serializer.Map(resourceQuota, &out.ResourceQuota); err != nil { + if err := serializer.Map(r.Context(), resourceQuota, &out.ResourceQuota); err != nil { log.Info(r.Context(), err) } out.Available = available diff --git a/internal/delivery/http/cluster.go b/internal/delivery/http/cluster.go index 7dea7c9e..b67042e4 100644 --- a/internal/delivery/http/cluster.go +++ b/internal/delivery/http/cluster.go @@ -54,7 +54,7 @@ func (h *ClusterHandler) GetClusters(w http.ResponseWriter, r *http.Request) { var out domain.GetClustersResponse out.Clusters = make([]domain.ClusterResponse, len(clusters)) for i, cluster := range clusters { - if err := serializer.Map(cluster, &out.Clusters[i]); err != nil { + if err := serializer.Map(r.Context(), cluster, &out.Clusters[i]); err != nil { log.Info(r.Context(), err) continue } @@ -67,7 +67,7 @@ func (h *ClusterHandler) GetClusters(w http.ResponseWriter, r *http.Request) { } - if out.Pagination, err = pg.Response(); err != nil { + if out.Pagination, err = pg.Response(r.Context()); err != nil { log.Info(r.Context(), err) } @@ -100,7 +100,7 @@ func (h *ClusterHandler) GetCluster(w http.ResponseWriter, r *http.Request) { } var out domain.GetClusterResponse - if err := serializer.Map(cluster, &out.Cluster); err != nil { + if err := serializer.Map(r.Context(), cluster, &out.Cluster); err != nil { log.Info(r.Context(), err) } @@ -158,7 +158,7 @@ func (h *ClusterHandler) CreateCluster(w http.ResponseWriter, r *http.Request) { } var dto model.Cluster - if err = serializer.Map(input, &dto); err != nil { + if err = serializer.Map(r.Context(), input, &dto); err != nil { log.Info(r.Context(), err) } @@ -212,7 +212,7 @@ func (h *ClusterHandler) ImportCluster(w http.ResponseWriter, r *http.Request) { } var dto model.Cluster - if err = serializer.Map(input, &dto); err != nil { + if err = serializer.Map(r.Context(), input, &dto); err != nil { log.Info(r.Context(), err) } dto.SetDefaultConf() diff --git a/internal/delivery/http/dashboard.go b/internal/delivery/http/dashboard.go index 55c75cd5..69e49c6f 100644 --- a/internal/delivery/http/dashboard.go +++ b/internal/delivery/http/dashboard.go @@ -74,7 +74,7 @@ func (h *DashboardHandler) GetCharts(w http.ResponseWriter, r *http.Request) { var out domain.GetDashboardChartsResponse out.Charts = make([]domain.DashboardChartResponse, len(charts)) for i, chart := range charts { - if err := serializer.Map(chart, &out.Charts[i]); err != nil { + if err := serializer.Map(r.Context(), chart, &out.Charts[i]); err != nil { log.Info(r.Context(), err) continue } @@ -153,7 +153,7 @@ func (h *DashboardHandler) GetChart(w http.ResponseWriter, r *http.Request) { } var out domain.DashboardChartResponse - if err := serializer.Map(charts[0], &out); err != nil { + if err := serializer.Map(r.Context(), charts[0], &out); err != nil { log.Info(r.Context(), err) } @@ -193,7 +193,7 @@ func (h *DashboardHandler) GetStacks(w http.ResponseWriter, r *http.Request) { var out domain.GetDashboardStacksResponse out.Stacks = make([]domain.DashboardStackResponse, len(stacks)) for i, stack := range stacks { - if err := serializer.Map(stack, &out.Stacks[i]); err != nil { + if err := serializer.Map(r.Context(), stack, &out.Stacks[i]); err != nil { log.Info(r.Context(), err) continue } @@ -231,7 +231,7 @@ func (h *DashboardHandler) GetResources(w http.ResponseWriter, r *http.Request) return } var out domain.GetDashboardResourcesResponse - if err := serializer.Map(resources, &out.Resources); err != nil { + if err := serializer.Map(r.Context(), resources, &out.Resources); err != nil { log.Info(r.Context(), err) } diff --git a/internal/delivery/http/organization.go b/internal/delivery/http/organization.go index a224781d..683873d4 100644 --- a/internal/delivery/http/organization.go +++ b/internal/delivery/http/organization.go @@ -55,7 +55,7 @@ func (h *OrganizationHandler) CreateOrganization(w http.ResponseWriter, r *http. ctx := r.Context() var organization model.Organization - if err = serializer.Map(input, &organization); err != nil { + if err = serializer.Map(r.Context(), input, &organization); err != nil { log.Error(r.Context(), err) } @@ -122,14 +122,14 @@ func (h *OrganizationHandler) CreateOrganization(w http.ResponseWriter, r *http. err = h.usecase.ChangeAdminId(r.Context(), organizationId, admin.ID) if err != nil { - log.ErrorfWithContext(r.Context(), "error is :%s(%T)", err.Error(), err) + log.Errorf(r.Context(), "error is :%s(%T)", err.Error(), err) ErrorJSON(w, r, err) return } organization.AdminId = &admin.ID var out domain.CreateOrganizationResponse - if err = serializer.Map(organization, &out); err != nil { + if err = serializer.Map(r.Context(), organization, &out); err != nil { log.Error(r.Context(), err) } @@ -166,14 +166,14 @@ func (h *OrganizationHandler) GetOrganizations(w http.ResponseWriter, r *http.Re out.Organizations = make([]domain.OrganizationResponse, len(*organizations)) for i, organization := range *organizations { - if err = serializer.Map(organization, &out.Organizations[i]); err != nil { + if err = serializer.Map(r.Context(), organization, &out.Organizations[i]); err != nil { log.Error(r.Context(), err) } log.Info(r.Context(), organization) } - if out.Pagination, err = pg.Response(); err != nil { + if out.Pagination, err = pg.Response(r.Context()); err != nil { log.Info(r.Context(), err) } @@ -211,24 +211,24 @@ func (h *OrganizationHandler) GetOrganization(w http.ResponseWriter, r *http.Req return } var out domain.GetOrganizationResponse - if err = serializer.Map(organization, &out.Organization); err != nil { + if err = serializer.Map(r.Context(), organization, &out.Organization); err != nil { log.Error(r.Context(), err) } out.Organization.StackTemplates = make([]domain.SimpleStackTemplateResponse, len(organization.StackTemplates)) for i, stackTemplate := range organization.StackTemplates { - if err = serializer.Map(stackTemplate, &out.Organization.StackTemplates[i]); err != nil { - log.ErrorWithContext(r.Context(), err) + if err = serializer.Map(r.Context(), stackTemplate, &out.Organization.StackTemplates[i]); err != nil { + log.Error(r.Context(), err) } err := json.Unmarshal(stackTemplate.Services, &out.Organization.StackTemplates[i].Services) if err != nil { - log.ErrorWithContext(r.Context(), err) + log.Error(r.Context(), err) } } out.Organization.PolicyTemplates = make([]domain.SimplePolicyTemplateResponse, len(organization.PolicyTemplates)) for i, policyTemplate := range organization.PolicyTemplates { - if err = serializer.Map(policyTemplate, &out.Organization.PolicyTemplates[i]); err != nil { - log.ErrorWithContext(r.Context(), err) + if err = serializer.Map(r.Context(), policyTemplate, &out.Organization.PolicyTemplates[i]); err != nil { + log.Error(r.Context(), err) } } @@ -325,7 +325,7 @@ func (h *OrganizationHandler) UpdateOrganization(w http.ResponseWriter, r *http. } var out domain.UpdateOrganizationResponse - if err = serializer.Map(organization, &out); err != nil { + if err = serializer.Map(r.Context(), organization, &out); err != nil { log.Error(r.Context(), err) } diff --git a/internal/delivery/http/permission.go b/internal/delivery/http/permission.go index 488c971a..84ea905d 100644 --- a/internal/delivery/http/permission.go +++ b/internal/delivery/http/permission.go @@ -42,7 +42,7 @@ func (h PermissionHandler) GetPermissionTemplates(w http.ResponseWriter, r *http permissionSet := model.NewDefaultPermissionSet() var premissionSetResponse domain.PermissionSetResponse - if err := serializer.Map(permissionSet, &premissionSetResponse); err != nil { + if err := serializer.Map(r.Context(), permissionSet, &premissionSetResponse); err != nil { log.Info(r.Context(), err) } @@ -86,7 +86,7 @@ func (h PermissionHandler) GetPermissionsByRoleId(w http.ResponseWriter, r *http } var premissionSetResponse domain.PermissionSetResponse - if err := serializer.Map(permissionSet, &premissionSetResponse); err != nil { + if err := serializer.Map(r.Context(), permissionSet, &premissionSetResponse); err != nil { log.Info(r.Context(), err) } @@ -135,7 +135,7 @@ func (h PermissionHandler) UpdatePermissionsByRoleId(w http.ResponseWriter, r *h for _, permissionResponse := range input.Permissions { var permission model.Permission - if err := serializer.Map(permissionResponse, &permission); err != nil { + if err := serializer.Map(r.Context(), permissionResponse, &permission); err != nil { log.Info(r.Context(), err) } diff --git a/internal/delivery/http/policy-template.go b/internal/delivery/http/policy-template.go index 20590ece..ccb5ada7 100644 --- a/internal/delivery/http/policy-template.go +++ b/internal/delivery/http/policy-template.go @@ -69,7 +69,7 @@ func (h *PolicyTemplateHandler) CreatePolicyTemplate(w http.ResponseWriter, r *h } var dto model.PolicyTemplate - if err = serializer.Map(input, &dto); err != nil { + if err = serializer.Map(r.Context(), input, &dto); err != nil { log.Info(r.Context(), err) } @@ -229,7 +229,7 @@ func (h *PolicyTemplateHandler) GetPolicyTemplate(w http.ResponseWriter, r *http } var out domain.GetPolicyTemplateResponse - if err = serializer.Map(*policyTemplate, &out.PolicyTemplate); err != nil { + if err = serializer.Map(r.Context(), *policyTemplate, &out.PolicyTemplate); err != nil { log.Error(r.Context(), err) } @@ -265,13 +265,13 @@ func (h *PolicyTemplateHandler) ListPolicyTemplate(w http.ResponseWriter, r *htt var out domain.ListPolicyTemplateResponse out.PolicyTemplates = make([]domain.PolicyTemplateResponse, len(policyTemplates)) for i, policyTemplate := range policyTemplates { - if err := serializer.Map(policyTemplate, &out.PolicyTemplates[i]); err != nil { + if err := serializer.Map(r.Context(), policyTemplate, &out.PolicyTemplates[i]); err != nil { log.Info(r.Context(), err) continue } } - if out.Pagination, err = pg.Response(); err != nil { + if out.Pagination, err = pg.Response(r.Context()); err != nil { log.Info(r.Context(), err) } @@ -319,7 +319,7 @@ func (h *PolicyTemplateHandler) ListPolicyTemplateVersions(w http.ResponseWriter } var out domain.ListPolicyTemplateVersionsResponse - if err = serializer.Map(*policyTemplateVersions, &out); err != nil { + if err = serializer.Map(r.Context(), *policyTemplateVersions, &out); err != nil { log.Error(r.Context(), err) } @@ -426,7 +426,7 @@ func (h *PolicyTemplateHandler) GetPolicyTemplateVersion(w http.ResponseWriter, } var out domain.GetPolicyTemplateVersionResponse - if err = serializer.Map(*policyTemplate, &out.PolicyTemplate); err != nil { + if err = serializer.Map(r.Context(), *policyTemplate, &out.PolicyTemplate); err != nil { log.Error(r.Context(), err) } diff --git a/internal/delivery/http/project.go b/internal/delivery/http/project.go index 015c4c48..10c38379 100644 --- a/internal/delivery/http/project.go +++ b/internal/delivery/http/project.go @@ -189,7 +189,7 @@ func (p ProjectHandler) GetProjects(w http.ResponseWriter, r *http.Request) { var out domain.GetProjectsResponse out.Projects = pr - if out.Pagination, err = pg.Response(); err != nil { + if out.Pagination, err = pg.Response(r.Context()); err != nil { log.Info(r.Context(), err) } @@ -231,7 +231,7 @@ func (p ProjectHandler) Admin_GetProjects(w http.ResponseWriter, r *http.Request var out domain.GetProjectsResponse out.Projects = pr - if out.Pagination, err = pg.Response(); err != nil { + if out.Pagination, err = pg.Response(r.Context()); err != nil { log.Info(r.Context(), err) } @@ -301,7 +301,7 @@ func (p ProjectHandler) GetProject(w http.ResponseWriter, r *http.Request) { } var pdr domain.ProjectDetailResponse - if err = serializer.Map(*project, &pdr); err != nil { + if err = serializer.Map(r.Context(), *project, &pdr); err != nil { log.Error(r.Context(), err) ErrorJSON(w, r, err) return @@ -764,7 +764,7 @@ func (p ProjectHandler) GetProjectMembers(w http.ResponseWriter, r *http.Request } out = domain.GetProjectMembersResponse{ProjectMembers: pmrs} - if out.Pagination, err = pg.Response(); err != nil { + if out.Pagination, err = pg.Response(r.Context()); err != nil { log.Info(r.Context(), err) } @@ -1298,7 +1298,7 @@ func (p ProjectHandler) GetProjectNamespaces(w http.ResponseWriter, r *http.Requ pnrs := make([]domain.ProjectNamespaceResponse, 0) for _, pn := range pns { var pnr domain.ProjectNamespaceResponse - if err = serializer.Map(pn, &pnr); err != nil { + if err = serializer.Map(r.Context(), pn, &pnr); err != nil { log.Error(r.Context(), err) ErrorJSON(w, r, err) return @@ -1382,7 +1382,7 @@ func (p ProjectHandler) GetProjectNamespace(w http.ResponseWriter, r *http.Reque } var pnr domain.ProjectNamespaceResponse - if err = serializer.Map(*pn, &pnr); err != nil { + if err = serializer.Map(r.Context(), *pn, &pnr); err != nil { log.Error(r.Context(), err) ErrorJSON(w, r, err) return @@ -1631,7 +1631,7 @@ func (p ProjectHandler) GetProjectNamespaceK8sResources(w http.ResponseWriter, r } var out domain.GetProjectNamespaceK8sResourcesResponse - if err = serializer.Map(k8sResources, &out.K8sResources); err != nil { + if err = serializer.Map(r.Context(), k8sResources, &out.K8sResources); err != nil { log.Error(r.Context(), err) } ResponseJSON(w, r, http.StatusOK, out) @@ -1684,7 +1684,7 @@ func (p ProjectHandler) GetProjectNamespaceResourcesUsage(w http.ResponseWriter, } var out domain.GetProjectNamespaceResourcesUsageResponse - if err = serializer.Map(resourcesUsage, &out.ResourcesUsage); err != nil { + if err = serializer.Map(r.Context(), resourcesUsage, &out.ResourcesUsage); err != nil { log.Error(r.Context(), err) } ResponseJSON(w, r, http.StatusOK, out) diff --git a/internal/delivery/http/role.go b/internal/delivery/http/role.go index c760b9d2..8aebd4ab 100644 --- a/internal/delivery/http/role.go +++ b/internal/delivery/http/role.go @@ -143,7 +143,7 @@ func (h RoleHandler) ListTksRoles(w http.ResponseWriter, r *http.Request) { } } - if err := serializer.Map(*pg, &out.Pagination); err != nil { + if err := serializer.Map(r.Context(), *pg, &out.Pagination); err != nil { log.Info(r.Context(), err) } @@ -320,7 +320,7 @@ func (h RoleHandler) Admin_ListTksRoles(w http.ResponseWriter, r *http.Request) } } - if err := serializer.Map(*pg, &out.Pagination); err != nil { + if err := serializer.Map(r.Context(), *pg, &out.Pagination); err != nil { log.Info(r.Context(), err) } diff --git a/internal/delivery/http/stack-template.go b/internal/delivery/http/stack-template.go index a03b41fd..3297f29a 100644 --- a/internal/delivery/http/stack-template.go +++ b/internal/delivery/http/stack-template.go @@ -48,7 +48,7 @@ func (h *StackTemplateHandler) CreateStackTemplate(w http.ResponseWriter, r *htt } var dto model.StackTemplate - if err = serializer.Map(input, &dto); err != nil { + if err = serializer.Map(r.Context(), input, &dto); err != nil { log.Info(r.Context(), err) } @@ -91,13 +91,13 @@ func (h *StackTemplateHandler) GetStackTemplates(w http.ResponseWriter, r *http. 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 { + if err := serializer.Map(r.Context(), stackTemplate, &out.StackTemplates[i]); err != nil { log.Info(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 { + if err := serializer.Map(r.Context(), organization, &out.StackTemplates[i].Organizations[j]); err != nil { log.Info(r.Context(), err) continue } @@ -109,7 +109,7 @@ func (h *StackTemplateHandler) GetStackTemplates(w http.ResponseWriter, r *http. } } - if out.Pagination, err = pg.Response(); err != nil { + if out.Pagination, err = pg.Response(r.Context()); err != nil { log.Info(r.Context(), err) } @@ -148,13 +148,13 @@ func (h *StackTemplateHandler) GetStackTemplate(w http.ResponseWriter, r *http.R } var out domain.GetStackTemplateResponse - if err := serializer.Map(stackTemplate, &out.StackTemplate); err != nil { + if err := serializer.Map(r.Context(), stackTemplate, &out.StackTemplate); err != nil { log.Info(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 { + if err := serializer.Map(r.Context(), organization, &out.StackTemplate.Organizations[i]); err != nil { log.Info(r.Context(), err) continue } @@ -194,7 +194,7 @@ func (h *StackTemplateHandler) UpdateStackTemplate(w http.ResponseWriter, r *htt } var dto model.StackTemplate - if err := serializer.Map(r, &dto); err != nil { + if err := serializer.Map(r.Context(), r, &dto); err != nil { log.Info(r.Context(), err) } dto.ID = stackTemplateId @@ -289,7 +289,7 @@ func (h *StackTemplateHandler) UpdateStackTemplateOrganizations(w http.ResponseW } var dto model.StackTemplate - if err := serializer.Map(input, &dto); err != nil { + if err := serializer.Map(r.Context(), input, &dto); err != nil { log.Info(r.Context(), err) } dto.ID = stackTemplateId @@ -336,25 +336,25 @@ func (h *StackTemplateHandler) GetOrganizationStackTemplates(w http.ResponseWrit 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) + if err := serializer.Map(r.Context(), stackTemplate, &out.StackTemplates[i]); err != nil { + log.Info(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) + if err := serializer.Map(r.Context(), organization, &out.StackTemplates[i].Organizations[j]); err != nil { + log.Info(r.Context(), err) } } err := json.Unmarshal(stackTemplate.Services, &out.StackTemplates[i].Services) if err != nil { - log.ErrorWithContext(r.Context(), err) + log.Error(r.Context(), err) } } - if out.Pagination, err = pg.Response(); err != nil { - log.InfoWithContext(r.Context(), err) + if out.Pagination, err = pg.Response(r.Context()); err != nil { + log.Info(r.Context(), err) } ResponseJSON(w, r, http.StatusOK, out) @@ -397,20 +397,20 @@ func (h *StackTemplateHandler) GetOrganizationStackTemplate(w http.ResponseWrite } var out domain.GetStackTemplateResponse - if err := serializer.Map(stackTemplate, &out.StackTemplate); err != nil { - log.InfoWithContext(r.Context(), err) + if err := serializer.Map(r.Context(), stackTemplate, &out.StackTemplate); err != nil { + log.Info(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) + if err := serializer.Map(r.Context(), organization, &out.StackTemplate.Organizations[i]); err != nil { + log.Info(r.Context(), err) } } err = json.Unmarshal(stackTemplate.Services, &out.StackTemplate.Services) if err != nil { - log.ErrorWithContext(r.Context(), err) + log.Error(r.Context(), err) } ResponseJSON(w, r, http.StatusOK, out) diff --git a/internal/delivery/http/stack.go b/internal/delivery/http/stack.go index be985e76..62f3ee7b 100644 --- a/internal/delivery/http/stack.go +++ b/internal/delivery/http/stack.go @@ -53,7 +53,7 @@ func (h *StackHandler) CreateStack(w http.ResponseWriter, r *http.Request) { } var dto model.Stack - if err = serializer.Map(input, &dto); err != nil { + if err = serializer.Map(r.Context(), input, &dto); err != nil { log.Info(r.Context(), err) } dto.OrganizationId = organizationId @@ -122,11 +122,11 @@ func (h *StackHandler) GetStacks(w http.ResponseWriter, r *http.Request) { var out domain.GetStacksResponse out.Stacks = make([]domain.StackResponse, len(stacks)) for i, stack := range stacks { - if err := serializer.Map(stack, &out.Stacks[i]); err != nil { + if err := serializer.Map(r.Context(), stack, &out.Stacks[i]); err != nil { log.Info(r.Context(), err) } - if err := serializer.Map(stack.CreatedAt, &out.Stacks[i].CreatedAt); err != nil { + if err := serializer.Map(r.Context(), stack.CreatedAt, &out.Stacks[i].CreatedAt); err != nil { log.Info(r.Context(), err) } @@ -136,7 +136,7 @@ func (h *StackHandler) GetStacks(w http.ResponseWriter, r *http.Request) { } } - if out.Pagination, err = pg.Response(); err != nil { + if out.Pagination, err = pg.Response(r.Context()); err != nil { log.Info(r.Context(), err) } @@ -170,7 +170,7 @@ func (h *StackHandler) GetStack(w http.ResponseWriter, r *http.Request) { } var out domain.GetStackResponse - if err := serializer.Map(stack, &out.Stack); err != nil { + if err := serializer.Map(r.Context(), stack, &out.Stack); err != nil { log.Info(r.Context(), err) } @@ -212,7 +212,7 @@ func (h *StackHandler) GetStackStatus(w http.ResponseWriter, r *http.Request) { var out domain.GetStackStatusResponse out.StepStatus = make([]domain.StackStepStatus, len(steps)) for i, step := range steps { - if err := serializer.Map(step, &out.StepStatus[i]); err != nil { + if err := serializer.Map(r.Context(), step, &out.StepStatus[i]); err != nil { log.Info(r.Context(), err) } } @@ -261,7 +261,7 @@ func (h *StackHandler) UpdateStack(w http.ResponseWriter, r *http.Request) { } var dto model.Stack - if err = serializer.Map(input, &dto); err != nil { + if err = serializer.Map(r.Context(), input, &dto); err != nil { log.Info(r.Context(), err) } dto.ID = stackId diff --git a/internal/delivery/http/user.go b/internal/delivery/http/user.go index 203194db..9d6f09ef 100644 --- a/internal/delivery/http/user.go +++ b/internal/delivery/http/user.go @@ -88,7 +88,7 @@ func (u UserHandler) Create(w http.ResponseWriter, r *http.Request) { ctx := r.Context() var user model.User - if err = serializer.Map(input, &user); err != nil { + if err = serializer.Map(r.Context(), input, &user); err != nil { log.Error(r.Context(), err) } user.Organization = model.Organization{ @@ -121,7 +121,7 @@ func (u UserHandler) Create(w http.ResponseWriter, r *http.Request) { } var out domain.CreateUserResponse - if err = serializer.Map(*resUser, &out.User); err != nil { + if err = serializer.Map(r.Context(), *resUser, &out.User); err != nil { log.Error(r.Context(), err) } @@ -168,7 +168,7 @@ func (u UserHandler) Get(w http.ResponseWriter, r *http.Request) { } var out domain.GetUserResponse - if err = serializer.Map(*user, &out.User); err != nil { + if err = serializer.Map(r.Context(), *user, &out.User); err != nil { log.Error(r.Context(), err) } @@ -211,12 +211,12 @@ func (u UserHandler) List(w http.ResponseWriter, r *http.Request) { var out domain.ListUserResponse out.Users = make([]domain.ListUserBody, len(*users)) for i, user := range *users { - if err = serializer.Map(user, &out.Users[i]); err != nil { + if err = serializer.Map(r.Context(), user, &out.Users[i]); err != nil { log.Error(r.Context(), err) } } - if out.Pagination, err = pg.Response(); err != nil { + if out.Pagination, err = pg.Response(r.Context()); err != nil { log.Info(r.Context(), err) } @@ -300,7 +300,7 @@ func (u UserHandler) Update(w http.ResponseWriter, r *http.Request) { ctx := r.Context() var user model.User - if err = serializer.Map(input, &user); err != nil { + if err = serializer.Map(r.Context(), input, &user); err != nil { ErrorJSON(w, r, err) return } @@ -334,7 +334,7 @@ func (u UserHandler) Update(w http.ResponseWriter, r *http.Request) { } var out domain.UpdateUserResponse - if err = serializer.Map(*resUser, &out.User); err != nil { + if err = serializer.Map(r.Context(), *resUser, &out.User); err != nil { log.Error(r.Context(), err) ErrorJSON(w, r, err) return @@ -401,7 +401,7 @@ func (u UserHandler) GetMyProfile(w http.ResponseWriter, r *http.Request) { } var out domain.GetMyProfileResponse - if err = serializer.Map(*user, &out.User); err != nil { + if err = serializer.Map(r.Context(), *user, &out.User); err != nil { log.Error(r.Context(), err) ErrorJSON(w, r, err) return @@ -453,7 +453,7 @@ func (u UserHandler) UpdateMyProfile(w http.ResponseWriter, r *http.Request) { ctx := r.Context() var user model.User - if err = serializer.Map(input, &user); err != nil { + if err = serializer.Map(r.Context(), input, &user); err != nil { log.Error(r.Context(), err) ErrorJSON(w, r, err) return @@ -471,7 +471,7 @@ func (u UserHandler) UpdateMyProfile(w http.ResponseWriter, r *http.Request) { } var out domain.UpdateMyProfileResponse - if err = serializer.Map(*resUser, &out.User); err != nil { + if err = serializer.Map(r.Context(), *resUser, &out.User); err != nil { log.Error(r.Context(), err) ErrorJSON(w, r, err) return @@ -801,12 +801,12 @@ func (u UserHandler) Admin_List(w http.ResponseWriter, r *http.Request) { var out admin_domain.ListUserResponse out.Users = make([]domain.ListUserBody, len(*users)) for i, user := range *users { - if err = serializer.Map(user, &out.Users[i]); err != nil { + if err = serializer.Map(r.Context(), user, &out.Users[i]); err != nil { log.Error(r.Context(), err) } } - if out.Pagination, err = pg.Response(); err != nil { + if out.Pagination, err = pg.Response(r.Context()); err != nil { log.Info(r.Context(), err) } @@ -851,7 +851,7 @@ func (u UserHandler) Admin_Get(w http.ResponseWriter, r *http.Request) { } var out admin_domain.GetUserResponse - if err = serializer.Map(*user, &out.User); err != nil { + if err = serializer.Map(r.Context(), *user, &out.User); err != nil { log.Error(r.Context(), err) } @@ -1010,7 +1010,7 @@ func (u UserHandler) Admin_Update(w http.ResponseWriter, r *http.Request) { } var out admin_domain.UpdateUserResponse - if err = serializer.Map(*resUser, &out.User); err != nil { + if err = serializer.Map(r.Context(), *resUser, &out.User); err != nil { log.Error(r.Context(), err) ErrorJSON(w, r, err) return diff --git a/internal/pagination/pagination.go b/internal/pagination/pagination.go index 591a498c..5630bbb2 100644 --- a/internal/pagination/pagination.go +++ b/internal/pagination/pagination.go @@ -1,6 +1,7 @@ package pagination import ( + "context" "net/url" "strconv" "strings" @@ -144,13 +145,13 @@ func (p *Pagination) Fetch(db *gorm.DB, dest interface{}) (*database.Paginator, return paginator, db } -func (p *Pagination) Response() (out domain.PaginationResponse, err error) { - if err := serializer.Map(*p, &out); err != nil { +func (p *Pagination) Response(ctx context.Context) (out domain.PaginationResponse, err error) { + if err := serializer.Map(ctx, *p, &out); err != nil { return out, err } out.Filters = make([]domain.FilterResponse, len(p.Filters)) for i, f := range p.Filters { - if err := serializer.Map(f, &out.Filters[i]); err != nil { + if err := serializer.Map(ctx, f, &out.Filters[i]); err != nil { continue } } diff --git a/internal/repository/policy-template.go b/internal/repository/policy-template.go index dcd45c22..92053bb4 100644 --- a/internal/repository/policy-template.go +++ b/internal/repository/policy-template.go @@ -188,10 +188,10 @@ func (r *PolicyTemplateRepository) Fetch(ctx context.Context, pg *pagination.Pag } func (r *PolicyTemplateRepository) reflectPolicyTemplate(ctx context.Context, policyTemplate model.PolicyTemplate, policyTemplateVersion model.PolicyTemplateSupportedVersion) (out model.PolicyTemplate) { - if err := serializer.Map(policyTemplate.Model, &out); err != nil { + if err := serializer.Map(ctx, policyTemplate.Model, &out); err != nil { log.Error(ctx, err) } - if err := serializer.Map(policyTemplate, &out); err != nil { + if err := serializer.Map(ctx, policyTemplate, &out); err != nil { log.Error(ctx, err) } out.TemplateName = policyTemplate.Name diff --git a/internal/serializer/serializer.go b/internal/serializer/serializer.go index 01fdec59..ddb434a7 100644 --- a/internal/serializer/serializer.go +++ b/internal/serializer/serializer.go @@ -1,6 +1,7 @@ package serializer import ( + "context" "fmt" "reflect" @@ -16,7 +17,7 @@ type compositeKey struct { dstType reflect.Type } -func recursiveMap(src interface{}, dst interface{}, converterMap ConverterMap) error { +func recursiveMap(ctx context.Context, src interface{}, dst interface{}, converterMap ConverterMap) error { srcVal := reflect.ValueOf(src) srcType := srcVal.Type() @@ -40,14 +41,14 @@ func recursiveMap(src interface{}, dst interface{}, converterMap ConverterMap) e 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 { - log.Error(err) + if err := recursiveMap(ctx, srcField.Interface(), dstField.Addr().Interface(), converterMap); err != nil { + log.Error(ctx, err) continue } } else if srcField.Kind() == reflect.Pointer && dstField.Type().Kind() == reflect.Struct { if !reflect.Value.IsNil(srcField) { - if err := recursiveMap(srcField.Elem().Interface(), dstField.Addr().Interface(), converterMap); err != nil { - log.Error(err) + if err := recursiveMap(ctx, srcField.Elem().Interface(), dstField.Addr().Interface(), converterMap); err != nil { + log.Error(ctx, err) continue } } @@ -74,13 +75,13 @@ func recursiveMap(src interface{}, dst interface{}, converterMap ConverterMap) e converterKey := compositeKey{srcType: srcField.Type(), dstType: dstField.Type()} if converter, ok := converterMap[converterKey]; ok { if converted, err := converter(srcField.Interface()); err != nil { - log.Error(err) + log.Error(ctx, err) continue } else { dstField.Set(reflect.ValueOf(converted)) } } else { - log.Debugf("no converter found for %s -> %s", srcField.Type(), dstField.Type()) + log.Debugf(ctx, "no converter found for %s -> %s", srcField.Type(), dstField.Type()) continue } } @@ -96,7 +97,7 @@ func recursiveMap(src interface{}, dst interface{}, converterMap ConverterMap) e */ } else { if fieldName == "Model" { - if err := recursiveMap(srcField.Interface(), dst, converterMap); err != nil { + if err := recursiveMap(ctx, srcField.Interface(), dst, converterMap); err != nil { return err } } @@ -106,8 +107,8 @@ func recursiveMap(src interface{}, dst interface{}, converterMap ConverterMap) e return nil } -func Map(src interface{}, dst interface{}) error { - return recursiveMap(src, dst, ConverterMap{ +func Map(ctx context.Context, src interface{}, dst interface{}) error { + return recursiveMap(ctx, src, dst, ConverterMap{ {srcType: reflect.TypeOf((*uuid.UUID)(nil)).Elem(), dstType: reflect.TypeOf("")}: func(i interface{}) (interface{}, error) { return i.(uuid.UUID).String(), nil }, diff --git a/internal/usecase/cluster.go b/internal/usecase/cluster.go index 52fb3287..a2b04912 100644 --- a/internal/usecase/cluster.go +++ b/internal/usecase/cluster.go @@ -457,7 +457,7 @@ func (u *ClusterUsecase) GetClusterSiteValues(ctx context.Context, clusterId dom out.SshKeyName = "tks-seoul" out.ClusterRegion = "ap-northeast-2" - if err := serializer.Map(cluster, &out); err != nil { + if err := serializer.Map(ctx, cluster, &out); err != nil { log.Error(ctx, err) } @@ -466,7 +466,7 @@ func (u *ClusterUsecase) GetClusterSiteValues(ctx context.Context, clusterId dom out.TksUserNodeMax = cluster.TksUserNodeMax / domain.MAX_AZ_NUM } - if err := serializer.Map(cluster, &out); err != nil { + if err := serializer.Map(ctx, cluster, &out); err != nil { log.Error(ctx, err) } diff --git a/internal/usecase/dashboard.go b/internal/usecase/dashboard.go index 12d15d91..40a8b9b4 100644 --- a/internal/usecase/dashboard.go +++ b/internal/usecase/dashboard.go @@ -105,7 +105,7 @@ func (u *DashboardUsecase) GetStacks(ctx context.Context, organizationId string) } stack := reflectClusterToStack(ctx, cluster, appGroups) dashboardStack := domain.DashboardStack{} - if err := serializer.Map(stack, &dashboardStack); err != nil { + if err := serializer.Map(ctx, stack, &dashboardStack); err != nil { log.Info(ctx, err) } diff --git a/internal/usecase/organization.go b/internal/usecase/organization.go index 7fe6ea4f..83970930 100644 --- a/internal/usecase/organization.go +++ b/internal/usecase/organization.go @@ -105,7 +105,7 @@ func (u *OrganizationUsecase) Get(ctx context.Context, organizationId string) (o clusters, err := u.clusterRepo.FetchByOrganizationId(ctx, organizationId, uuid.Nil, nil) if err != nil { - log.Info(err) + log.Info(ctx, err) out.ClusterCount = 0 } out.ClusterCount = len(clusters) diff --git a/internal/usecase/policy-template.go b/internal/usecase/policy-template.go index ed503e7a..7f38429e 100644 --- a/internal/usecase/policy-template.go +++ b/internal/usecase/policy-template.go @@ -91,9 +91,9 @@ func (u *PolicyTemplateUsecase) Fetch(ctx context.Context, pg *pagination.Pagina organizations, err := u.organizationRepo.Fetch(ctx, nil) if err == nil { for i, policyTemplate := range policyTemplates { - permittedOrgIdSet := u.getPermittedOrganiationIdSet(&policyTemplate) + permittedOrgIdSet := u.getPermittedOrganiationIdSet(ctx, &policyTemplate) - u.updatePermittedOrganizations(organizations, permittedOrgIdSet, &policyTemplates[i]) + u.updatePermittedOrganizations(ctx, organizations, permittedOrgIdSet, &policyTemplates[i]) } } @@ -108,11 +108,11 @@ func (u *PolicyTemplateUsecase) Get(ctx context.Context, policyTemplateID uuid.U return nil, err } - permittedOrgIdSet := u.getPermittedOrganiationIdSet(policyTemplate) + permittedOrgIdSet := u.getPermittedOrganiationIdSet(ctx, policyTemplate) organizations, err := u.organizationRepo.Fetch(ctx, nil) if err == nil { - u.updatePermittedOrganizations(organizations, permittedOrgIdSet, policyTemplate) + u.updatePermittedOrganizations(ctx, organizations, permittedOrgIdSet, policyTemplate) } return policyTemplate, nil @@ -182,21 +182,21 @@ func (u *PolicyTemplateUsecase) GetPolicyTemplateVersion(ctx context.Context, po return nil, err } - permittedOrgIdSet := u.getPermittedOrganiationIdSet(policyTemplate) + permittedOrgIdSet := u.getPermittedOrganiationIdSet(ctx, policyTemplate) organizations, err := u.organizationRepo.Fetch(ctx, nil) if err == nil { - u.updatePermittedOrganizations(organizations, permittedOrgIdSet, policyTemplate) + u.updatePermittedOrganizations(ctx, organizations, permittedOrgIdSet, policyTemplate) } return policyTemplate, nil } -func (*PolicyTemplateUsecase) updatePermittedOrganizations(organizations *[]model.Organization, permittedOrgIdSet map[string]string, policyTemplate *model.PolicyTemplate) { +func (*PolicyTemplateUsecase) updatePermittedOrganizations(ctx context.Context, organizations *[]model.Organization, permittedOrgIdSet map[string]string, policyTemplate *model.PolicyTemplate) { // 허용리스트가 비어있으면 모든 Org에 대해서 허용 permitted := len(permittedOrgIdSet) == 0 - log.Info("CHECK HERE ", permitted) + log.Info(ctx, "CHECK HERE ", permitted) for _, organization := range *organizations { @@ -219,7 +219,7 @@ func (*PolicyTemplateUsecase) updatePermittedOrganizations(organizations *[]mode } } -func (*PolicyTemplateUsecase) getPermittedOrganiationIdSet(policyTemplate *model.PolicyTemplate) map[string]string { +func (*PolicyTemplateUsecase) getPermittedOrganiationIdSet(ctx context.Context, policyTemplate *model.PolicyTemplate) map[string]string { permittedOrgIdSet := make(map[string]string) for _, permittedOrg := range policyTemplate.PermittedOrganizations { @@ -228,7 +228,7 @@ func (*PolicyTemplateUsecase) getPermittedOrganiationIdSet(policyTemplate *model // ktkfree : 이부분 확인 부탁 드립니다. // //permittedOrgIdSet[permittedOrg.OrganizationId] = "1" - log.Info("CHECK HERE ", permittedOrg) + log.Info(ctx, "CHECK HERE ", permittedOrg) } return permittedOrgIdSet } diff --git a/internal/usecase/project.go b/internal/usecase/project.go index 2fa7d364..817eb24e 100644 --- a/internal/usecase/project.go +++ b/internal/usecase/project.go @@ -274,7 +274,7 @@ func (u *ProjectUsecase) GetProjectUser(ctx context.Context, projectUserId strin return nil, errors.Wrap(err, "Failed to retrieve user by id") } var pu model.ProjectUser - if err = serializer.Map(user, &pu); err != nil { + if err = serializer.Map(ctx, user, &pu); err != nil { log.Error(ctx, err) return nil, err } diff --git a/internal/usecase/stack.go b/internal/usecase/stack.go index f49dc70c..00a2e6c9 100644 --- a/internal/usecase/stack.go +++ b/internal/usecase/stack.go @@ -104,7 +104,7 @@ func (u *StackUsecase) Create(ctx context.Context, dto model.Stack) (stackId dom // Make stack nodes var stackConf domain.StackConfResponse - if err = serializer.Map(dto, &stackConf); err != nil { + if err = serializer.Map(ctx, dto, &stackConf); err != nil { log.Info(ctx, err) } if stackTemplate.CloudService == "AWS" && stackTemplate.KubeType == "AWS" { @@ -197,7 +197,7 @@ func (u *StackUsecase) Install(ctx context.Context, stackId domain.StackId) (err // Make stack nodes var stackConf domain.StackConfResponse - if err = serializer.Map(cluster, &stackConf); err != nil { + if err = serializer.Map(ctx, cluster, &stackConf); err != nil { log.Info(ctx, err) } @@ -250,7 +250,7 @@ func (u *StackUsecase) Get(ctx context.Context, stackId domain.StackId) (out mod for _, resource := range stackResources { if resource.ID == domain.StackId(cluster.ID) { - if err := serializer.Map(resource, &out.Resource); err != nil { + if err := serializer.Map(ctx, resource, &out.Resource); err != nil { log.Error(ctx, err) } } @@ -337,7 +337,7 @@ func (u *StackUsecase) Fetch(ctx context.Context, organizationId string, pg *pag for _, resource := range stackResources { if resource.ID == domain.StackId(cluster.ID) { - if err := serializer.Map(resource, &outStack.Resource); err != nil { + if err := serializer.Map(ctx, resource, &outStack.Resource); err != nil { log.Error(ctx, err) } } @@ -619,7 +619,7 @@ func (u *StackUsecase) DeleteFavorite(ctx context.Context, stackId domain.StackI } func reflectClusterToStack(ctx context.Context, cluster model.Cluster, appGroups []model.AppGroup) (out model.Stack) { - if err := serializer.Map(cluster, &out); err != nil { + if err := serializer.Map(ctx, cluster, &out); err != nil { log.Error(ctx, err) } diff --git a/pkg/domain/mapper.go b/pkg/domain/mapper.go deleted file mode 100644 index e69de29b..00000000