From c9c08d362587fa0be3de916f08a123d70071ba66 Mon Sep 17 00:00:00 2001 From: namkyu1999 Date: Thu, 16 Mar 2023 13:55:07 +0900 Subject: [PATCH 01/11] Migrate from Gorilla mux to Gin Signed-off-by: Namkyu Park Signed-off-by: namkyu1999 --- litmus-portal/graphql-server/go.mod | 4 +- litmus-portal/graphql-server/go.sum | 30 +++++++++++-- .../pkg/authorization/middleware.go | 42 ++++++++++--------- .../pkg/handlers/core_version_handler.go | 10 +++-- .../pkg/handlers/file_handler.go | 21 ++++------ .../pkg/handlers/playground_handler.go | 15 +++++++ .../pkg/handlers/readiness_handler.go | 14 ++++--- .../pkg/handlers/status_handler.go | 10 +++-- .../graphql-server/pkg/myhub/myhub.go | 37 +++++++++------- litmus-portal/graphql-server/server.go | 37 ++++++++-------- litmus-portal/graphql-server/utils/misc.go | 4 +- 11 files changed, 137 insertions(+), 87 deletions(-) create mode 100644 litmus-portal/graphql-server/pkg/handlers/playground_handler.go diff --git a/litmus-portal/graphql-server/go.mod b/litmus-portal/graphql-server/go.mod index b1beca60651..6429a85d58d 100644 --- a/litmus-portal/graphql-server/go.mod +++ b/litmus-portal/graphql-server/go.mod @@ -6,11 +6,12 @@ require ( github.com/99designs/gqlgen v0.11.3 github.com/argoproj/argo-workflows/v3 v3.3.1 github.com/ghodss/yaml v1.0.1-0.20190212211648-25d852aebe32 + github.com/gin-contrib/cors v1.3.1 + github.com/gin-gonic/gin v1.7.7 github.com/go-git/go-git/v5 v5.4.2 github.com/golang-jwt/jwt v3.2.2+incompatible github.com/golang/protobuf v1.5.2 github.com/google/uuid v1.3.0 - github.com/gorilla/mux v1.8.0 github.com/gorilla/websocket v1.5.0 github.com/jinzhu/copier v0.3.5 github.com/kelseyhightower/envconfig v1.4.0 @@ -20,7 +21,6 @@ require ( github.com/pkg/errors v0.9.1 github.com/prometheus/client_golang v1.12.1 github.com/prometheus/common v0.32.1 - github.com/rs/cors v1.8.2 github.com/sirupsen/logrus v1.8.1 github.com/tidwall/gjson v1.14.0 github.com/tidwall/sjson v1.2.4 diff --git a/litmus-portal/graphql-server/go.sum b/litmus-portal/graphql-server/go.sum index e6fef934633..1bc43705b19 100644 --- a/litmus-portal/graphql-server/go.sum +++ b/litmus-portal/graphql-server/go.sum @@ -548,6 +548,13 @@ github.com/ghodss/yaml v0.0.0-20150909031657-73d445a93680/go.mod h1:4dBDuWmgqj2H github.com/ghodss/yaml v1.0.0/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04= github.com/ghodss/yaml v1.0.1-0.20190212211648-25d852aebe32 h1:Mn26/9ZMNWSw9C9ERFA1PUxfmGpolnw2v0bKOREu5ew= github.com/ghodss/yaml v1.0.1-0.20190212211648-25d852aebe32/go.mod h1:GIjDIg/heH5DOkXY3YJ/wNhfHsQHoXGjl8G8amsYQ1I= +github.com/gin-contrib/cors v1.3.1 h1:doAsuITavI4IOcd0Y19U4B+O0dNWihRyX//nn4sEmgA= +github.com/gin-contrib/cors v1.3.1/go.mod h1:jjEJ4268OPZUcU7k9Pm653S7lXUGcqMADzFA61xsmDk= +github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE= +github.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI= +github.com/gin-gonic/gin v1.5.0/go.mod h1:Nd6IXA8m5kNZdNEHMBd93KT+mdY3+bewLgRvmCsR2Do= +github.com/gin-gonic/gin v1.7.7 h1:3DoBmSbJbZAWqXJC3SLjAPfutPJJRN1U5pALB7EeTTs= +github.com/gin-gonic/gin v1.7.7/go.mod h1:axIBovoeJpVj8S3BwE0uPMTeReE4+AfFtqpqaZ1qq1U= github.com/gizak/termui/v3 v3.1.0/go.mod h1:bXQEBkJpzxUAKf0+xq9MSWAvWZlE7c+aidmyFlkYTrY= github.com/gliderlabs/ssh v0.1.1/go.mod h1:U7qILu1NlMHj9FlMhZLlkCdDnU1DBEAqr0aevW3Awn0= github.com/gliderlabs/ssh v0.2.2 h1:6zsha5zo/TWhRhwqCD3+EarCAgZ2yN28ipRnGPnwkI0= @@ -714,6 +721,16 @@ github.com/go-openapi/validate v0.19.15/go.mod h1:tbn/fdOwYHgrhPBzidZfJC2MIVvs9G github.com/go-openapi/validate v0.20.1/go.mod h1:b60iJT+xNNLfaQJUqLI7946tYiFEOuE9E4k54HpKcJ0= github.com/go-openapi/validate v0.20.3/go.mod h1:goDdqVGiigM3jChcrYJxD2joalke3ZXeftD16byIjA4= github.com/go-ozzo/ozzo-validation v3.5.0+incompatible/go.mod h1:gsEKFIVnabGBt6mXmxK0MoFy+cZoTJY6mu5Ll3LVLBU= +github.com/go-playground/assert/v2 v2.0.1 h1:MsBgLAaY856+nPRTKrp3/OZK38U/wa0CcBYNjji3q3A= +github.com/go-playground/assert/v2 v2.0.1/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4= +github.com/go-playground/locales v0.12.1/go.mod h1:IUMDtCfWo/w/mtMfIE/IG2K+Ey3ygWanZIBtBW0W2TM= +github.com/go-playground/locales v0.13.0 h1:HyWk6mgj5qFqCT5fjGBuRArbVDfE4hi8+e8ceBS/t7Q= +github.com/go-playground/locales v0.13.0/go.mod h1:taPMhCMXrRLJO55olJkUXHZBHCxTMfnGwq/HNwmWNS8= +github.com/go-playground/universal-translator v0.16.0/go.mod h1:1AnU7NaIRDWWzGEKwgtJRd2xk99HeFyHw3yid4rvQIY= +github.com/go-playground/universal-translator v0.17.0 h1:icxd5fm+REJzpZx7ZfpaD876Lmtgy7VtROAbHHXk8no= +github.com/go-playground/universal-translator v0.17.0/go.mod h1:UkSxE5sNxxRwHyU+Scu5vgOQjsIJAF8j9muTVoKLVtA= +github.com/go-playground/validator/v10 v10.4.1 h1:pH2c5ADXtd66mxoE0Zm9SUhxE20r7aM3F26W0hOn+GE= +github.com/go-playground/validator/v10 v10.4.1/go.mod h1:nlOn6nFhuKACm19sB/8EGNn9GlaMV7XkbRSipzJ0Ii4= github.com/go-redis/redis v6.15.9+incompatible/go.mod h1:NAIEuMOZ/fxfXJIrKDQDz8wamY7mA7PouImQ2Jvg6kA= github.com/go-resty/resty/v2 v2.7.0/go.mod h1:9PWDzw47qPphMRFfhsyk0NnSgvluHcljSMVIq3w7q0I= github.com/go-sql-driver/mysql v1.4.0/go.mod h1:zAC/RDZ24gD3HViQzih4MyKcchzm+sOG5ZlKdlhCg5w= @@ -960,7 +977,6 @@ github.com/gorilla/mux v1.7.0/go.mod h1:1lud6UwP+6orDFRuTfBEV8e9/aOM/c4fVVCaMa2z github.com/gorilla/mux v1.7.1/go.mod h1:1lud6UwP+6orDFRuTfBEV8e9/aOM/c4fVVCaMa2zaAs= github.com/gorilla/mux v1.7.2/go.mod h1:1lud6UwP+6orDFRuTfBEV8e9/aOM/c4fVVCaMa2zaAs= github.com/gorilla/mux v1.7.3/go.mod h1:1lud6UwP+6orDFRuTfBEV8e9/aOM/c4fVVCaMa2zaAs= -github.com/gorilla/mux v1.8.0 h1:i40aqfkR1h2SlN9hojwV5ZA91wcXFOvkdNIeFDP5koI= github.com/gorilla/mux v1.8.0/go.mod h1:DVbg23sWSpFRCP0SfiEN6jmj59UnW/n46BH5rLB71So= github.com/gorilla/securecookie v1.1.1/go.mod h1:ra0sb63/xPlUeL+yeDciTfxMRAA+MP+HVt/4epWDjd4= github.com/gorilla/sessions v1.2.1/go.mod h1:dk2InVEVJ0sfLlnXv9EAgkf6ecYs/i80K/zI+bUmuGM= @@ -1202,6 +1218,9 @@ github.com/labstack/gommon v0.2.7/go.mod h1:/tj9csK2iPSBvn+3NLM9e52usepMtrd5ilFY github.com/lann/builder v0.0.0-20180802200727-47ae307949d0/go.mod h1:dXGbAdH5GtBTC4WfIxhKZfyBF/HBFgRZSWwZ9g/He9o= github.com/lann/ps v0.0.0-20150810152359-62de8c46ede0/go.mod h1:vmVJ0l/dxyfGW6FmdpVm2joNMFikkuWg0EoCKLGUMNw= github.com/leanovate/gopter v0.2.4/go.mod h1:gNcbPWNEWRe4lm+bycKqxUYoH5uoVje5SkOJ3uoLer8= +github.com/leodido/go-urn v1.1.0/go.mod h1:+cyI34gQWZcE1eQU7NVgKkkzdXDQHr1dBMtdAPozLkw= +github.com/leodido/go-urn v1.2.0 h1:hpXL4XnriNwQ/ABnpepYM/1vCLWNDfUNts8dX3xTG6Y= +github.com/leodido/go-urn v1.2.0/go.mod h1:+8+nEpDfqqsY+g338gtMEUOtuK+4dEMhiQEgxpxOKII= github.com/lib/pq v1.0.0/go.mod h1:5WUZQaWbwv1U+lTReE5YruASi9Al49XbQIvNi/34Woo= github.com/lib/pq v1.2.0/go.mod h1:5WUZQaWbwv1U+lTReE5YruASi9Al49XbQIvNi/34Woo= github.com/lib/pq v1.3.0/go.mod h1:5WUZQaWbwv1U+lTReE5YruASi9Al49XbQIvNi/34Woo= @@ -1274,6 +1293,7 @@ github.com/mattn/go-isatty v0.0.9/go.mod h1:YNRxwqDuOph6SZLI9vUUz6OYw3QyUt7WiY2y github.com/mattn/go-isatty v0.0.10/go.mod h1:qgIWMr58cqv1PHHyhnkY9lrL7etaEgOFcMEpPG5Rm84= github.com/mattn/go-isatty v0.0.11/go.mod h1:PhnuNfih5lzO57/f3n+odYbM4JtupLOxQOAqxQCu2WE= github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU= +github.com/mattn/go-isatty v0.0.14 h1:yVuAays6BHfxijgZPzw+3Zlu5yQgKGP2/hcQbHb7S9Y= github.com/mattn/go-isatty v0.0.14/go.mod h1:7GGIvUiUoEMVVmxf/4nioHXj79iQHKdU27kJ6hsGG94= github.com/mattn/go-runewidth v0.0.2/go.mod h1:LwmH8dsx7+W8Uxz3IHJYH5QSwggIsqBzpuz5H//U1FU= github.com/mattn/go-runewidth v0.0.3/go.mod h1:LwmH8dsx7+W8Uxz3IHJYH5QSwggIsqBzpuz5H//U1FU= @@ -1602,8 +1622,6 @@ github.com/rogpeppe/go-internal v1.6.1/go.mod h1:xXDCJY+GAPziupqXw64V24skbSoqbTE github.com/rogpeppe/go-internal v1.8.1 h1:geMPLpDpQOgVyCg5z5GoRwLHepNdb71NXb67XFkP+Eg= github.com/rogpeppe/go-internal v1.8.1/go.mod h1:JeRgkft04UBgHMgCIwADu4Pn6Mtm5d4nPKWu0nJ5d+o= github.com/rs/cors v1.6.0/go.mod h1:gFx+x8UowdsKA9AchylcLynDq+nNFfI8FkUZdN/jGCU= -github.com/rs/cors v1.8.2 h1:KCooALfAYGs415Cwu5ABvv9n9509fSiG5SQJn/AQo4U= -github.com/rs/cors v1.8.2/go.mod h1:XyqrcTp5zjWr1wsJ8PIRZssZ8b/WMcMf71DJnit4EMU= github.com/rs/xid v1.2.1/go.mod h1:+uKXf+4Djp6Md1KODXJxgGQPKngRmWyn10oCKFzNHOQ= github.com/rubenv/sql-migrate v0.0.0-20191025130928-9355dd04f4b3/go.mod h1:WS0rl9eEliYI8DPnr3TOwz4439pay+qNgzJoVya/DmY= github.com/rubenv/sql-migrate v0.0.0-20200212082348-64f95ea68aa3/go.mod h1:rtQlpHw+eR6UrqaS3kX1VYeaCxzCVdimDS7g5Ln4pPc= @@ -1751,7 +1769,11 @@ github.com/uber/jaeger-client-go v2.30.0+incompatible/go.mod h1:WVhlPFC8FDjOFMMW github.com/uber/jaeger-lib v2.2.0+incompatible/go.mod h1:ComeNDZlWwrWnDv8aPp0Ba6+uUTzImX/AauajbLI56U= github.com/uber/jaeger-lib v2.4.1+incompatible/go.mod h1:ComeNDZlWwrWnDv8aPp0Ba6+uUTzImX/AauajbLI56U= github.com/ugorji/go v1.1.4/go.mod h1:uQMGLiO92mf5W77hV/PUCpI3pbzQx3CRekS0kk+RGrc= +github.com/ugorji/go v1.1.7 h1:/68gy2h+1mWMrwZFeD1kQialdSzAb432dtpeJ42ovdo= +github.com/ugorji/go v1.1.7/go.mod h1:kZn38zHttfInRq0xu/PH0az30d+z6vm202qpg1oXVMw= github.com/ugorji/go/codec v0.0.0-20181204163529-d75b2dcb6bc8/go.mod h1:VFNgLljTbGfSG7qAOspJ7OScBnGdDN/yBr0sguwnwf0= +github.com/ugorji/go/codec v1.1.7 h1:2SvQaVZ1ouYrrKKwoSk2pzd4A9evlKJb9oTL+OaLUSs= +github.com/ugorji/go/codec v1.1.7/go.mod h1:Ax+UKWsSmolVDwsd+7N3ZtXu+yMGCf907BLYF3GoBXY= github.com/ultraware/funlen v0.0.1/go.mod h1:Dp4UiAus7Wdb9KUZsYWZEWiRzGuM2kXM1lPbfaF6xhA= github.com/ultraware/funlen v0.0.2/go.mod h1:Dp4UiAus7Wdb9KUZsYWZEWiRzGuM2kXM1lPbfaF6xhA= github.com/urfave/cli v0.0.0-20171014202726-7bc6a0acffa5/go.mod h1:70zkFmudgCuE/ngEzBv17Jvp/497gISqfk5gWijbERA= @@ -2634,6 +2656,8 @@ gopkg.in/fsnotify.v1 v1.4.7/go.mod h1:Tz8NjZHkW78fSQdbUxIjBTcgA1z1m8ZHf0WmKUhAMy gopkg.in/fsnotify/fsnotify.v1 v1.4.7/go.mod h1:Fyux9zXlo4rWoMSIzpn9fDAYjalPqJ/K1qJ27s+7ltE= gopkg.in/gcfg.v1 v1.2.0/go.mod h1:yesOnuUOFQAhST5vPY4nbZsb/huCgGGXlipJsBn0b3o= gopkg.in/gemnasium/logrus-airbrake-hook.v2 v2.1.2/go.mod h1:Xk6kEKp8OKb+X14hQBKWaSkCsqBpgog8nAV2xsGOxlo= +gopkg.in/go-playground/assert.v1 v1.2.1/go.mod h1:9RXL0bg/zibRAgZUYszZSwO/z8Y/a8bDuhia5mkpMnE= +gopkg.in/go-playground/validator.v9 v9.29.1/go.mod h1:+c9/zcJMFNgbLvly1L1V+PpxWdVbfP1avr/N00E2vyQ= gopkg.in/go-playground/webhooks.v5 v5.17.0/go.mod h1:LZbya/qLVdbqDR1aKrGuWV6qbia2zCYSR5dpom2SInQ= gopkg.in/gorp.v1 v1.7.2/go.mod h1:Wo3h+DBQZIxATwftsglhdD/62zRFPhGhTiu5jUJmCaw= gopkg.in/imdario/mergo.v0 v0.3.7/go.mod h1:9qPP6AGrlC1G2PTNXko614FwGZvorN7MiBU0Eppok+U= diff --git a/litmus-portal/graphql-server/pkg/authorization/middleware.go b/litmus-portal/graphql-server/pkg/authorization/middleware.go index 66efa32f061..7247d76cfb7 100644 --- a/litmus-portal/graphql-server/pkg/authorization/middleware.go +++ b/litmus-portal/graphql-server/pkg/authorization/middleware.go @@ -2,6 +2,7 @@ package authorization import ( "context" + "github.com/gin-gonic/gin" "net/http" "github.com/sirupsen/logrus" @@ -15,50 +16,51 @@ const ( CookieName = "litmus-cc-token" ) -func Middleware(handler http.Handler) http.Handler { - return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { +// Middleware verifies jwt and checks if user has enough privilege to access route (no roles' info needed) +func Middleware(handler http.Handler) gin.HandlerFunc { + return func(c *gin.Context) { jwt := "" - auth, err := r.Cookie(CookieName) + auth, err := c.Request.Cookie(CookieName) if err == nil { jwt = auth.Value - } else if r.Header.Get("Authorization") != "" { - jwt = r.Header.Get("Authorization") + } else if c.Request.Header.Get("Authorization") != "" { + jwt = c.Request.Header.Get("Authorization") } - ctx := context.WithValue(r.Context(), AuthKey, jwt) - r = r.WithContext(ctx) - handler.ServeHTTP(w, r) - }) + ctx := context.WithValue(c.Request.Context(), AuthKey, jwt) + c.Request = c.Request.WithContext(ctx) + handler.ServeHTTP(c.Writer, c.Request) + } } // RestMiddlewareWithRole verifies jwt and checks if user has enough privilege to access route -func RestMiddlewareWithRole(handler http.Handler, roles []string) http.Handler { - return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { +func RestMiddlewareWithRole(handler gin.HandlerFunc, roles []string) gin.HandlerFunc { + return func(c *gin.Context) { jwt := "" - auth, err := r.Cookie(CookieName) + auth, err := c.Request.Cookie(CookieName) if err == nil { jwt = auth.Value - } else if r.Header.Get("Authorization") != "" { - jwt = r.Header.Get("Authorization") + } else if c.Request.Header.Get("Authorization") != "" { + jwt = c.Request.Header.Get("Authorization") } user, err := UserValidateJWT(jwt) if err != nil { logrus.WithError(err).Error("Invalid Auth Cookie") - w.WriteHeader(http.StatusUnauthorized) - w.Write([]byte("Error verifying JWT token: " + err.Error())) + c.Writer.WriteHeader(http.StatusUnauthorized) + c.Writer.Write([]byte("Error verifying JWT token: " + err.Error())) return } if len(roles) == 0 { - handler.ServeHTTP(w, r) + handler(c) return } for _, role := range roles { if role == user["role"] { - handler.ServeHTTP(w, r) + handler(c) return } } - w.WriteHeader(http.StatusUnauthorized) + c.Writer.WriteHeader(http.StatusUnauthorized) return - }) + } } diff --git a/litmus-portal/graphql-server/pkg/handlers/core_version_handler.go b/litmus-portal/graphql-server/pkg/handlers/core_version_handler.go index 0f6b5a68843..23245352ead 100644 --- a/litmus-portal/graphql-server/pkg/handlers/core_version_handler.go +++ b/litmus-portal/graphql-server/pkg/handlers/core_version_handler.go @@ -2,6 +2,7 @@ package handlers import ( "encoding/json" + "github.com/gin-gonic/gin" "net/http" "github.com/litmuschaos/litmus/litmus-portal/graphql-server/utils" @@ -12,16 +13,17 @@ type WorkflowHelperImageVersion struct { Version string `json:"version"` } -func WorkflowHelperImageVersionHandler(w http.ResponseWriter, r *http.Request) { +// WorkflowHelperImageVersionHandler is used to provide workflow helper's image version +func WorkflowHelperImageVersionHandler(c *gin.Context) { versionDetails := utils.Config.WorkflowHelperImageVersion version := WorkflowHelperImageVersion{Version: versionDetails} versionByte, err := json.Marshal(version) if err != nil { logrus.Error(err) - utils.WriteHeaders(&w, http.StatusBadRequest) + utils.WriteHeaders(&c.Writer, http.StatusBadRequest) return } - utils.WriteHeaders(&w, http.StatusOK) - w.Write(versionByte) + utils.WriteHeaders(&c.Writer, http.StatusOK) + c.Writer.Write(versionByte) } diff --git a/litmus-portal/graphql-server/pkg/handlers/file_handler.go b/litmus-portal/graphql-server/pkg/handlers/file_handler.go index c06817c1edd..d5b42af0dd7 100644 --- a/litmus-portal/graphql-server/pkg/handlers/file_handler.go +++ b/litmus-portal/graphql-server/pkg/handlers/file_handler.go @@ -1,29 +1,24 @@ package handlers import ( - "net/http" - - "github.com/gorilla/mux" + "github.com/gin-gonic/gin" "github.com/litmuschaos/litmus/litmus-portal/graphql-server/pkg/cluster" "github.com/sirupsen/logrus" + "strings" "github.com/litmuschaos/litmus/litmus-portal/graphql-server/utils" ) // FileHandler dynamically generates the manifest file and sends it as a response -func FileHandler(w http.ResponseWriter, r *http.Request) { - var ( - vars = mux.Vars(r) - token = vars["key"] - ) - +func FileHandler(c *gin.Context) { + token := strings.TrimSuffix(c.Param("key"), ".yaml") response, statusCode, err := cluster.GetManifest(token) if err != nil { logrus.WithError(err).Error("error while generating manifest file") - utils.WriteHeaders(&w, statusCode) - w.Write([]byte(err.Error())) + utils.WriteHeaders(&c.Writer, statusCode) + c.Writer.Write([]byte(err.Error())) } - utils.WriteHeaders(&w, statusCode) - w.Write(response) + utils.WriteHeaders(&c.Writer, statusCode) + c.Writer.Write(response) } diff --git a/litmus-portal/graphql-server/pkg/handlers/playground_handler.go b/litmus-portal/graphql-server/pkg/handlers/playground_handler.go new file mode 100644 index 00000000000..fe3301c0d2b --- /dev/null +++ b/litmus-portal/graphql-server/pkg/handlers/playground_handler.go @@ -0,0 +1,15 @@ +package handlers + +import ( + "github.com/99designs/gqlgen/graphql/playground" + "github.com/gin-gonic/gin" +) + +// PlaygroundHandler returns GraphQL playground ui +func PlaygroundHandler() gin.HandlerFunc { + h := playground.Handler("GraphQL playground", "/query") + + return func(c *gin.Context) { + h.ServeHTTP(c.Writer, c.Request) + } +} diff --git a/litmus-portal/graphql-server/pkg/handlers/readiness_handler.go b/litmus-portal/graphql-server/pkg/handlers/readiness_handler.go index 4361d781d25..bd25e1237e0 100644 --- a/litmus-portal/graphql-server/pkg/handlers/readiness_handler.go +++ b/litmus-portal/graphql-server/pkg/handlers/readiness_handler.go @@ -3,6 +3,7 @@ package handlers import ( "context" "encoding/json" + "github.com/gin-gonic/gin" "net/http" "github.com/litmuschaos/litmus/litmus-portal/graphql-server/pkg/database/mongodb" @@ -27,8 +28,9 @@ func contains(s []string, str string) bool { return false } -func ReadinessHandler(handler http.Handler, mclient *mongo.Client) http.Handler { - return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { +// ReadinessHandler returns readiness information +func ReadinessHandler(mclient *mongo.Client) gin.HandlerFunc { + return func(c *gin.Context) { var ( db_flag = "up" col_flag = "up" @@ -56,10 +58,10 @@ func ReadinessHandler(handler http.Handler, mclient *mongo.Client) http.Handler statusByte, err := json.Marshal(status) if err != nil { logrus.Error(err) - utils.WriteHeaders(&w, http.StatusBadRequest) + utils.WriteHeaders(&c.Writer, http.StatusBadRequest) } - utils.WriteHeaders(&w, http.StatusOK) - w.Write(statusByte) - }) + utils.WriteHeaders(&c.Writer, http.StatusOK) + c.Writer.Write(statusByte) + } } diff --git a/litmus-portal/graphql-server/pkg/handlers/status_handler.go b/litmus-portal/graphql-server/pkg/handlers/status_handler.go index 8a7bee40a11..0c43ac1451f 100644 --- a/litmus-portal/graphql-server/pkg/handlers/status_handler.go +++ b/litmus-portal/graphql-server/pkg/handlers/status_handler.go @@ -2,6 +2,7 @@ package handlers import ( "encoding/json" + "github.com/gin-gonic/gin" "net/http" "github.com/litmuschaos/litmus/litmus-portal/graphql-server/utils" @@ -12,14 +13,15 @@ type APIStatus struct { Status string `json:"status"` } -func StatusHandler(w http.ResponseWriter, r *http.Request) { +// StatusHandler returns current status of this application +func StatusHandler(c *gin.Context) { var status = APIStatus{Status: "up"} statusByte, err := json.Marshal(status) if err != nil { logrus.Error(err) - utils.WriteHeaders(&w, http.StatusBadRequest) + utils.WriteHeaders(&c.Writer, http.StatusBadRequest) } - utils.WriteHeaders(&w, http.StatusOK) - w.Write(statusByte) + utils.WriteHeaders(&c.Writer, http.StatusOK) + c.Writer.Write(statusByte) } diff --git a/litmus-portal/graphql-server/pkg/myhub/myhub.go b/litmus-portal/graphql-server/pkg/myhub/myhub.go index 63f9f79adfc..027c61ed1a2 100644 --- a/litmus-portal/graphql-server/pkg/myhub/myhub.go +++ b/litmus-portal/graphql-server/pkg/myhub/myhub.go @@ -4,16 +4,15 @@ import ( "context" "errors" "fmt" + "github.com/gin-gonic/gin" "io" "log" - "net/http" "os" "strconv" "strings" "time" "github.com/google/uuid" - "github.com/gorilla/mux" "github.com/jinzhu/copier" "go.mongodb.org/mongo-driver/bson" @@ -515,31 +514,37 @@ func DeleteChaosHub(ctx context.Context, hubID string, projectID string) (bool, } // GetIconHandler ... -var GetIconHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - vars := mux.Vars(r) - var img *os.File - var err error - var responseStatusCode int - if strings.ToLower(vars["ChartName"]) == "predefined" { - img, err = os.Open("/tmp/version/" + vars["ProjectID"] + "/" + vars["HubName"] + "/workflows/icons/" + vars["IconName"]) +var GetIconHandler = gin.HandlerFunc(func(c *gin.Context) { + var ( + projectID = c.Param("ProjectID") + hubName = c.Param("HubName") + chartName = c.Param("ChartName") + iconName = c.Param("IconName") + img *os.File + err error + responseStatusCode int + ) + + if strings.ToLower(chartName) == "predefined" { + img, err = os.Open("/tmp/version/" + projectID + "/" + hubName + "/workflows/icons/" + iconName) responseStatusCode = 200 if err != nil { responseStatusCode = 500 - fmt.Fprint(w, "icon cannot be fetched, err : "+err.Error()) + fmt.Fprint(c.Writer, "icon cannot be fetched, err : "+err.Error()) } } else { - img, err = os.Open("/tmp/version/" + vars["ProjectID"] + "/" + vars["HubName"] + "/charts/" + vars["ChartName"] + "/icons/" + vars["IconName"]) + img, err = os.Open("/tmp/version/" + projectID + "/" + hubName + "/charts/" + chartName + "/icons/" + iconName) responseStatusCode = 200 if err != nil { responseStatusCode = 500 - fmt.Fprint(w, "icon cannot be fetched, err : "+err.Error()) + fmt.Fprint(c.Writer, "icon cannot be fetched, err : "+err.Error()) } } defer img.Close() - w.Header().Set("Access-Control-Allow-Origin", "*") - w.WriteHeader(responseStatusCode) - w.Header().Set("Content-Type", "image/png") // <-- set the content-type header - io.Copy(w, img) + c.Writer.Header().Set("Access-Control-Allow-Origin", "*") + c.Writer.WriteHeader(responseStatusCode) + c.Writer.Header().Set("Content-Type", "image/png") // <-- set the content-type header + io.Copy(c.Writer, img) }) // RecurringHubSync is used for syncing diff --git a/litmus-portal/graphql-server/server.go b/litmus-portal/graphql-server/server.go index 54388576aba..1f7c7ede5d6 100644 --- a/litmus-portal/graphql-server/server.go +++ b/litmus-portal/graphql-server/server.go @@ -3,6 +3,8 @@ package main import ( "context" "fmt" + "github.com/gin-contrib/cors" + "github.com/gin-gonic/gin" "net" "net/http" "runtime" @@ -22,8 +24,6 @@ import ( "github.com/99designs/gqlgen/graphql/handler" "github.com/99designs/gqlgen/graphql/handler/extension" "github.com/99designs/gqlgen/graphql/handler/transport" - "github.com/99designs/gqlgen/graphql/playground" - "github.com/gorilla/mux" "github.com/gorilla/websocket" "github.com/sirupsen/logrus" @@ -34,7 +34,6 @@ import ( "github.com/litmuschaos/litmus/litmus-portal/graphql-server/pkg/handlers" "github.com/litmuschaos/litmus/litmus-portal/graphql-server/pkg/myhub" pb "github.com/litmuschaos/litmus/litmus-portal/graphql-server/protos" - "github.com/rs/cors" "google.golang.org/grpc" ) @@ -106,25 +105,26 @@ func main() { // to be removed in production srv.Use(extension.Introspection{}) - router := mux.NewRouter() + gin.SetMode(gin.ReleaseMode) + gin.EnableJsonDecoderDisallowUnknownFields() + router := gin.Default() - router.Use(cors.New(cors.Options{ - AllowedHeaders: []string{"*"}, - AllowedOrigins: []string{"*"}, + router.Use(cors.New(cors.Config{ + AllowOrigins: []string{"*"}, + AllowHeaders: []string{"*"}, AllowCredentials: true, - }).Handler) + })) //router.Use(handlers.LoggingMiddleware()) // routers - router.Handle("/", playground.Handler("GraphQL playground", "/query")) - router.Handle("/query", authorization.Middleware(srv)) - router.Handle("/readiness", handlers.ReadinessHandler(srv, client)) - router.Handle("/icon/{ProjectID}/{HubName}/{ChartName}/{IconName}", authorization.RestMiddlewareWithRole(myhub.GetIconHandler, nil)).Methods("GET") - - router.HandleFunc("/file/{key}{path:.yaml}", handlers.FileHandler) - router.HandleFunc("/status", handlers.StatusHandler) - router.HandleFunc("/workflow_helper_image_version", handlers.WorkflowHelperImageVersionHandler) + router.GET("/", handlers.PlaygroundHandler()) + router.Any("/query", authorization.Middleware(srv)) + router.GET("/readiness", handlers.ReadinessHandler(client)) + router.GET("/icon/:ProjectID/:HubName/:ChartName/:IconName", authorization.RestMiddlewareWithRole(myhub.GetIconHandler, nil)) + router.Any("/file/:key", handlers.FileHandler) + router.GET("/status", handlers.StatusHandler) + router.GET("/workflow_helper_image_version", handlers.WorkflowHelperImageVersionHandler) gitOpsHandler.GitOpsSyncHandler(true) // sync all previous existing repos before start @@ -132,7 +132,10 @@ func main() { go gitOpsHandler.GitOpsSyncHandler(false) // routine to sync git repos for gitOps logrus.Printf("connect to http://localhost:%s/ for GraphQL playground", utils.Config.HttpPort) - logrus.Fatal(http.ListenAndServe(":"+utils.Config.HttpPort, router)) + err = router.Run(":" + utils.Config.HttpPort) + if err != nil { + logrus.Fatal(err) + } } // startGRPCServer initializes, registers services to and starts the gRPC server for RPC calls diff --git a/litmus-portal/graphql-server/utils/misc.go b/litmus-portal/graphql-server/utils/misc.go index 828414a8928..adb4a5c7cd6 100644 --- a/litmus-portal/graphql-server/utils/misc.go +++ b/litmus-portal/graphql-server/utils/misc.go @@ -3,14 +3,14 @@ package utils import ( "bytes" "encoding/base64" + "github.com/gin-gonic/gin" "math/rand" - "net/http" "strings" "unicode" ) // WriteHeaders adds important headers to API responses -func WriteHeaders(w *http.ResponseWriter, statusCode int) { +func WriteHeaders(w *gin.ResponseWriter, statusCode int) { (*w).Header().Set("Content-Type", "application/json; charset=utf-8") (*w).Header().Set("Access-Control-Allow-Origin", "*") (*w).WriteHeader(statusCode) From d6e352deb1f5cc7a587d29584b70143ed8150ab7 Mon Sep 17 00:00:00 2001 From: namkyu1999 Date: Sat, 18 Mar 2023 11:14:43 +0900 Subject: [PATCH 02/11] Linting & Ordering codes Signed-off-by: namkyu1999 --- .../pkg/authorization/middleware.go | 2 +- .../pkg/handlers/core_version_handler.go | 2 +- .../pkg/handlers/file_handler.go | 6 ++--- .../pkg/handlers/readiness_handler.go | 19 ++++++++------- .../pkg/handlers/status_handler.go | 2 +- .../graphql-server/pkg/myhub/myhub.go | 5 ++-- litmus-portal/graphql-server/server.go | 23 ++++++++----------- litmus-portal/graphql-server/utils/misc.go | 3 ++- 8 files changed, 28 insertions(+), 34 deletions(-) diff --git a/litmus-portal/graphql-server/pkg/authorization/middleware.go b/litmus-portal/graphql-server/pkg/authorization/middleware.go index 7247d76cfb7..986093719ea 100644 --- a/litmus-portal/graphql-server/pkg/authorization/middleware.go +++ b/litmus-portal/graphql-server/pkg/authorization/middleware.go @@ -2,9 +2,9 @@ package authorization import ( "context" - "github.com/gin-gonic/gin" "net/http" + "github.com/gin-gonic/gin" "github.com/sirupsen/logrus" ) diff --git a/litmus-portal/graphql-server/pkg/handlers/core_version_handler.go b/litmus-portal/graphql-server/pkg/handlers/core_version_handler.go index 23245352ead..2f908ff3daf 100644 --- a/litmus-portal/graphql-server/pkg/handlers/core_version_handler.go +++ b/litmus-portal/graphql-server/pkg/handlers/core_version_handler.go @@ -2,9 +2,9 @@ package handlers import ( "encoding/json" - "github.com/gin-gonic/gin" "net/http" + "github.com/gin-gonic/gin" "github.com/litmuschaos/litmus/litmus-portal/graphql-server/utils" "github.com/sirupsen/logrus" ) diff --git a/litmus-portal/graphql-server/pkg/handlers/file_handler.go b/litmus-portal/graphql-server/pkg/handlers/file_handler.go index d5b42af0dd7..4fd0e791557 100644 --- a/litmus-portal/graphql-server/pkg/handlers/file_handler.go +++ b/litmus-portal/graphql-server/pkg/handlers/file_handler.go @@ -1,12 +1,12 @@ package handlers import ( - "github.com/gin-gonic/gin" - "github.com/litmuschaos/litmus/litmus-portal/graphql-server/pkg/cluster" - "github.com/sirupsen/logrus" "strings" + "github.com/gin-gonic/gin" + "github.com/litmuschaos/litmus/litmus-portal/graphql-server/pkg/cluster" "github.com/litmuschaos/litmus/litmus-portal/graphql-server/utils" + "github.com/sirupsen/logrus" ) // FileHandler dynamically generates the manifest file and sends it as a response diff --git a/litmus-portal/graphql-server/pkg/handlers/readiness_handler.go b/litmus-portal/graphql-server/pkg/handlers/readiness_handler.go index bd25e1237e0..a876969e66b 100644 --- a/litmus-portal/graphql-server/pkg/handlers/readiness_handler.go +++ b/litmus-portal/graphql-server/pkg/handlers/readiness_handler.go @@ -3,14 +3,13 @@ package handlers import ( "context" "encoding/json" - "github.com/gin-gonic/gin" "net/http" + "github.com/gin-gonic/gin" "github.com/litmuschaos/litmus/litmus-portal/graphql-server/pkg/database/mongodb" - "go.mongodb.org/mongo-driver/mongo" - "github.com/litmuschaos/litmus/litmus-portal/graphql-server/utils" "github.com/sirupsen/logrus" + "go.mongodb.org/mongo-driver/mongo" ) type ReadinessAPIStatus struct { @@ -32,29 +31,29 @@ func contains(s []string, str string) bool { func ReadinessHandler(mclient *mongo.Client) gin.HandlerFunc { return func(c *gin.Context) { var ( - db_flag = "up" - col_flag = "up" + dbFlag = "up" + colFlag = "up" ) dbs, err := mongodb.Operator.ListDataBase(context.Background(), mclient) if err != nil { - db_flag = "down" + dbFlag = "down" } if !contains(dbs, "litmus") { - db_flag = "down" + dbFlag = "down" } cols, err := mongodb.Operator.ListCollection(context.Background(), mclient) if err != nil { - col_flag = "down" + colFlag = "down" } if !contains(cols, "gitops-collection") || !contains(cols, "server-config-collection") || !contains(cols, "workflow-collection") { - col_flag = "down" + colFlag = "down" } - var status = ReadinessAPIStatus{Collections: col_flag, DataBase: db_flag} + var status = ReadinessAPIStatus{Collections: colFlag, DataBase: dbFlag} statusByte, err := json.Marshal(status) if err != nil { logrus.Error(err) diff --git a/litmus-portal/graphql-server/pkg/handlers/status_handler.go b/litmus-portal/graphql-server/pkg/handlers/status_handler.go index 0c43ac1451f..788f6421522 100644 --- a/litmus-portal/graphql-server/pkg/handlers/status_handler.go +++ b/litmus-portal/graphql-server/pkg/handlers/status_handler.go @@ -2,9 +2,9 @@ package handlers import ( "encoding/json" - "github.com/gin-gonic/gin" "net/http" + "github.com/gin-gonic/gin" "github.com/litmuschaos/litmus/litmus-portal/graphql-server/utils" "github.com/sirupsen/logrus" ) diff --git a/litmus-portal/graphql-server/pkg/myhub/myhub.go b/litmus-portal/graphql-server/pkg/myhub/myhub.go index 027c61ed1a2..4b3b93bfcce 100644 --- a/litmus-portal/graphql-server/pkg/myhub/myhub.go +++ b/litmus-portal/graphql-server/pkg/myhub/myhub.go @@ -4,7 +4,6 @@ import ( "context" "errors" "fmt" - "github.com/gin-gonic/gin" "io" "log" "os" @@ -12,15 +11,15 @@ import ( "strings" "time" + "github.com/gin-gonic/gin" "github.com/google/uuid" "github.com/jinzhu/copier" - "go.mongodb.org/mongo-driver/bson" - "github.com/litmuschaos/litmus/litmus-portal/graphql-server/graph/model" dbOperationsMyHub "github.com/litmuschaos/litmus/litmus-portal/graphql-server/pkg/database/mongodb/myhub" dbSchemaMyHub "github.com/litmuschaos/litmus/litmus-portal/graphql-server/pkg/database/mongodb/myhub" "github.com/litmuschaos/litmus/litmus-portal/graphql-server/pkg/myhub/handler" myHubOps "github.com/litmuschaos/litmus/litmus-portal/graphql-server/pkg/myhub/ops" + "go.mongodb.org/mongo-driver/bson" ) const ( diff --git a/litmus-portal/graphql-server/server.go b/litmus-portal/graphql-server/server.go index 1f7c7ede5d6..2e301b800e9 100644 --- a/litmus-portal/graphql-server/server.go +++ b/litmus-portal/graphql-server/server.go @@ -3,37 +3,32 @@ package main import ( "context" "fmt" - "github.com/gin-contrib/cors" - "github.com/gin-gonic/gin" "net" "net/http" "runtime" "strings" "time" - gitOpsHandler "github.com/litmuschaos/litmus/litmus-portal/graphql-server/pkg/gitops/handler" - - "github.com/litmuschaos/litmus/litmus-portal/graphql-server/pkg/projects" - - "github.com/litmuschaos/litmus/litmus-portal/graphql-server/pkg/cluster" - "github.com/litmuschaos/litmus/litmus-portal/graphql-server/utils" - - "github.com/kelseyhightower/envconfig" - "github.com/litmuschaos/litmus/litmus-portal/graphql-server/pkg/database/mongodb/config" - "github.com/99designs/gqlgen/graphql/handler" "github.com/99designs/gqlgen/graphql/handler/extension" "github.com/99designs/gqlgen/graphql/handler/transport" + "github.com/gin-contrib/cors" + "github.com/gin-gonic/gin" "github.com/gorilla/websocket" - "github.com/sirupsen/logrus" - + "github.com/kelseyhightower/envconfig" "github.com/litmuschaos/litmus/litmus-portal/graphql-server/graph" "github.com/litmuschaos/litmus/litmus-portal/graphql-server/graph/generated" "github.com/litmuschaos/litmus/litmus-portal/graphql-server/pkg/authorization" + "github.com/litmuschaos/litmus/litmus-portal/graphql-server/pkg/cluster" "github.com/litmuschaos/litmus/litmus-portal/graphql-server/pkg/database/mongodb" + "github.com/litmuschaos/litmus/litmus-portal/graphql-server/pkg/database/mongodb/config" + gitOpsHandler "github.com/litmuschaos/litmus/litmus-portal/graphql-server/pkg/gitops/handler" "github.com/litmuschaos/litmus/litmus-portal/graphql-server/pkg/handlers" "github.com/litmuschaos/litmus/litmus-portal/graphql-server/pkg/myhub" + "github.com/litmuschaos/litmus/litmus-portal/graphql-server/pkg/projects" pb "github.com/litmuschaos/litmus/litmus-portal/graphql-server/protos" + "github.com/litmuschaos/litmus/litmus-portal/graphql-server/utils" + "github.com/sirupsen/logrus" "google.golang.org/grpc" ) diff --git a/litmus-portal/graphql-server/utils/misc.go b/litmus-portal/graphql-server/utils/misc.go index adb4a5c7cd6..42045d38cce 100644 --- a/litmus-portal/graphql-server/utils/misc.go +++ b/litmus-portal/graphql-server/utils/misc.go @@ -3,10 +3,11 @@ package utils import ( "bytes" "encoding/base64" - "github.com/gin-gonic/gin" "math/rand" "strings" "unicode" + + "github.com/gin-gonic/gin" ) // WriteHeaders adds important headers to API responses From 26a1619f6b6156a7a08ab52f3ef31f0790eee08f Mon Sep 17 00:00:00 2001 From: namkyu1999 Date: Mon, 27 Mar 2023 16:40:36 +0900 Subject: [PATCH 03/11] fix: remove duplicated code Signed-off-by: namkyu1999 --- .../graphql-server/pkg/chaoshub/chaoshub.go | 19 ++++++++----------- 1 file changed, 8 insertions(+), 11 deletions(-) diff --git a/litmus-portal/graphql-server/pkg/chaoshub/chaoshub.go b/litmus-portal/graphql-server/pkg/chaoshub/chaoshub.go index 0e6f9a0b781..48808ce042e 100644 --- a/litmus-portal/graphql-server/pkg/chaoshub/chaoshub.go +++ b/litmus-portal/graphql-server/pkg/chaoshub/chaoshub.go @@ -521,25 +521,22 @@ var GetIconHandler = gin.HandlerFunc(func(c *gin.Context) { iconName = c.Param("IconName") img *os.File err error - responseStatusCode int + responseStatusCode = 200 ) if strings.ToLower(chartName) == "predefined" { img, err = os.Open("/tmp/version/" + projectID + "/" + hubName + "/workflows/icons/" + iconName) - responseStatusCode = 200 - if err != nil { - responseStatusCode = 500 - fmt.Fprint(c.Writer, "icon cannot be fetched, err : "+err.Error()) - } } else { img, err = os.Open("/tmp/version/" + projectID + "/" + hubName + "/charts/" + chartName + "/icons/" + iconName) - responseStatusCode = 200 - if err != nil { - responseStatusCode = 500 - fmt.Fprint(c.Writer, "icon cannot be fetched, err : "+err.Error()) - } } + + if err != nil { + responseStatusCode = 500 + fmt.Fprint(c.Writer, "icon cannot be fetched, err : "+err.Error()) + } + defer img.Close() + c.Writer.Header().Set("Access-Control-Allow-Origin", "*") c.Writer.WriteHeader(responseStatusCode) c.Writer.Header().Set("Content-Type", "image/png") // <-- set the content-type header From 6c7738a52580aae4ef50d60ccc4e045157f6f51f Mon Sep 17 00:00:00 2001 From: namkyu1999 Date: Wed, 29 Mar 2023 15:08:13 +0900 Subject: [PATCH 04/11] fix: adopt go fmt Signed-off-by: namkyu1999 --- .../graph/generated/generated.go | 20 +++++++++---------- .../pkg/chaos-workflow/ops/operations.go | 2 +- .../graphql-server/pkg/chaoshub/chaoshub.go | 2 +- 3 files changed, 12 insertions(+), 12 deletions(-) diff --git a/litmus-portal/graphql-server/graph/generated/generated.go b/litmus-portal/graphql-server/graph/generated/generated.go index 574b891dc28..0c60c931eb1 100644 --- a/litmus-portal/graphql-server/graph/generated/generated.go +++ b/litmus-portal/graphql-server/graph/generated/generated.go @@ -4005,7 +4005,7 @@ func (ec *executionContext) introspectType(name string) (*introspection.Type, er } var sources = []*ast.Source{ - &ast.Source{Name: "graph/analytics.graphqls", Input: `input DSInput { + {Name: "graph/analytics.graphqls", Input: `input DSInput { dsID: String dsName: String! dsType: String! @@ -4485,7 +4485,7 @@ extend type Subscription { ): DashboardPromResponse! @authorized } `, BuiltIn: false}, - &ast.Source{Name: "graph/chaoshub.graphqls", Input: `enum AuthType { + {Name: "graph/chaoshub.graphqls", Input: `enum AuthType { BASIC NONE SSH @@ -5012,7 +5012,7 @@ extend type Mutation { """ deleteChaosHub(projectID: String!, hubID: String!): Boolean! @authorized }`, BuiltIn: false}, - &ast.Source{Name: "graph/cluster.graphqls", Input: `""" + {Name: "graph/cluster.graphqls", Input: `""" Defines the details for a cluster """ type Cluster { @@ -5340,7 +5340,7 @@ extend type Subscription { getKubeObject(request: KubeObjectRequest!): KubeObjectResponse! @authorized }`, BuiltIn: false}, - &ast.Source{Name: "graph/gitops.graphqls", Input: ` + {Name: "graph/gitops.graphqls", Input: ` """ Defines the SSHKey details """ @@ -5466,7 +5466,7 @@ extend type Mutation { """ updateGitOps(config: GitConfig!): Boolean! @authorized }`, BuiltIn: false}, - &ast.Source{Name: "graph/image_registry.graphqls", Input: `""" + {Name: "graph/image_registry.graphqls", Input: `""" Defines details for image registry """ type ImageRegistry { @@ -5603,7 +5603,7 @@ extend type Mutation { deleteImageRegistry(imageRegistryID: String!, projectID: String!): String! @authorized }`, BuiltIn: false}, - &ast.Source{Name: "graph/k8s.graphqls", Input: ` + {Name: "graph/k8s.graphqls", Input: ` """ Response received for querying Kubernetes Object """ @@ -5664,7 +5664,7 @@ input Workload { namespace: String! } `, BuiltIn: false}, - &ast.Source{Name: "graph/project.graphqls", Input: `enum Invitation { + {Name: "graph/project.graphqls", Input: `enum Invitation { Accepted Pending } @@ -5675,7 +5675,7 @@ enum MemberRole { Viewer } `, BuiltIn: false}, - &ast.Source{Name: "graph/usage.graphqls", Input: `""" + {Name: "graph/usage.graphqls", Input: `""" Defines details of workflow statistics """ type WorkflowStat { @@ -5826,7 +5826,7 @@ extend type Query { """ getUsageData(request: UsageDataRequest!): UsageDataResponse! @authorized }`, BuiltIn: false}, - &ast.Source{Name: "graph/workflow.graphqls", Input: `directive @authorized on FIELD_DEFINITION + {Name: "graph/workflow.graphqls", Input: `directive @authorized on FIELD_DEFINITION """ Defines the details of the weightages of each chaos experiment in the workflow @@ -6470,7 +6470,7 @@ type Subscription { """ getWorkflowEvents(projectID: String!): WorkflowRun! @authorized }`, BuiltIn: false}, - &ast.Source{Name: "graph/workflow_template.graphqls", Input: `""" + {Name: "graph/workflow_template.graphqls", Input: `""" Details for a workflow template """ type WorkflowTemplate { diff --git a/litmus-portal/graphql-server/pkg/chaos-workflow/ops/operations.go b/litmus-portal/graphql-server/pkg/chaos-workflow/ops/operations.go index 5aa9aaefdaf..caa5a9229c7 100644 --- a/litmus-portal/graphql-server/pkg/chaos-workflow/ops/operations.go +++ b/litmus-portal/graphql-server/pkg/chaos-workflow/ops/operations.go @@ -289,7 +289,7 @@ func ProcessCompletedWorkflowRun(execData types.ExecutionData, wfID string) (typ if value.ChaosExp == nil { continue } - for expName, _ := range weightMap { + for expName := range weightMap { if strings.Contains(value.ChaosExp.EngineName, expName) { experimentName = expName } diff --git a/litmus-portal/graphql-server/pkg/chaoshub/chaoshub.go b/litmus-portal/graphql-server/pkg/chaoshub/chaoshub.go index 48808ce042e..23f2947ac98 100644 --- a/litmus-portal/graphql-server/pkg/chaoshub/chaoshub.go +++ b/litmus-portal/graphql-server/pkg/chaoshub/chaoshub.go @@ -536,7 +536,7 @@ var GetIconHandler = gin.HandlerFunc(func(c *gin.Context) { } defer img.Close() - + c.Writer.Header().Set("Access-Control-Allow-Origin", "*") c.Writer.WriteHeader(responseStatusCode) c.Writer.Header().Set("Content-Type", "image/png") // <-- set the content-type header From acba37ce92747609c4e8056f93685457364b63f0 Mon Sep 17 00:00:00 2001 From: Namkyu Park <53862866+namkyu1999@users.noreply.github.com> Date: Wed, 29 Mar 2023 15:20:38 +0900 Subject: [PATCH 05/11] Move to using interface for better mocking at chaoshub package (#3933) * fix: Move to using interface for better mocking at chaoshub Signed-off-by: namkyu1999 * fix: delete operator interface and linting codes Signed-off-by: namkyu1999 * fix: change db instance to local variable Signed-off-by: namkyu1999 * fix: passing operator interface for better mocking Signed-off-by: namkyu1999 --------- Signed-off-by: namkyu1999 --- .../graph/chaoshub.resolvers.go | 32 +- .../graphql-server/graph/resolver.go | 13 +- .../pkg/chaoshub/models_factory.go | 18 + .../pkg/chaoshub/{chaoshub.go => service.go} | 501 +++++++++--------- .../database/mongodb/chaoshub/operations.go | 30 +- .../pkg/database/mongodb/chaoshub/schema.go | 5 +- .../pkg/database/mongodb/collection.go | 5 +- .../pkg/database/mongodb/init.go | 15 +- .../pkg/database/mongodb/operations.go | 20 +- .../pkg/projects/project_handler.go | 8 +- .../graphql-server/pkg/projects/types.go | 6 +- litmus-portal/graphql-server/server.go | 18 +- 12 files changed, 366 insertions(+), 305 deletions(-) create mode 100644 litmus-portal/graphql-server/pkg/chaoshub/models_factory.go rename litmus-portal/graphql-server/pkg/chaoshub/{chaoshub.go => service.go} (74%) diff --git a/litmus-portal/graphql-server/graph/chaoshub.resolvers.go b/litmus-portal/graphql-server/graph/chaoshub.resolvers.go index c36fb941cdd..71a5562bf93 100644 --- a/litmus-portal/graphql-server/graph/chaoshub.resolvers.go +++ b/litmus-portal/graphql-server/graph/chaoshub.resolvers.go @@ -8,19 +8,17 @@ import ( "github.com/litmuschaos/litmus/litmus-portal/graphql-server/graph/model" "github.com/litmuschaos/litmus/litmus-portal/graphql-server/pkg/authorization" - "github.com/litmuschaos/litmus/litmus-portal/graphql-server/pkg/chaoshub" chaosHubOps "github.com/litmuschaos/litmus/litmus-portal/graphql-server/pkg/chaoshub/ops" ) func (r *mutationResolver) AddChaosHub(ctx context.Context, request model.CreateChaosHubRequest) (*model.ChaosHub, error) { - err := authorization.ValidateRole(ctx, request.ProjectID, + if err := authorization.ValidateRole(ctx, request.ProjectID, authorization.MutationRbacRules[authorization.AddChaosHub], - model.InvitationAccepted.String()) - if err != nil { + model.InvitationAccepted.String()); err != nil { return nil, err } - return chaoshub.AddChaosHub(ctx, request) + return r.chaosHubService.AddChaosHub(ctx, request) } func (r *mutationResolver) AddRemoteChaosHub(ctx context.Context, request model.CreateRemoteChaosHub) (*model.ChaosHub, error) { @@ -31,7 +29,7 @@ func (r *mutationResolver) AddRemoteChaosHub(ctx context.Context, request model. return nil, err } - return chaoshub.AddRemoteChaosHub(ctx, request) + return r.chaosHubService.AddRemoteChaosHub(ctx, request) } func (r *mutationResolver) SaveChaosHub(ctx context.Context, request model.CreateChaosHubRequest) (*model.ChaosHub, error) { @@ -42,7 +40,7 @@ func (r *mutationResolver) SaveChaosHub(ctx context.Context, request model.Creat return nil, err } - return chaoshub.SaveChaosHub(ctx, request) + return r.chaosHubService.SaveChaosHub(ctx, request) } func (r *mutationResolver) SyncChaosHub(ctx context.Context, id string, projectID string) (string, error) { @@ -52,7 +50,7 @@ func (r *mutationResolver) SyncChaosHub(ctx context.Context, id string, projectI if err != nil { return "", err } - return chaoshub.SyncHub(ctx, id, projectID) + return r.chaosHubService.SyncHub(ctx, id, projectID) } func (r *mutationResolver) GenerateSSHKey(ctx context.Context) (*model.SSHKey, error) { @@ -74,7 +72,7 @@ func (r *mutationResolver) UpdateChaosHub(ctx context.Context, request model.Upd if err != nil { return nil, err } - return chaoshub.UpdateChaosHub(ctx, request) + return r.chaosHubService.UpdateChaosHub(ctx, request) } func (r *mutationResolver) DeleteChaosHub(ctx context.Context, projectID string, hubID string) (bool, error) { @@ -84,7 +82,7 @@ func (r *mutationResolver) DeleteChaosHub(ctx context.Context, projectID string, if err != nil { return false, err } - return chaoshub.DeleteChaosHub(ctx, hubID, projectID) + return r.chaosHubService.DeleteChaosHub(ctx, hubID, projectID) } func (r *queryResolver) ListCharts(ctx context.Context, hubName string, projectID string) ([]*model.Chart, error) { @@ -95,7 +93,7 @@ func (r *queryResolver) ListCharts(ctx context.Context, hubName string, projectI return nil, err } - return chaoshub.ListCharts(ctx, hubName, projectID) + return r.chaosHubService.ListCharts(ctx, hubName, projectID) } func (r *queryResolver) GetHubExperiment(ctx context.Context, request model.ExperimentRequest) (*model.Chart, error) { @@ -106,7 +104,7 @@ func (r *queryResolver) GetHubExperiment(ctx context.Context, request model.Expe return nil, err } - return chaoshub.GetHubExperiment(ctx, request) + return r.chaosHubService.GetHubExperiment(ctx, request) } func (r *queryResolver) ListHubStatus(ctx context.Context, projectID string) ([]*model.ChaosHubStatus, error) { @@ -117,7 +115,7 @@ func (r *queryResolver) ListHubStatus(ctx context.Context, projectID string) ([] return nil, err } - return chaoshub.ListHubStatus(ctx, projectID) + return r.chaosHubService.ListHubStatus(ctx, projectID) } func (r *queryResolver) GetYAMLData(ctx context.Context, request model.ExperimentRequest) (string, error) { @@ -128,7 +126,7 @@ func (r *queryResolver) GetYAMLData(ctx context.Context, request model.Experimen return "", err } - return chaoshub.GetYAMLData(request) + return r.chaosHubService.GetYAMLData(request) } func (r *queryResolver) GetExperimentDetails(ctx context.Context, request model.ExperimentRequest) (*model.ExperimentDetails, error) { @@ -138,7 +136,7 @@ func (r *queryResolver) GetExperimentDetails(ctx context.Context, request model. if err != nil { return nil, err } - return chaoshub.GetExperimentManifestDetails(ctx, request) + return r.chaosHubService.GetExperimentManifestDetails(ctx, request) } func (r *queryResolver) ListPredefinedWorkflows(ctx context.Context, hubName string, projectID string) ([]*model.PredefinedWorkflowList, error) { @@ -149,7 +147,7 @@ func (r *queryResolver) ListPredefinedWorkflows(ctx context.Context, hubName str return nil, err } - return chaoshub.ListPredefinedWorkflows(hubName, projectID) + return r.chaosHubService.ListPredefinedWorkflows(hubName, projectID) } func (r *queryResolver) GetPredefinedExperimentYaml(ctx context.Context, request model.ExperimentRequest) (string, error) { @@ -159,5 +157,5 @@ func (r *queryResolver) GetPredefinedExperimentYaml(ctx context.Context, request if err != nil { return "", err } - return chaoshub.GetPredefinedExperimentYAMLData(request) + return r.chaosHubService.GetPredefinedExperimentYAMLData(request) } diff --git a/litmus-portal/graphql-server/graph/resolver.go b/litmus-portal/graphql-server/graph/resolver.go index ff8a682eb4c..a035d6beca5 100644 --- a/litmus-portal/graphql-server/graph/resolver.go +++ b/litmus-portal/graphql-server/graph/resolver.go @@ -8,17 +8,22 @@ import ( "github.com/99designs/gqlgen/graphql" "github.com/litmuschaos/litmus/litmus-portal/graphql-server/graph/generated" "github.com/litmuschaos/litmus/litmus-portal/graphql-server/pkg/authorization" + "github.com/litmuschaos/litmus/litmus-portal/graphql-server/pkg/chaoshub" + "github.com/litmuschaos/litmus/litmus-portal/graphql-server/pkg/database/mongodb" ) // This file will not be regenerated automatically. // // It serves as dependency injection for your app, add any dependencies you require here. -type Resolver struct{} - -func NewConfig() generated.Config { +type Resolver struct { + chaosHubService chaoshub.Service +} - config := generated.Config{Resolvers: &Resolver{}} +func NewConfig(mongodbOperator mongodb.MongoOperator) generated.Config { + config := generated.Config{Resolvers: &Resolver{ + chaosHubService: chaoshub.NewService(mongodbOperator), + }} config.Directives.Authorized = func(ctx context.Context, obj interface{}, next graphql.Resolver) (interface{}, error) { token := ctx.Value(authorization.AuthKey).(string) user, err := authorization.UserValidateJWT(token) diff --git a/litmus-portal/graphql-server/pkg/chaoshub/models_factory.go b/litmus-portal/graphql-server/pkg/chaoshub/models_factory.go new file mode 100644 index 00000000000..de7ac954345 --- /dev/null +++ b/litmus-portal/graphql-server/pkg/chaoshub/models_factory.go @@ -0,0 +1,18 @@ +package chaoshub + +import "github.com/litmuschaos/litmus/litmus-portal/graphql-server/graph/model" + +func NewCloningInputFrom(chaosHub model.CreateChaosHubRequest) model.CloningInput { + return model.CloningInput{ + ProjectID: chaosHub.ProjectID, + RepoBranch: chaosHub.RepoBranch, + RepoURL: chaosHub.RepoURL, + HubName: chaosHub.HubName, + IsPrivate: chaosHub.IsPrivate, + UserName: chaosHub.UserName, + Password: chaosHub.Password, + AuthType: chaosHub.AuthType, + Token: chaosHub.Token, + SSHPrivateKey: chaosHub.SSHPrivateKey, + } +} diff --git a/litmus-portal/graphql-server/pkg/chaoshub/chaoshub.go b/litmus-portal/graphql-server/pkg/chaoshub/service.go similarity index 74% rename from litmus-portal/graphql-server/pkg/chaoshub/chaoshub.go rename to litmus-portal/graphql-server/pkg/chaoshub/service.go index 23f2947ac98..f9f5f160544 100644 --- a/litmus-portal/graphql-server/pkg/chaoshub/chaoshub.go +++ b/litmus-portal/graphql-server/pkg/chaoshub/service.go @@ -17,7 +17,7 @@ import ( "github.com/litmuschaos/litmus/litmus-portal/graphql-server/graph/model" "github.com/litmuschaos/litmus/litmus-portal/graphql-server/pkg/chaoshub/handler" chaosHubOps "github.com/litmuschaos/litmus/litmus-portal/graphql-server/pkg/chaoshub/ops" - dbOperationsChaosHub "github.com/litmuschaos/litmus/litmus-portal/graphql-server/pkg/database/mongodb/chaoshub" + "github.com/litmuschaos/litmus/litmus-portal/graphql-server/pkg/database/mongodb" dbSchemaChaosHub "github.com/litmuschaos/litmus/litmus-portal/graphql-server/pkg/database/mongodb/chaoshub" "go.mongodb.org/mongo-driver/bson" ) @@ -27,34 +27,46 @@ const ( defaultPath = "/tmp/version/" ) -// AddChaosHub is used for Adding a new ChaosHub -func AddChaosHub(ctx context.Context, chaosHub model.CreateChaosHubRequest) (*model.ChaosHub, error) { +type Service interface { + AddChaosHub(ctx context.Context, chaosHub model.CreateChaosHubRequest) (*model.ChaosHub, error) + AddRemoteChaosHub(ctx context.Context, chaosHub model.CreateRemoteChaosHub) (*model.ChaosHub, error) + SaveChaosHub(ctx context.Context, chaosHub model.CreateChaosHubRequest) (*model.ChaosHub, error) + SyncHub(ctx context.Context, hubID string, projectID string) (string, error) + UpdateChaosHub(ctx context.Context, chaosHub model.UpdateChaosHubRequest) (*model.ChaosHub, error) + DeleteChaosHub(ctx context.Context, hubID string, projectID string) (bool, error) + ListCharts(ctx context.Context, hubName string, projectID string) ([]*model.Chart, error) + GetHubExperiment(ctx context.Context, request model.ExperimentRequest) (*model.Chart, error) + ListHubStatus(ctx context.Context, projectID string) ([]*model.ChaosHubStatus, error) + GetYAMLData(request model.ExperimentRequest) (string, error) + GetExperimentManifestDetails(ctx context.Context, request model.ExperimentRequest) (*model.ExperimentDetails, error) + ListPredefinedWorkflows(hubName string, projectID string) ([]*model.PredefinedWorkflowList, error) + GetPredefinedExperimentYAMLData(request model.ExperimentRequest) (string, error) + IsChaosHubAvailable(ctx context.Context, hubName string, projectID string) (bool, error) + GetAllHubs(ctx context.Context) ([]*model.ChaosHub, error) + RecurringHubSync() +} - IsExist, err := IsChaosHubAvailable(ctx, chaosHub.HubName, chaosHub.ProjectID) - if err != nil { - return nil, err - } - if IsExist == true { - return nil, errors.New("HubName Already exists") +type chaosHubService struct { + chaosHubOperator *dbSchemaChaosHub.Operator +} + +func NewService(mongodbOperator mongodb.MongoOperator) Service { + return &chaosHubService{ + chaosHubOperator: dbSchemaChaosHub.NewChaosHubOperator(mongodbOperator), } +} - cloneHub := model.CloningInput{ - ProjectID: chaosHub.ProjectID, - RepoBranch: chaosHub.RepoBranch, - RepoURL: chaosHub.RepoURL, - HubName: chaosHub.HubName, - IsPrivate: chaosHub.IsPrivate, - UserName: chaosHub.UserName, - Password: chaosHub.Password, - AuthType: chaosHub.AuthType, - Token: chaosHub.Token, - SSHPrivateKey: chaosHub.SSHPrivateKey, +// AddChaosHub is used for Adding a new ChaosHub +func (c *chaosHubService) AddChaosHub(ctx context.Context, chaosHub model.CreateChaosHubRequest) (*model.ChaosHub, error) { + if IsExist, err := c.IsChaosHubAvailable(ctx, chaosHub.HubName, chaosHub.ProjectID); err != nil { + return nil, err + } else if IsExist == true { + return nil, errors.New("HubName Already exists") } - // Initialize a UID for new Hub. - uuid := uuid.New() + cloneHub := NewCloningInputFrom(chaosHub) newHub := &dbSchemaChaosHub.ChaosHub{ - ID: uuid.String(), + ID: uuid.New().String(), ProjectID: chaosHub.ProjectID, RepoURL: chaosHub.RepoURL, RepoBranch: chaosHub.RepoBranch, @@ -74,23 +86,21 @@ func AddChaosHub(ctx context.Context, chaosHub model.CreateChaosHubRequest) (*mo } // Adding the new hub into database with the given username. - err = dbOperationsChaosHub.CreateChaosHub(ctx, newHub) - if err != nil { + if err := c.chaosHubOperator.CreateChaosHub(ctx, newHub); err != nil { log.Print("ERROR", err) return nil, err } // Cloning the repository at a path from chaoshub link structure. - err = chaosHubOps.GitClone(cloneHub) - if err != nil { + if err := chaosHubOps.GitClone(cloneHub); err != nil { log.Print("Error", err) } return newHub.GetOutputChaosHub(), nil } -func AddRemoteChaosHub(ctx context.Context, chaosHub model.CreateRemoteChaosHub) (*model.ChaosHub, error) { - IsExist, err := IsChaosHubAvailable(ctx, chaosHub.HubName, chaosHub.ProjectID) +func (c *chaosHubService) AddRemoteChaosHub(ctx context.Context, chaosHub model.CreateRemoteChaosHub) (*model.ChaosHub, error) { + IsExist, err := c.IsChaosHubAvailable(ctx, chaosHub.HubName, chaosHub.ProjectID) if err != nil { return nil, err } @@ -98,10 +108,8 @@ func AddRemoteChaosHub(ctx context.Context, chaosHub model.CreateRemoteChaosHub) return nil, errors.New("HubName Already exists") } - // Initialize a UID for new Hub. - uuid := uuid.New() newHub := &dbSchemaChaosHub.ChaosHub{ - ID: uuid.String(), + ID: uuid.New().String(), ProjectID: chaosHub.ProjectID, RepoURL: chaosHub.RepoURL, RepoBranch: "", @@ -116,7 +124,7 @@ func AddRemoteChaosHub(ctx context.Context, chaosHub model.CreateRemoteChaosHub) } // Adding the new hub into database with the given name. - err = dbSchemaChaosHub.CreateChaosHub(ctx, newHub) + err = c.chaosHubOperator.CreateChaosHub(ctx, newHub) if err != nil { log.Print("ERROR", err) return nil, err @@ -133,9 +141,9 @@ func AddRemoteChaosHub(ctx context.Context, chaosHub model.CreateRemoteChaosHub) } // SaveChaosHub is used for Adding a new ChaosHub -func SaveChaosHub(ctx context.Context, chaosHub model.CreateChaosHubRequest) (*model.ChaosHub, error) { +func (c *chaosHubService) SaveChaosHub(ctx context.Context, chaosHub model.CreateChaosHubRequest) (*model.ChaosHub, error) { - IsExist, err := IsChaosHubAvailable(ctx, chaosHub.HubName, chaosHub.ProjectID) + IsExist, err := c.IsChaosHubAvailable(ctx, chaosHub.HubName, chaosHub.ProjectID) if err != nil { return nil, err } @@ -165,7 +173,7 @@ func SaveChaosHub(ctx context.Context, chaosHub model.CreateChaosHubRequest) (*m } // Adding the new hub into database with the given username without cloning. - err = dbOperationsChaosHub.CreateChaosHub(ctx, newHub) + err = c.chaosHubOperator.CreateChaosHub(ctx, newHub) if err != nil { log.Print("ERROR", err) return nil, err @@ -174,120 +182,9 @@ func SaveChaosHub(ctx context.Context, chaosHub model.CreateChaosHubRequest) (*m return newHub.GetOutputChaosHub(), nil } -// ListHubStatus returns the array of hubdetails with their current status. -func ListHubStatus(ctx context.Context, projectID string) ([]*model.ChaosHubStatus, error) { - - allHubs, err := dbOperationsChaosHub.GetChaosHubByProjectID(ctx, projectID) - if err != nil { - return nil, err - } - var hubDetails []*model.ChaosHubStatus - var isConfirmed bool - for _, hub := range allHubs { - sum := 0 - chartsInput := model.CloningInput{ - HubName: hub.HubName, - ProjectID: hub.ProjectID, - RepoURL: hub.RepoURL, - RepoBranch: hub.RepoBranch, - } - ChartsPath := handler.GetChartsPath(chartsInput) - ChartData, err := handler.GetChartsData(ChartsPath) - if err != nil { - isConfirmed = false - sum = 0 - } else { - isConfirmed = true - for _, chart := range ChartData { - sum = sum + len(chart.Spec.Experiments) - } - } - hubDetail := &model.ChaosHubStatus{ - IsAvailable: isConfirmed, - ID: hub.ID, - RepoURL: hub.RepoURL, - HubName: hub.HubName, - RepoBranch: hub.RepoBranch, - IsPrivate: hub.IsPrivate, - AuthType: model.AuthType(hub.AuthType), - HubType: model.HubType(hub.HubType), - Token: hub.Token, - UserName: hub.UserName, - Password: hub.Password, - SSHPrivateKey: hub.SSHPrivateKey, - SSHPublicKey: hub.SSHPublicKey, - IsRemoved: hub.IsRemoved, - LastSyncedAt: hub.LastSyncedAt, - TotalExp: strconv.Itoa(sum), - } - hubDetails = append(hubDetails, hubDetail) - } - return hubDetails, nil - -} - -// IsChaosHubAvailable is used for checking if hub already exist or not -func IsChaosHubAvailable(ctx context.Context, hubName string, projectID string) (bool, error) { - chaosHubs, err := dbOperationsChaosHub.GetChaosHubByProjectID(ctx, projectID) - if err != nil { - return true, err - } - - for _, n := range chaosHubs { - if n.HubName == hubName { - return true, nil - } - } - return false, nil -} - -// ListCharts is responsible for getting the charts details -func ListCharts(ctx context.Context, hubName string, projectID string) ([]*model.Chart, error) { - - chartsInput := model.CloningInput{} - chaosHubs, err := dbOperationsChaosHub.GetChaosHubByProjectID(ctx, projectID) - if err != nil { - return nil, err - } - for _, n := range chaosHubs { - if n.HubName == hubName { - chartsInput = model.CloningInput{ - HubName: hubName, - ProjectID: projectID, - RepoURL: n.RepoURL, - RepoBranch: n.RepoBranch, - } - } - } - - ChartsPath := handler.GetChartsPath(chartsInput) - ChartsData, err := handler.GetChartsData(ChartsPath) - if err != nil { - return nil, err - } - - return ChartsData, nil -} - -// GetHubExperiment is used for getting details of chartserviceversion.yaml. -func GetHubExperiment(ctx context.Context, request model.ExperimentRequest) (*model.Chart, error) { - var ExperimentPath string - - if strings.ToLower(*request.FileType) != "csv" { - return nil, errors.New("invalid file type") - } - ExperimentPath = handler.GetCSVData(request) - - ExperimentData, err := handler.GetExperimentData(ExperimentPath) - if err != nil { - return nil, err - } - return ExperimentData, nil -} - // SyncHub is used for syncing the hub again if some not present or some error happens. -func SyncHub(ctx context.Context, hubID string, projectID string) (string, error) { - chaosHub, err := dbOperationsChaosHub.GetHubByID(ctx, hubID, projectID) +func (c *chaosHubService) SyncHub(ctx context.Context, hubID string, projectID string) (string, error) { + chaosHub, err := c.chaosHubOperator.GetHubByID(ctx, hubID, projectID) if err != nil { return "", err } @@ -321,7 +218,7 @@ func SyncHub(ctx context.Context, hubID string, projectID string) (string, error } } // Updating the last_synced_at time using hubID - err = dbOperationsChaosHub.UpdateChaosHub(ctx, query, update) + err = c.chaosHubOperator.UpdateChaosHub(ctx, query, update) if err != nil { log.Print("ERROR", err) return "", err @@ -329,88 +226,7 @@ func SyncHub(ctx context.Context, hubID string, projectID string) (string, error return "Successfully synced ChaosHub", nil } -// GetYAMLData is responsible for sending the experiment/engine.yaml for a given experiment. -func GetYAMLData(request model.ExperimentRequest) (string, error) { - if strings.ToLower(*request.FileType) == "csv" || strings.ToLower(*request.FileType) == "workflow" { - return "", errors.New("invalid file type") - } - YAMLPath := handler.GetExperimentYAMLPath(request) - YAMLData, err := handler.ReadExperimentYAMLFile(YAMLPath) - if err != nil { - return "", err - } - return YAMLData, nil -} - -// GetPredefinedExperimentYAMLData is responsible for sending the workflow.yaml for a given pre-defined workflow. -func GetPredefinedExperimentYAMLData(request model.ExperimentRequest) (string, error) { - var YAMLPath string - if request.FileType == nil { - return "", errors.New("provide a valid filetype") - } - if strings.ToLower(*request.FileType) != "workflow" { - return "", errors.New("invalid file type") - } - if strings.ToLower(request.ChartName) == "predefined" && strings.ToLower(*request.FileType) == "workflow" { - YAMLPath = handler.GetPredefinedExperimentManifest(request) - } - YAMLData, err := handler.ReadExperimentYAMLFile(YAMLPath) - if err != nil { - return "", err - } - return YAMLData, nil -} - -// GetExperimentManifestDetails is used to send the ChaosEngine and ChaosExperiment YAMLs -func GetExperimentManifestDetails(ctx context.Context, request model.ExperimentRequest) (*model.ExperimentDetails, error) { - - engineType := model.FileTypeEngine - experimentType := model.FileTypeExperiment - - engineData, err := GetYAMLData(model.ExperimentRequest{ - ProjectID: request.ProjectID, - ChartName: request.ChartName, - ExperimentName: request.ExperimentName, - HubName: request.HubName, - FileType: (*string)(&engineType), - }) - if err != nil { - engineData = "" - } - experimentData, err := GetYAMLData(model.ExperimentRequest{ - ProjectID: request.ProjectID, - ChartName: request.ChartName, - ExperimentName: request.ExperimentName, - HubName: request.HubName, - FileType: (*string)(&experimentType), - }) - if err != nil { - experimentData = "" - } - experimentDetails := &model.ExperimentDetails{ - EngineDetails: engineData, - ExperimentDetails: experimentData, - } - return experimentDetails, nil -} - -// GetAllHubs ... -func GetAllHubs(ctx context.Context) ([]*model.ChaosHub, error) { - - chaosHubs, err := dbOperationsChaosHub.GetHubs(ctx) - if err != nil { - return nil, err - } - - var outputChaosHubs []*model.ChaosHub - for _, chaosHub := range chaosHubs { - outputChaosHubs = append(outputChaosHubs, chaosHub.GetOutputChaosHub()) - } - - return outputChaosHubs, nil -} - -func UpdateChaosHub(ctx context.Context, chaosHub model.UpdateChaosHubRequest) (*model.ChaosHub, error) { +func (c *chaosHubService) UpdateChaosHub(ctx context.Context, chaosHub model.UpdateChaosHubRequest) (*model.ChaosHub, error) { cloneHub := model.CloningInput{ ProjectID: chaosHub.ProjectID, @@ -425,7 +241,7 @@ func UpdateChaosHub(ctx context.Context, chaosHub model.UpdateChaosHubRequest) ( SSHPrivateKey: chaosHub.SSHPrivateKey, } - prevChaosHub, err := dbOperationsChaosHub.GetHubByID(ctx, chaosHub.ID, chaosHub.ProjectID) + prevChaosHub, err := c.chaosHubOperator.GetHubByID(ctx, chaosHub.ID, chaosHub.ProjectID) if err != nil { return nil, err } @@ -474,7 +290,7 @@ func UpdateChaosHub(ctx context.Context, chaosHub model.UpdateChaosHubRequest) ( {"SSHPrivateKey", chaosHub.SSHPrivateKey}, {"SSHPublicKey", chaosHub.SSHPublicKey}, {"updated_at", time}}}} // Updating the new hub into database with the given username. - err = dbOperationsChaosHub.UpdateChaosHub(ctx, query, update) + err = c.chaosHubOperator.UpdateChaosHub(ctx, query, update) if err != nil { log.Print("ERROR", err) return nil, err @@ -488,8 +304,8 @@ func UpdateChaosHub(ctx context.Context, chaosHub model.UpdateChaosHubRequest) ( return &newChaosHub, nil } -func DeleteChaosHub(ctx context.Context, hubID string, projectID string) (bool, error) { - chaosHub, err := dbOperationsChaosHub.GetHubByID(ctx, hubID, projectID) +func (c *chaosHubService) DeleteChaosHub(ctx context.Context, hubID string, projectID string) (bool, error) { + chaosHub, err := c.chaosHubOperator.GetHubByID(ctx, hubID, projectID) if err != nil { log.Print("ERROR", err) return false, err @@ -497,7 +313,7 @@ func DeleteChaosHub(ctx context.Context, hubID string, projectID string) (bool, query := bson.D{{"chaoshub_id", hubID}, {"project_id", projectID}} update := bson.D{{"$set", bson.D{{"IsRemoved", true}, {"updated_at", strconv.FormatInt(time.Now().Unix(), 10)}}}} - err = dbOperationsChaosHub.UpdateChaosHub(ctx, query, update) + err = c.chaosHubOperator.UpdateChaosHub(ctx, query, update) if err != nil { log.Print("ERROR", err) return false, err @@ -512,6 +328,205 @@ func DeleteChaosHub(ctx context.Context, hubID string, projectID string) (bool, return true, nil } +// ListCharts is responsible for getting the charts details +func (c *chaosHubService) ListCharts(ctx context.Context, hubName string, projectID string) ([]*model.Chart, error) { + + chartsInput := model.CloningInput{} + chaosHubs, err := c.chaosHubOperator.GetChaosHubByProjectID(ctx, projectID) + if err != nil { + return nil, err + } + for _, n := range chaosHubs { + if n.HubName == hubName { + chartsInput = model.CloningInput{ + HubName: hubName, + ProjectID: projectID, + RepoURL: n.RepoURL, + RepoBranch: n.RepoBranch, + } + } + } + + ChartsPath := handler.GetChartsPath(chartsInput) + ChartsData, err := handler.GetChartsData(ChartsPath) + if err != nil { + return nil, err + } + + return ChartsData, nil +} + +// GetHubExperiment is used for getting details of chartserviceversion.yaml. +func (c *chaosHubService) GetHubExperiment(ctx context.Context, request model.ExperimentRequest) (*model.Chart, error) { + var ExperimentPath string + + if strings.ToLower(*request.FileType) != "csv" { + return nil, errors.New("invalid file type") + } + ExperimentPath = handler.GetCSVData(request) + + ExperimentData, err := handler.GetExperimentData(ExperimentPath) + if err != nil { + return nil, err + } + return ExperimentData, nil +} + +// ListHubStatus returns the array of hubdetails with their current status. +func (c *chaosHubService) ListHubStatus(ctx context.Context, projectID string) ([]*model.ChaosHubStatus, error) { + + allHubs, err := c.chaosHubOperator.GetChaosHubByProjectID(ctx, projectID) + if err != nil { + return nil, err + } + var hubDetails []*model.ChaosHubStatus + var isConfirmed bool + for _, hub := range allHubs { + sum := 0 + chartsInput := model.CloningInput{ + HubName: hub.HubName, + ProjectID: hub.ProjectID, + RepoURL: hub.RepoURL, + RepoBranch: hub.RepoBranch, + } + ChartsPath := handler.GetChartsPath(chartsInput) + ChartData, err := handler.GetChartsData(ChartsPath) + if err != nil { + isConfirmed = false + sum = 0 + } else { + isConfirmed = true + for _, chart := range ChartData { + sum = sum + len(chart.Spec.Experiments) + } + } + hubDetail := &model.ChaosHubStatus{ + IsAvailable: isConfirmed, + ID: hub.ID, + RepoURL: hub.RepoURL, + HubName: hub.HubName, + RepoBranch: hub.RepoBranch, + IsPrivate: hub.IsPrivate, + AuthType: model.AuthType(hub.AuthType), + HubType: model.HubType(hub.HubType), + Token: hub.Token, + UserName: hub.UserName, + Password: hub.Password, + SSHPrivateKey: hub.SSHPrivateKey, + SSHPublicKey: hub.SSHPublicKey, + IsRemoved: hub.IsRemoved, + LastSyncedAt: hub.LastSyncedAt, + TotalExp: strconv.Itoa(sum), + } + hubDetails = append(hubDetails, hubDetail) + } + return hubDetails, nil +} + +// GetYAMLData is responsible for sending the experiment/engine.yaml for a given experiment. +func (c *chaosHubService) GetYAMLData(request model.ExperimentRequest) (string, error) { + if strings.ToLower(*request.FileType) == "csv" || strings.ToLower(*request.FileType) == "workflow" { + return "", errors.New("invalid file type") + } + YAMLPath := handler.GetExperimentYAMLPath(request) + YAMLData, err := handler.ReadExperimentYAMLFile(YAMLPath) + if err != nil { + return "", err + } + return YAMLData, nil +} + +// GetExperimentManifestDetails is used to send the ChaosEngine and ChaosExperiment YAMLs +func (c *chaosHubService) GetExperimentManifestDetails(ctx context.Context, request model.ExperimentRequest) (*model.ExperimentDetails, error) { + + engineType := model.FileTypeEngine + experimentType := model.FileTypeExperiment + + engineData, err := c.GetYAMLData(model.ExperimentRequest{ + ProjectID: request.ProjectID, + ChartName: request.ChartName, + ExperimentName: request.ExperimentName, + HubName: request.HubName, + FileType: (*string)(&engineType), + }) + if err != nil { + engineData = "" + } + experimentData, err := c.GetYAMLData(model.ExperimentRequest{ + ProjectID: request.ProjectID, + ChartName: request.ChartName, + ExperimentName: request.ExperimentName, + HubName: request.HubName, + FileType: (*string)(&experimentType), + }) + if err != nil { + experimentData = "" + } + experimentDetails := &model.ExperimentDetails{ + EngineDetails: engineData, + ExperimentDetails: experimentData, + } + return experimentDetails, nil +} + +func (c *chaosHubService) ListPredefinedWorkflows(hubName string, projectID string) ([]*model.PredefinedWorkflowList, error) { + workflowsList, err := handler.ListPredefinedWorkflowDetails(hubName, projectID) + if err != nil { + return nil, err + } + return workflowsList, nil +} + +// GetPredefinedExperimentYAMLData is responsible for sending the workflow.yaml for a given pre-defined workflow. +func (c *chaosHubService) GetPredefinedExperimentYAMLData(request model.ExperimentRequest) (string, error) { + var YAMLPath string + if request.FileType == nil { + return "", errors.New("provide a valid filetype") + } + if strings.ToLower(*request.FileType) != "workflow" { + return "", errors.New("invalid file type") + } + if strings.ToLower(request.ChartName) == "predefined" && strings.ToLower(*request.FileType) == "workflow" { + YAMLPath = handler.GetPredefinedExperimentManifest(request) + } + YAMLData, err := handler.ReadExperimentYAMLFile(YAMLPath) + if err != nil { + return "", err + } + return YAMLData, nil +} + +// IsChaosHubAvailable is used for checking if hub already exist or not +func (c *chaosHubService) IsChaosHubAvailable(ctx context.Context, hubName string, projectID string) (bool, error) { + chaosHubs, err := c.chaosHubOperator.GetChaosHubByProjectID(ctx, projectID) + if err != nil { + return true, err + } + + for _, n := range chaosHubs { + if n.HubName == hubName { + return true, nil + } + } + return false, nil +} + +// GetAllHubs ... +func (c *chaosHubService) GetAllHubs(ctx context.Context) ([]*model.ChaosHub, error) { + + chaosHubs, err := c.chaosHubOperator.GetHubs(ctx) + if err != nil { + return nil, err + } + + var outputChaosHubs []*model.ChaosHub + for _, chaosHub := range chaosHubs { + outputChaosHubs = append(outputChaosHubs, chaosHub.GetOutputChaosHub()) + } + + return outputChaosHubs, nil +} + // GetIconHandler ... var GetIconHandler = gin.HandlerFunc(func(c *gin.Context) { var ( @@ -544,10 +559,10 @@ var GetIconHandler = gin.HandlerFunc(func(c *gin.Context) { }) // RecurringHubSync is used for syncing -func RecurringHubSync() { +func (c *chaosHubService) RecurringHubSync() { for { // Started Syncing of hubs - chaosHubs, _ := GetAllHubs(nil) + chaosHubs, _ := c.GetAllHubs(nil) for _, chaosHub := range chaosHubs { if !chaosHub.IsRemoved { @@ -575,11 +590,3 @@ func RecurringHubSync() { time.Sleep(timeInterval) } } - -func ListPredefinedWorkflows(hubName string, projectID string) ([]*model.PredefinedWorkflowList, error) { - workflowsList, err := handler.ListPredefinedWorkflowDetails(hubName, projectID) - if err != nil { - return nil, err - } - return workflowsList, nil -} diff --git a/litmus-portal/graphql-server/pkg/database/mongodb/chaoshub/operations.go b/litmus-portal/graphql-server/pkg/database/mongodb/chaoshub/operations.go index 784054e55fe..541932c14f0 100644 --- a/litmus-portal/graphql-server/pkg/database/mongodb/chaoshub/operations.go +++ b/litmus-portal/graphql-server/pkg/database/mongodb/chaoshub/operations.go @@ -9,9 +9,19 @@ import ( "go.mongodb.org/mongo-driver/bson" ) +type Operator struct { + operator mongodb.MongoOperator +} + +func NewChaosHubOperator(mongodbOperator mongodb.MongoOperator) *Operator { + return &Operator{ + operator: mongodbOperator, + } +} + // CreateChaosHub creates a private chaosHub for the user in the database -func CreateChaosHub(ctx context.Context, chaosHub *ChaosHub) error { - err := mongodb.Operator.Create(ctx, mongodb.ChaosHubCollection, chaosHub) +func (c *Operator) CreateChaosHub(ctx context.Context, chaosHub *ChaosHub) error { + err := c.operator.Create(ctx, mongodb.ChaosHubCollection, chaosHub) if err != nil { log.Print("Error creating ChaosHub: ", err) return err @@ -20,12 +30,12 @@ func CreateChaosHub(ctx context.Context, chaosHub *ChaosHub) error { } // GetChaosHubByProjectID returns a private Hub based on the projectID -func GetChaosHubByProjectID(ctx context.Context, projectID string) ([]ChaosHub, error) { +func (c *Operator) GetChaosHubByProjectID(ctx context.Context, projectID string) ([]ChaosHub, error) { query := bson.D{ {"project_id", projectID}, {"IsRemoved", false}, } - results, err := mongodb.Operator.List(ctx, mongodb.ChaosHubCollection, query) + results, err := c.operator.List(ctx, mongodb.ChaosHubCollection, query) if err != nil { log.Print("ERROR GETTING HUBS : ", err) return []ChaosHub{}, err @@ -40,9 +50,9 @@ func GetChaosHubByProjectID(ctx context.Context, projectID string) ([]ChaosHub, } // GetHubs lists all the chaosHubs that are present -func GetHubs(ctx context.Context) ([]ChaosHub, error) { +func (c *Operator) GetHubs(ctx context.Context) ([]ChaosHub, error) { query := bson.D{{}} - results, err := mongodb.Operator.List(ctx, mongodb.ChaosHubCollection, query) + results, err := c.operator.List(ctx, mongodb.ChaosHubCollection, query) if err != nil { log.Print("Error getting chaosHubs: ", err) return []ChaosHub{}, err @@ -57,9 +67,9 @@ func GetHubs(ctx context.Context) ([]ChaosHub, error) { } // GetHubByID returns a single chaosHub based on the hubID -func GetHubByID(ctx context.Context, hubID string, projectID string) (ChaosHub, error) { +func (c *Operator) GetHubByID(ctx context.Context, hubID string, projectID string) (ChaosHub, error) { var chaosHub ChaosHub - result, err := mongodb.Operator.Get(ctx, mongodb.ChaosHubCollection, bson.D{{"chaoshub_id", hubID}, { + result, err := c.operator.Get(ctx, mongodb.ChaosHubCollection, bson.D{{"chaoshub_id", hubID}, { "project_id", projectID, }}) err = result.Decode(&chaosHub) @@ -71,8 +81,8 @@ func GetHubByID(ctx context.Context, hubID string, projectID string) (ChaosHub, } // UpdateChaosHub updates the chaosHub -func UpdateChaosHub(ctx context.Context, query bson.D, update bson.D) error { - updateResult, err := mongodb.Operator.Update(ctx, mongodb.ChaosHubCollection, query, update) +func (c *Operator) UpdateChaosHub(ctx context.Context, query bson.D, update bson.D) error { + updateResult, err := c.operator.Update(ctx, mongodb.ChaosHubCollection, query, update) if err != nil { return err } diff --git a/litmus-portal/graphql-server/pkg/database/mongodb/chaoshub/schema.go b/litmus-portal/graphql-server/pkg/database/mongodb/chaoshub/schema.go index 6e7ebec930c..07717c3a4a7 100644 --- a/litmus-portal/graphql-server/pkg/database/mongodb/chaoshub/schema.go +++ b/litmus-portal/graphql-server/pkg/database/mongodb/chaoshub/schema.go @@ -1,6 +1,8 @@ package chaoshub -import "github.com/litmuschaos/litmus/litmus-portal/graphql-server/graph/model" +import ( + "github.com/litmuschaos/litmus/litmus-portal/graphql-server/graph/model" +) // ChaosHub ... type ChaosHub struct { @@ -25,7 +27,6 @@ type ChaosHub struct { // GetOutputChaosHub ... func (c *ChaosHub) GetOutputChaosHub() *model.ChaosHub { - return &model.ChaosHub{ ID: c.ID, ProjectID: c.ProjectID, diff --git a/litmus-portal/graphql-server/pkg/database/mongodb/collection.go b/litmus-portal/graphql-server/pkg/database/mongodb/collection.go index 4d3742adb7a..95ae044a034 100644 --- a/litmus-portal/graphql-server/pkg/database/mongodb/collection.go +++ b/litmus-portal/graphql-server/pkg/database/mongodb/collection.go @@ -7,7 +7,7 @@ import ( ) type GetCollectionInterface interface { - getCollection(collectionType int) (*mongo.Collection, error) + getCollection(mongoClient MongoInterface, collectionType int) (*mongo.Collection, error) } type GetCollectionStruct struct{} @@ -17,8 +17,7 @@ var ( ) // getCollection function returns the appropriate DB collection based on the collection value passed -func (g *GetCollectionStruct) getCollection(collectionType int) (*mongo.Collection, error) { - mongoClient := Client +func (g *GetCollectionStruct) getCollection(mongoClient MongoInterface, collectionType int) (*mongo.Collection, error) { switch collectionType { case ClusterCollection: return mongoClient.(*MongoClient).ClusterCollection, nil diff --git a/litmus-portal/graphql-server/pkg/database/mongodb/init.go b/litmus-portal/graphql-server/pkg/database/mongodb/init.go index 7be79eca091..ab10cc3d953 100644 --- a/litmus-portal/graphql-server/pkg/database/mongodb/init.go +++ b/litmus-portal/graphql-server/pkg/database/mongodb/init.go @@ -32,7 +32,6 @@ const ( // MongoInterface requires a MongoClient that implements the Initialize method to create the Mongo DB client // and a initAllCollection method to initialize all DB Collections type MongoInterface interface { - Initialize(client *mongo.Client) *MongoClient initAllCollection() } @@ -112,10 +111,16 @@ func MongoConnection() (*mongo.Client, error) { } // Initialize initializes database connection -func (m *MongoClient) Initialize(client *mongo.Client) *MongoClient { - m.Database = client.Database(dbName) - m.initAllCollection() - return m +func Initialize(client *mongo.Client) *MongoClient { + mongodbClient := &MongoClient{ + Database: client.Database(dbName), + } + mongodbClient.initAllCollection() + + // TODO: will be removed after the migration + Client = mongodbClient + + return mongodbClient } // initAllCollection initializes all the database collections diff --git a/litmus-portal/graphql-server/pkg/database/mongodb/operations.go b/litmus-portal/graphql-server/pkg/database/mongodb/operations.go index 863b50216d7..0c21fa03552 100644 --- a/litmus-portal/graphql-server/pkg/database/mongodb/operations.go +++ b/litmus-portal/graphql-server/pkg/database/mongodb/operations.go @@ -21,18 +21,26 @@ type MongoOperator interface { Delete(ctx context.Context, collectionType int, query bson.D, opts ...*options.DeleteOptions) (*mongo.DeleteResult, error) CountDocuments(ctx context.Context, collectionType int, query bson.D, opts ...*options.CountOptions) (int64, error) Aggregate(ctx context.Context, collectionType int, pipeline interface{}, opts ...*options.AggregateOptions) (*mongo.Cursor, error) - GetCollection(collectionType int) (*mongo.Collection, error) ListCollection(ctx context.Context, mclient *mongo.Client) ([]string, error) ListDataBase(ctx context.Context, mclient *mongo.Client) ([]string, error) } -type MongoOperations struct{} +type MongoOperations struct { + MongoClient *MongoClient +} var ( + // TODO: remove this when all packages shift to interface pattern // Operator contains all the CRUD operations of the mongo database - Operator MongoOperator = &MongoOperations{} + Operator MongoOperator ) +func NewMongoOperations(mongoClient *MongoClient) *MongoOperations { + return &MongoOperations{ + MongoClient: mongoClient, + } +} + // Create puts a document in the database func (m *MongoOperations) Create(ctx context.Context, collectionType int, document interface{}) error { collection, err := m.GetCollection(collectionType) @@ -117,12 +125,12 @@ func (m *MongoOperations) UpdateMany(ctx context.Context, collectionType int, qu // Replace changes a document with a new one in the database based on a query func (m *MongoOperations) Replace(ctx context.Context, collectionType int, query bson.D, replacement interface{}) (*mongo.UpdateResult, error) { var result *mongo.UpdateResult + // If the given item is not present then insert. + opts := options.Replace().SetUpsert(true) collection, err := m.GetCollection(collectionType) if err != nil { return result, err } - // If the given item is not present then insert. - opts := options.Replace().SetUpsert(true) result, err = collection.ReplaceOne(ctx, query, replacement, opts) if err != nil { return result, err @@ -172,7 +180,7 @@ func (m *MongoOperations) Aggregate(ctx context.Context, collectionType int, pip // GetCollection fetches the correct collection based on the collection type func (m *MongoOperations) GetCollection(collectionType int) (*mongo.Collection, error) { - return GetCollectionClient.getCollection(collectionType) + return GetCollectionClient.getCollection(m.MongoClient, collectionType) } func (m *MongoOperations) ListDataBase(ctx context.Context, mclient *mongo.Client) ([]string, error) { diff --git a/litmus-portal/graphql-server/pkg/projects/project_handler.go b/litmus-portal/graphql-server/pkg/projects/project_handler.go index c63e3aee7ea..d2cd997e931 100644 --- a/litmus-portal/graphql-server/pkg/projects/project_handler.go +++ b/litmus-portal/graphql-server/pkg/projects/project_handler.go @@ -6,6 +6,7 @@ import ( "log" "strings" + "github.com/litmuschaos/litmus/litmus-portal/graphql-server/pkg/database/mongodb" "github.com/litmuschaos/litmus/litmus-portal/graphql-server/utils" "google.golang.org/protobuf/types/known/wrapperspb" @@ -31,7 +32,7 @@ func (s *ProjectServer) InitializeProject(ctx context.Context, req *pb.ProjectIn } // ProjectInitializer initializes the project by creating instances for required stateful services - err := ProjectInitializer(ctx, req.ProjectID, req.Role) + err := ProjectInitializer(ctx, req.ProjectID, req.Role, s.Operator) if err != nil { return res, fmt.Errorf("failed to initialize project, %w", err) } else { @@ -40,7 +41,7 @@ func (s *ProjectServer) InitializeProject(ctx context.Context, req *pb.ProjectIn } // ProjectInitializer creates a default hub and default image registry for a new project -func ProjectInitializer(ctx context.Context, projectID string, role string) error { +func ProjectInitializer(ctx context.Context, projectID string, role string, operator mongodb.MongoOperator) error { var ( selfCluster = utils.Config.SelfAgent @@ -55,8 +56,9 @@ func ProjectInitializer(ctx context.Context, projectID string, role string) erro } log.Print("Cloning https://github.com/litmuschaos/chaos-charts") + //TODO: Remove goroutine after adding hub optimisations - go chaoshub.AddChaosHub(context.Background(), defaultHub) + go chaoshub.NewService(operator).AddChaosHub(context.Background(), defaultHub) _, err := imageRegistryOps.CreateImageRegistry(ctx, projectID, model.ImageRegistryInput{ IsDefault: bl_true, diff --git a/litmus-portal/graphql-server/pkg/projects/types.go b/litmus-portal/graphql-server/pkg/projects/types.go index 09ab36c0940..d1b2d164e7c 100644 --- a/litmus-portal/graphql-server/pkg/projects/types.go +++ b/litmus-portal/graphql-server/pkg/projects/types.go @@ -1,8 +1,12 @@ package projects -import pb "github.com/litmuschaos/litmus/litmus-portal/graphql-server/protos" +import ( + "github.com/litmuschaos/litmus/litmus-portal/graphql-server/pkg/database/mongodb" + pb "github.com/litmuschaos/litmus/litmus-portal/graphql-server/protos" +) // ProjectServer is used to implement project.ProjectServer type ProjectServer struct { pb.UnimplementedProjectServer + Operator mongodb.MongoOperator } diff --git a/litmus-portal/graphql-server/server.go b/litmus-portal/graphql-server/server.go index d03ba45cc34..a376f567967 100644 --- a/litmus-portal/graphql-server/server.go +++ b/litmus-portal/graphql-server/server.go @@ -77,15 +77,19 @@ func main() { logrus.Fatal(err) } - mongodb.Client = mongodb.Client.Initialize(client) + mongoClient := mongodb.Initialize(client) + + var mongodbOperator mongodb.MongoOperator = mongodb.NewMongoOperations(mongoClient) + // TODO: remove this when all packages shift to interface pattern + mongodb.Operator = mongodbOperator if err := validateVersion(); err != nil { logrus.Fatal(err) } - go startGRPCServer(utils.Config.RpcPort) // start GRPC server + go startGRPCServer(utils.Config.RpcPort, mongodbOperator) // start GRPC server - srv := handler.New(generated.NewExecutableSchema(graph.NewConfig())) + srv := handler.New(generated.NewExecutableSchema(graph.NewConfig(mongodbOperator))) srv.AddTransport(transport.POST{}) srv.AddTransport(transport.GET{}) srv.AddTransport(transport.Websocket{ @@ -123,8 +127,8 @@ func main() { gitOpsHandler.GitOpsSyncHandler(true) // sync all previous existing repos before start - go chaoshub.RecurringHubSync() // go routine for syncing hubs for all users - go gitOpsHandler.GitOpsSyncHandler(false) // routine to sync git repos for gitOps + go chaoshub.NewService(mongodbOperator).RecurringHubSync() // go routine for syncing hubs for all users + go gitOpsHandler.GitOpsSyncHandler(false) // routine to sync git repos for gitOps logrus.Printf("connect to http://localhost:%s/ for GraphQL playground", utils.Config.HttpPort) err = router.Run(":" + utils.Config.HttpPort) @@ -134,7 +138,7 @@ func main() { } // startGRPCServer initializes, registers services to and starts the gRPC server for RPC calls -func startGRPCServer(port string) { +func startGRPCServer(port string, mongodbOperator mongodb.MongoOperator) { lis, err := net.Listen("tcp", ":"+port) if err != nil { logrus.Fatal("failed to listen: %w", err) @@ -143,7 +147,7 @@ func startGRPCServer(port string) { grpcServer := grpc.NewServer() // Register services - pb.RegisterProjectServer(grpcServer, &projects.ProjectServer{}) + pb.RegisterProjectServer(grpcServer, &projects.ProjectServer{Operator: mongodbOperator}) logrus.Printf("GRPC server listening on %v", lis.Addr()) logrus.Fatal(grpcServer.Serve(lis)) From 34936056c342bd00b4a87f3d3776d9abe0bea66e Mon Sep 17 00:00:00 2001 From: namkyu1999 Date: Wed, 29 Mar 2023 15:27:52 +0900 Subject: [PATCH 06/11] fix: status code to constant variable Signed-off-by: namkyu1999 --- litmus-portal/graphql-server/pkg/chaoshub/service.go | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/litmus-portal/graphql-server/pkg/chaoshub/service.go b/litmus-portal/graphql-server/pkg/chaoshub/service.go index f9f5f160544..8830ec59514 100644 --- a/litmus-portal/graphql-server/pkg/chaoshub/service.go +++ b/litmus-portal/graphql-server/pkg/chaoshub/service.go @@ -6,6 +6,7 @@ import ( "fmt" "io" "log" + "net/http" "os" "strconv" "strings" @@ -536,7 +537,7 @@ var GetIconHandler = gin.HandlerFunc(func(c *gin.Context) { iconName = c.Param("IconName") img *os.File err error - responseStatusCode = 200 + responseStatusCode = http.StatusOK ) if strings.ToLower(chartName) == "predefined" { @@ -546,7 +547,7 @@ var GetIconHandler = gin.HandlerFunc(func(c *gin.Context) { } if err != nil { - responseStatusCode = 500 + responseStatusCode = http.StatusInternalServerError fmt.Fprint(c.Writer, "icon cannot be fetched, err : "+err.Error()) } From 9e9377e0c9f4ccb55876da107ba8c31a7f8bd577 Mon Sep 17 00:00:00 2001 From: namkyu1999 Date: Wed, 29 Mar 2023 15:40:49 +0900 Subject: [PATCH 07/11] fix: add logs when encounterd error Signed-off-by: namkyu1999 --- litmus-portal/graphql-server/pkg/handlers/readiness_handler.go | 2 ++ 1 file changed, 2 insertions(+) diff --git a/litmus-portal/graphql-server/pkg/handlers/readiness_handler.go b/litmus-portal/graphql-server/pkg/handlers/readiness_handler.go index a876969e66b..ed0fd5d1087 100644 --- a/litmus-portal/graphql-server/pkg/handlers/readiness_handler.go +++ b/litmus-portal/graphql-server/pkg/handlers/readiness_handler.go @@ -37,6 +37,7 @@ func ReadinessHandler(mclient *mongo.Client) gin.HandlerFunc { dbs, err := mongodb.Operator.ListDataBase(context.Background(), mclient) if err != nil { + logrus.Error(err) dbFlag = "down" } @@ -46,6 +47,7 @@ func ReadinessHandler(mclient *mongo.Client) gin.HandlerFunc { cols, err := mongodb.Operator.ListCollection(context.Background(), mclient) if err != nil { + logrus.Error(err) colFlag = "down" } From b5b0b28a13a70f7852ef8ce2426d79eebed7b9a6 Mon Sep 17 00:00:00 2001 From: namkyu1999 Date: Wed, 5 Apr 2023 14:33:36 +0900 Subject: [PATCH 08/11] fix: rename pkg name Signed-off-by: namkyu1999 --- .../graphql-server/pkg/gitops/handler/handler.go | 2 +- .../core_version_handler.go | 2 +- .../{handlers => graphql_server}/file_handler.go | 2 +- .../playground_handler.go | 2 +- .../readiness_handler.go | 2 +- .../{handlers => graphql_server}/request_logger.go | 2 +- .../{handlers => graphql_server}/status_handler.go | 2 +- litmus-portal/graphql-server/server.go | 14 +++++++------- 8 files changed, 14 insertions(+), 14 deletions(-) rename litmus-portal/graphql-server/pkg/{handlers => graphql_server}/core_version_handler.go (96%) rename litmus-portal/graphql-server/pkg/{handlers => graphql_server}/file_handler.go (96%) rename litmus-portal/graphql-server/pkg/{handlers => graphql_server}/playground_handler.go (93%) rename litmus-portal/graphql-server/pkg/{handlers => graphql_server}/readiness_handler.go (98%) rename litmus-portal/graphql-server/pkg/{handlers => graphql_server}/request_logger.go (97%) rename litmus-portal/graphql-server/pkg/{handlers => graphql_server}/status_handler.go (96%) diff --git a/litmus-portal/graphql-server/pkg/gitops/handler/handler.go b/litmus-portal/graphql-server/pkg/gitops/handler/handler.go index 4db76f36ada..7f83cc7d3d6 100644 --- a/litmus-portal/graphql-server/pkg/gitops/handler/handler.go +++ b/litmus-portal/graphql-server/pkg/gitops/handler/handler.go @@ -1,4 +1,4 @@ -// GQL handlers and other external functions to facilitate gitops +// GQL graphql_server and other external functions to facilitate gitops package handler import ( diff --git a/litmus-portal/graphql-server/pkg/handlers/core_version_handler.go b/litmus-portal/graphql-server/pkg/graphql_server/core_version_handler.go similarity index 96% rename from litmus-portal/graphql-server/pkg/handlers/core_version_handler.go rename to litmus-portal/graphql-server/pkg/graphql_server/core_version_handler.go index 2f908ff3daf..b5f6cdc67da 100644 --- a/litmus-portal/graphql-server/pkg/handlers/core_version_handler.go +++ b/litmus-portal/graphql-server/pkg/graphql_server/core_version_handler.go @@ -1,4 +1,4 @@ -package handlers +package graphql_server import ( "encoding/json" diff --git a/litmus-portal/graphql-server/pkg/handlers/file_handler.go b/litmus-portal/graphql-server/pkg/graphql_server/file_handler.go similarity index 96% rename from litmus-portal/graphql-server/pkg/handlers/file_handler.go rename to litmus-portal/graphql-server/pkg/graphql_server/file_handler.go index 4fd0e791557..53078c399ce 100644 --- a/litmus-portal/graphql-server/pkg/handlers/file_handler.go +++ b/litmus-portal/graphql-server/pkg/graphql_server/file_handler.go @@ -1,4 +1,4 @@ -package handlers +package graphql_server import ( "strings" diff --git a/litmus-portal/graphql-server/pkg/handlers/playground_handler.go b/litmus-portal/graphql-server/pkg/graphql_server/playground_handler.go similarity index 93% rename from litmus-portal/graphql-server/pkg/handlers/playground_handler.go rename to litmus-portal/graphql-server/pkg/graphql_server/playground_handler.go index fe3301c0d2b..f0e0907bc48 100644 --- a/litmus-portal/graphql-server/pkg/handlers/playground_handler.go +++ b/litmus-portal/graphql-server/pkg/graphql_server/playground_handler.go @@ -1,4 +1,4 @@ -package handlers +package graphql_server import ( "github.com/99designs/gqlgen/graphql/playground" diff --git a/litmus-portal/graphql-server/pkg/handlers/readiness_handler.go b/litmus-portal/graphql-server/pkg/graphql_server/readiness_handler.go similarity index 98% rename from litmus-portal/graphql-server/pkg/handlers/readiness_handler.go rename to litmus-portal/graphql-server/pkg/graphql_server/readiness_handler.go index ed0fd5d1087..d751e061c00 100644 --- a/litmus-portal/graphql-server/pkg/handlers/readiness_handler.go +++ b/litmus-portal/graphql-server/pkg/graphql_server/readiness_handler.go @@ -1,4 +1,4 @@ -package handlers +package graphql_server import ( "context" diff --git a/litmus-portal/graphql-server/pkg/handlers/request_logger.go b/litmus-portal/graphql-server/pkg/graphql_server/request_logger.go similarity index 97% rename from litmus-portal/graphql-server/pkg/handlers/request_logger.go rename to litmus-portal/graphql-server/pkg/graphql_server/request_logger.go index b18dac4912c..1411b98729d 100644 --- a/litmus-portal/graphql-server/pkg/handlers/request_logger.go +++ b/litmus-portal/graphql-server/pkg/graphql_server/request_logger.go @@ -1,4 +1,4 @@ -package handlers +package graphql_server import ( "net/http" diff --git a/litmus-portal/graphql-server/pkg/handlers/status_handler.go b/litmus-portal/graphql-server/pkg/graphql_server/status_handler.go similarity index 96% rename from litmus-portal/graphql-server/pkg/handlers/status_handler.go rename to litmus-portal/graphql-server/pkg/graphql_server/status_handler.go index 788f6421522..4a870a48fa5 100644 --- a/litmus-portal/graphql-server/pkg/handlers/status_handler.go +++ b/litmus-portal/graphql-server/pkg/graphql_server/status_handler.go @@ -1,4 +1,4 @@ -package handlers +package graphql_server import ( "encoding/json" diff --git a/litmus-portal/graphql-server/server.go b/litmus-portal/graphql-server/server.go index a376f567967..60136c6ea4b 100644 --- a/litmus-portal/graphql-server/server.go +++ b/litmus-portal/graphql-server/server.go @@ -24,7 +24,7 @@ import ( "github.com/litmuschaos/litmus/litmus-portal/graphql-server/pkg/database/mongodb" "github.com/litmuschaos/litmus/litmus-portal/graphql-server/pkg/database/mongodb/config" gitOpsHandler "github.com/litmuschaos/litmus/litmus-portal/graphql-server/pkg/gitops/handler" - "github.com/litmuschaos/litmus/litmus-portal/graphql-server/pkg/handlers" + "github.com/litmuschaos/litmus/litmus-portal/graphql-server/pkg/graphql_server" "github.com/litmuschaos/litmus/litmus-portal/graphql-server/pkg/projects" pb "github.com/litmuschaos/litmus/litmus-portal/graphql-server/protos" "github.com/litmuschaos/litmus/litmus-portal/graphql-server/utils" @@ -114,16 +114,16 @@ func main() { AllowCredentials: true, })) - //router.Use(handlers.LoggingMiddleware()) + //router.Use(graphql_server.LoggingMiddleware()) // routers - router.GET("/", handlers.PlaygroundHandler()) + router.GET("/", graphql_server.PlaygroundHandler()) router.Any("/query", authorization.Middleware(srv)) - router.GET("/readiness", handlers.ReadinessHandler(client)) + router.GET("/readiness", graphql_server.ReadinessHandler(client)) router.GET("/icon/:ProjectID/:HubName/:ChartName/:IconName", authorization.RestMiddlewareWithRole(chaoshub.GetIconHandler, nil)) - router.Any("/file/:key", handlers.FileHandler) - router.GET("/status", handlers.StatusHandler) - router.GET("/workflow_helper_image_version", handlers.WorkflowHelperImageVersionHandler) + router.Any("/file/:key", graphql_server.FileHandler) + router.GET("/status", graphql_server.StatusHandler) + router.GET("/workflow_helper_image_version", graphql_server.WorkflowHelperImageVersionHandler) gitOpsHandler.GitOpsSyncHandler(true) // sync all previous existing repos before start From c20456d2f6b82f6794dbf17552a686c4ed6f1632 Mon Sep 17 00:00:00 2001 From: namkyu1999 Date: Fri, 7 Apr 2023 16:02:46 +0900 Subject: [PATCH 09/11] fix: rename pkg, graphql_server to rest_handlers Signed-off-by: namkyu1999 --- .../core_version_handler.go | 2 +- .../file_handler.go | 2 +- .../playground_handler.go | 2 +- .../readiness_handler.go | 2 +- .../request_logger.go | 2 +- .../status_handler.go | 2 +- litmus-portal/graphql-server/server.go | 14 +++++++------- 7 files changed, 13 insertions(+), 13 deletions(-) rename litmus-portal/graphql-server/pkg/{graphql_server => rest_handlers}/core_version_handler.go (96%) rename litmus-portal/graphql-server/pkg/{graphql_server => rest_handlers}/file_handler.go (96%) rename litmus-portal/graphql-server/pkg/{graphql_server => rest_handlers}/playground_handler.go (93%) rename litmus-portal/graphql-server/pkg/{graphql_server => rest_handlers}/readiness_handler.go (98%) rename litmus-portal/graphql-server/pkg/{graphql_server => rest_handlers}/request_logger.go (97%) rename litmus-portal/graphql-server/pkg/{graphql_server => rest_handlers}/status_handler.go (96%) diff --git a/litmus-portal/graphql-server/pkg/graphql_server/core_version_handler.go b/litmus-portal/graphql-server/pkg/rest_handlers/core_version_handler.go similarity index 96% rename from litmus-portal/graphql-server/pkg/graphql_server/core_version_handler.go rename to litmus-portal/graphql-server/pkg/rest_handlers/core_version_handler.go index b5f6cdc67da..38e2a175780 100644 --- a/litmus-portal/graphql-server/pkg/graphql_server/core_version_handler.go +++ b/litmus-portal/graphql-server/pkg/rest_handlers/core_version_handler.go @@ -1,4 +1,4 @@ -package graphql_server +package rest_handlers import ( "encoding/json" diff --git a/litmus-portal/graphql-server/pkg/graphql_server/file_handler.go b/litmus-portal/graphql-server/pkg/rest_handlers/file_handler.go similarity index 96% rename from litmus-portal/graphql-server/pkg/graphql_server/file_handler.go rename to litmus-portal/graphql-server/pkg/rest_handlers/file_handler.go index 53078c399ce..b7f19f01fc1 100644 --- a/litmus-portal/graphql-server/pkg/graphql_server/file_handler.go +++ b/litmus-portal/graphql-server/pkg/rest_handlers/file_handler.go @@ -1,4 +1,4 @@ -package graphql_server +package rest_handlers import ( "strings" diff --git a/litmus-portal/graphql-server/pkg/graphql_server/playground_handler.go b/litmus-portal/graphql-server/pkg/rest_handlers/playground_handler.go similarity index 93% rename from litmus-portal/graphql-server/pkg/graphql_server/playground_handler.go rename to litmus-portal/graphql-server/pkg/rest_handlers/playground_handler.go index f0e0907bc48..2e5442a2293 100644 --- a/litmus-portal/graphql-server/pkg/graphql_server/playground_handler.go +++ b/litmus-portal/graphql-server/pkg/rest_handlers/playground_handler.go @@ -1,4 +1,4 @@ -package graphql_server +package rest_handlers import ( "github.com/99designs/gqlgen/graphql/playground" diff --git a/litmus-portal/graphql-server/pkg/graphql_server/readiness_handler.go b/litmus-portal/graphql-server/pkg/rest_handlers/readiness_handler.go similarity index 98% rename from litmus-portal/graphql-server/pkg/graphql_server/readiness_handler.go rename to litmus-portal/graphql-server/pkg/rest_handlers/readiness_handler.go index d751e061c00..55d98796003 100644 --- a/litmus-portal/graphql-server/pkg/graphql_server/readiness_handler.go +++ b/litmus-portal/graphql-server/pkg/rest_handlers/readiness_handler.go @@ -1,4 +1,4 @@ -package graphql_server +package rest_handlers import ( "context" diff --git a/litmus-portal/graphql-server/pkg/graphql_server/request_logger.go b/litmus-portal/graphql-server/pkg/rest_handlers/request_logger.go similarity index 97% rename from litmus-portal/graphql-server/pkg/graphql_server/request_logger.go rename to litmus-portal/graphql-server/pkg/rest_handlers/request_logger.go index 1411b98729d..6be1a6252d8 100644 --- a/litmus-portal/graphql-server/pkg/graphql_server/request_logger.go +++ b/litmus-portal/graphql-server/pkg/rest_handlers/request_logger.go @@ -1,4 +1,4 @@ -package graphql_server +package rest_handlers import ( "net/http" diff --git a/litmus-portal/graphql-server/pkg/graphql_server/status_handler.go b/litmus-portal/graphql-server/pkg/rest_handlers/status_handler.go similarity index 96% rename from litmus-portal/graphql-server/pkg/graphql_server/status_handler.go rename to litmus-portal/graphql-server/pkg/rest_handlers/status_handler.go index 4a870a48fa5..54d285afbb8 100644 --- a/litmus-portal/graphql-server/pkg/graphql_server/status_handler.go +++ b/litmus-portal/graphql-server/pkg/rest_handlers/status_handler.go @@ -1,4 +1,4 @@ -package graphql_server +package rest_handlers import ( "encoding/json" diff --git a/litmus-portal/graphql-server/server.go b/litmus-portal/graphql-server/server.go index 60136c6ea4b..008a80cae5a 100644 --- a/litmus-portal/graphql-server/server.go +++ b/litmus-portal/graphql-server/server.go @@ -24,8 +24,8 @@ import ( "github.com/litmuschaos/litmus/litmus-portal/graphql-server/pkg/database/mongodb" "github.com/litmuschaos/litmus/litmus-portal/graphql-server/pkg/database/mongodb/config" gitOpsHandler "github.com/litmuschaos/litmus/litmus-portal/graphql-server/pkg/gitops/handler" - "github.com/litmuschaos/litmus/litmus-portal/graphql-server/pkg/graphql_server" "github.com/litmuschaos/litmus/litmus-portal/graphql-server/pkg/projects" + "github.com/litmuschaos/litmus/litmus-portal/graphql-server/pkg/rest_handlers" pb "github.com/litmuschaos/litmus/litmus-portal/graphql-server/protos" "github.com/litmuschaos/litmus/litmus-portal/graphql-server/utils" "github.com/sirupsen/logrus" @@ -114,16 +114,16 @@ func main() { AllowCredentials: true, })) - //router.Use(graphql_server.LoggingMiddleware()) + //router.Use(rest_handlers.LoggingMiddleware()) // routers - router.GET("/", graphql_server.PlaygroundHandler()) + router.GET("/", rest_handlers.PlaygroundHandler()) router.Any("/query", authorization.Middleware(srv)) - router.GET("/readiness", graphql_server.ReadinessHandler(client)) + router.GET("/readiness", rest_handlers.ReadinessHandler(client)) router.GET("/icon/:ProjectID/:HubName/:ChartName/:IconName", authorization.RestMiddlewareWithRole(chaoshub.GetIconHandler, nil)) - router.Any("/file/:key", graphql_server.FileHandler) - router.GET("/status", graphql_server.StatusHandler) - router.GET("/workflow_helper_image_version", graphql_server.WorkflowHelperImageVersionHandler) + router.Any("/file/:key", rest_handlers.FileHandler) + router.GET("/status", rest_handlers.StatusHandler) + router.GET("/workflow_helper_image_version", rest_handlers.WorkflowHelperImageVersionHandler) gitOpsHandler.GitOpsSyncHandler(true) // sync all previous existing repos before start From 464cef0dd4b716871efb85dea4443244ebe89f70 Mon Sep 17 00:00:00 2001 From: namkyu1999 Date: Fri, 7 Apr 2023 16:37:39 +0900 Subject: [PATCH 10/11] fix: resolve codeql issue Signed-off-by: namkyu1999 --- .../graphql-server/pkg/chaoshub/service.go | 9 +++-- .../pkg/rest_handlers/core_version_handler.go | 1 + .../pkg/rest_handlers/request_logger.go | 37 +++++++++---------- 3 files changed, 23 insertions(+), 24 deletions(-) diff --git a/litmus-portal/graphql-server/pkg/chaoshub/service.go b/litmus-portal/graphql-server/pkg/chaoshub/service.go index 8830ec59514..b6254f655d7 100644 --- a/litmus-portal/graphql-server/pkg/chaoshub/service.go +++ b/litmus-portal/graphql-server/pkg/chaoshub/service.go @@ -530,11 +530,12 @@ func (c *chaosHubService) GetAllHubs(ctx context.Context) ([]*model.ChaosHub, er // GetIconHandler ... var GetIconHandler = gin.HandlerFunc(func(c *gin.Context) { + replacer := strings.NewReplacer("\\.", "", "/", "") var ( - projectID = c.Param("ProjectID") - hubName = c.Param("HubName") - chartName = c.Param("ChartName") - iconName = c.Param("IconName") + projectID = replacer.Replace(c.Param("ProjectID")) + hubName = replacer.Replace(c.Param("HubName")) + chartName = replacer.Replace(c.Param("ChartName")) + iconName = replacer.Replace(c.Param("IconName")) img *os.File err error responseStatusCode = http.StatusOK diff --git a/litmus-portal/graphql-server/pkg/rest_handlers/core_version_handler.go b/litmus-portal/graphql-server/pkg/rest_handlers/core_version_handler.go index 38e2a175780..69c714a2468 100644 --- a/litmus-portal/graphql-server/pkg/rest_handlers/core_version_handler.go +++ b/litmus-portal/graphql-server/pkg/rest_handlers/core_version_handler.go @@ -1,3 +1,4 @@ +// Package rest_handlers provides rest handlers package rest_handlers import ( diff --git a/litmus-portal/graphql-server/pkg/rest_handlers/request_logger.go b/litmus-portal/graphql-server/pkg/rest_handlers/request_logger.go index 6be1a6252d8..9e55f47cd95 100644 --- a/litmus-portal/graphql-server/pkg/rest_handlers/request_logger.go +++ b/litmus-portal/graphql-server/pkg/rest_handlers/request_logger.go @@ -2,10 +2,6 @@ package rest_handlers import ( "net/http" - "strings" - "time" - - "github.com/sirupsen/logrus" ) type responseWriter struct { @@ -34,19 +30,20 @@ func (rw *responseWriter) WriteHeader(code int) { return } -func LoggingMiddleware() func(http.Handler) http.Handler { - return func(next http.Handler) http.Handler { - fn := func(w http.ResponseWriter, r *http.Request) { - start := time.Now() - wrapped := wrapResponseWriter(w) - next.ServeHTTP(wrapped, r) - - escapedURL := strings.Replace(r.URL.EscapedPath(), "\n", "", -1) - escapedURL = strings.Replace(escapedURL, "\r", "", -1) - - logrus.Infof("status: %v, method: %v, path: %v, duration: %v", wrapped.status, r.Method, r.URL.EscapedPath(), time.Since(start)) - } - - return http.HandlerFunc(fn) - } -} +// not used now +//func LoggingMiddleware() func(http.Handler) http.Handler { +// return func(next http.Handler) http.Handler { +// fn := func(w http.ResponseWriter, r *http.Request) { +// start := time.Now() +// wrapped := wrapResponseWriter(w) +// next.ServeHTTP(wrapped, r) +// +// escapedURL := strings.Replace(r.URL.EscapedPath(), "\n", "", -1) +// escapedURL = strings.Replace(escapedURL, "\r", "", -1) +// +// logrus.Infof("status: %v, method: %v, path: %v, duration: %v", wrapped.status, r.Method, r.URL.EscapedPath(), time.Since(start)) +// } +// +// return http.HandlerFunc(fn) +// } +//} From 04842e5e5018fb3e00de2a66c53b84759c1b0257 Mon Sep 17 00:00:00 2001 From: namkyu1999 Date: Fri, 7 Apr 2023 18:14:57 +0900 Subject: [PATCH 11/11] fix: add replacer value Signed-off-by: namkyu1999 --- litmus-portal/graphql-server/pkg/chaoshub/service.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/litmus-portal/graphql-server/pkg/chaoshub/service.go b/litmus-portal/graphql-server/pkg/chaoshub/service.go index b6254f655d7..7181086f689 100644 --- a/litmus-portal/graphql-server/pkg/chaoshub/service.go +++ b/litmus-portal/graphql-server/pkg/chaoshub/service.go @@ -530,7 +530,7 @@ func (c *chaosHubService) GetAllHubs(ctx context.Context) ([]*model.ChaosHub, er // GetIconHandler ... var GetIconHandler = gin.HandlerFunc(func(c *gin.Context) { - replacer := strings.NewReplacer("\\.", "", "/", "") + replacer := strings.NewReplacer("../", "", "./", "", "/", "", "..", "") var ( projectID = replacer.Replace(c.Param("ProjectID")) hubName = replacer.Replace(c.Param("HubName"))