diff --git a/README.md b/README.md index 0a4c37b..d87b84a 100644 --- a/README.md +++ b/README.md @@ -15,26 +15,31 @@ make compile > List of command available ```bash - -backends string - Load balanced backends, use commas to separate - -configFile string - Only config filename.yaml default ngonx.yaml (default "ngonx.yaml") - -configPath string - Config path only not filename.yaml (default "pwd") - -genkey - Action for generate hash for protected routes - -lbPort int - Port to serve to run load balancing (default 3030) - -prevkey string - Action for save a previous hash for protected routes to validate JWT - -proxyPort int - Port to serve to run proxy - -setup - Create yaml file configuration - -type string - Main Service default is proxy (default "proxy") - -version - Display version and exit +ngonxctl -h +``` + +```bash +This is Ngonx ctl a proxy reverse inspired on nginx & traefik + +Usage: + ngonxctl [command] + +Available Commands: + completion generate the autocompletion script for the specified shell + help Help about any command + lb Run ngonx as a load balancer (round robin) + proxy Run ngonx as a reverse proxy + setup Create configuration file it`s doesn`t exist + static Run ngonx as a static web server + version Print the version number of ngonxctl + +Flags: + -f, --cfgfile string File setting.yml (default "ngonx.yaml") + -p, --cfgpath string Config path only (default "path/binary") + -h, --help help for ngonxctl + +Use "ngonxctl [command] --help" for more information about a command. + ``` > Start Proxy server first time @@ -42,37 +47,57 @@ make compile `genkey` command in true generate random secretkey and save on badgerdb on `badger.data` ```bash -./ngxctl -proxyPort 5000 -genkey true +./ngonxctl proxy -port 5000 -genkey true ``` `prevkey` command receive a custom secretkey and save this on badgerdb on `badger.data` ```bash -./ngxctl -proxyPort 5000 -prevkey +./ngonxctl proxy -port 5000 -prevkey ``` > Start Proxy server ```bash -./ngxctl -proxyPort 5001 +./ngonxctl proxy -port 5000 ``` > Start load balancer ```bash -./ngxctl -type lb --backends "http://localhost:5000,http://localhost:5001,http://localhost:5002" +./ngonxctl lb --backends "http://localhost:5000,http://localhost:5001,http://localhost:5002" ``` +> Start static files server -> Start API PoC service +```bash +./ngonxctl static +``` + +Metrics +----------- + +Currently ngonx use prometheus as a metric collector. The main service `proxy` expose for port 10000 on route `/metrics` ```bash -go run services/micro-a/api.go --port +curl http://localhost:10000/metrics ``` -> Start static files server + +Management API & Web(coming...) +----------- + +Currently ngonx use port 10001 for export a simple api to check all services + +```bash +curl http://localhost:10001/api/v1/mngt/ +``` + + + +> Start API PoC service ```bash -go run cmd/main.go -type static +go run services/micro-a/api.go --port ``` Install badger db on window if you don`t use CGO @@ -84,7 +109,7 @@ CGO_ENABLED=0 go get github.com/dgraph-io/badger/v3 ```bash -cd ssl +cd scripts chmod +x ./generate.sh @@ -133,10 +158,6 @@ certbot renew --- -Metrics ------------ - -Currently ngonx used prometheus for metric collector. The main service `proxy` expose for port 10000 on route `/metrics` BenchMarking ------------ diff --git a/cmd/cli/flags.go b/cmd/cli/flags.go new file mode 100644 index 0000000..5fac8dc --- /dev/null +++ b/cmd/cli/flags.go @@ -0,0 +1,23 @@ +package cli + +import ( + "os" + + "github.com/kenriortega/ngonx/pkg/config" +) + +var ( + // variables to store data for global usage + configFromYaml config.Config + cfgFile = "ngonx.yaml" + cfgPath, _ = os.Getwd() + errConfig error + + // flags + flagPort = "port" + flagServerList = "backends" + flagGenApiKey = "genkey" + flagPrevKey = "prevkey" + flagCfgFile = "cfgfile" + flagCfgPath = "cfgpath" +) diff --git a/cmd/cli/lb.go b/cmd/cli/lb.go index 168feaa..d48a1c3 100644 --- a/cmd/cli/lb.go +++ b/cmd/cli/lb.go @@ -10,12 +10,12 @@ import ( "strings" "time" - "github.com/kenriortega/ngonx/pkg/backoff" - "github.com/kenriortega/ngonx/pkg/logger" - domain "github.com/kenriortega/ngonx/internal/proxy/domain" handlers "github.com/kenriortega/ngonx/internal/proxy/handlers" + "github.com/kenriortega/ngonx/pkg/backoff" + "github.com/kenriortega/ngonx/pkg/logger" + "github.com/spf13/cobra" ) // MaxJitter will randomize over the full exponential backoff time @@ -24,62 +24,81 @@ const MaxJitter = 1.0 // NoJitter disables the use of jitter for randomizing the exponential backoff time const NoJitter = 0.0 -func StartLB(serverList string, port int) { - - if len(serverList) == 0 { - log.Fatal("Please provide one or more backends to load balance") - } - - // parse servers - tokens := strings.Split(serverList, ",") - for _, tok := range tokens { - serverUrl, err := url.Parse(tok) +var lbCmd = &cobra.Command{ + Use: "lb", + Short: "Run ngonx as a load balancer (round robin)", + Run: func(cmd *cobra.Command, args []string) { + port, err := cmd.Flags().GetInt(flagPort) if err != nil { logger.LogError(err.Error()) } + serverList, err := cmd.Flags().GetString(flagServerList) + if err != nil { + log.Fatalf(err.Error()) + } + if len(serverList) == 0 { + log.Fatal("Please provide one or more backends to load balance") + } + + // parse servers + tokens := strings.Split(serverList, ",") + for _, tok := range tokens { + serverUrl, err := url.Parse(tok) + if err != nil { + logger.LogError(err.Error()) + } + + proxy := httputil.NewSingleHostReverseProxy(serverUrl) + proxy.ErrorHandler = func(writer http.ResponseWriter, request *http.Request, e error) { + logger.LogInfo(fmt.Sprintf("[%s] %s\n", serverUrl.Host, e.Error())) + retry := handlers.GetRetryFromContext(request) + + if retry < 3 { + time.Sleep(backoff.Default.Duration(retry)) + ctx := context.WithValue(request.Context(), domain.RETRY, retry+1) + proxy.ServeHTTP(writer, request.WithContext(ctx)) - proxy := httputil.NewSingleHostReverseProxy(serverUrl) - proxy.ErrorHandler = func(writer http.ResponseWriter, request *http.Request, e error) { - logger.LogInfo(fmt.Sprintf("[%s] %s\n", serverUrl.Host, e.Error())) - retry := handlers.GetRetryFromContext(request) + return + } - if retry < 3 { - time.Sleep(backoff.Default.Duration(retry)) - ctx := context.WithValue(request.Context(), domain.RETRY, retry+1) - proxy.ServeHTTP(writer, request.WithContext(ctx)) + // after 3 retries, mark this backend as down + handlers.ServerPool.MarkBackendStatus(serverUrl, false) - return + // if the same request routing for few attempts with different backends, increase the count + attempts := handlers.GetAttemptsFromContext(request) + logger.LogInfo(fmt.Sprintf("%s(%s) Attempting retry %d\n", request.RemoteAddr, request.URL.Path, attempts)) + ctx := context.WithValue(request.Context(), domain.ATTEMPTS, attempts+1) + handlers.Lbalancer(writer, request.WithContext(ctx)) } - // after 3 retries, mark this backend as down - handlers.ServerPool.MarkBackendStatus(serverUrl, false) + handlers.ServerPool.AddBackend(&domain.Backend{ + URL: serverUrl, + Alive: true, + ReverseProxy: proxy, + }) + logger.LogInfo(fmt.Sprintf("Configured server: %s\n", serverUrl)) + } - // if the same request routing for few attempts with different backends, increase the count - attempts := handlers.GetAttemptsFromContext(request) - logger.LogInfo(fmt.Sprintf("%s(%s) Attempting retry %d\n", request.RemoteAddr, request.URL.Path, attempts)) - ctx := context.WithValue(request.Context(), domain.ATTEMPTS, attempts+1) - handlers.Lbalancer(writer, request.WithContext(ctx)) + // create http server + server := http.Server{ + Addr: fmt.Sprintf(":%d", port), + Handler: http.HandlerFunc(handlers.Lbalancer), } - handlers.ServerPool.AddBackend(&domain.Backend{ - URL: serverUrl, - Alive: true, - ReverseProxy: proxy, - }) - logger.LogInfo(fmt.Sprintf("Configured server: %s\n", serverUrl)) - } - - // create http server - server := http.Server{ - Addr: fmt.Sprintf(":%d", port), - Handler: http.HandlerFunc(handlers.Lbalancer), - } - - // start health checking - go handlers.HealthCheck() - - logger.LogInfo(fmt.Sprintf("Load Balancer started at :%d\n", port)) - if err := server.ListenAndServe(); err != nil { - logger.LogError(err.Error()) - } + // start health checking + go handlers.HealthCheck() + + logger.LogInfo(fmt.Sprintf("Load Balancer started at :%d\n", port)) + if err := server.ListenAndServe(); err != nil { + logger.LogError(err.Error()) + } + + }, +} + +func init() { + lbCmd.Flags().String(flagServerList, cfgFile, "Load balanced backends, use commas to separate") + lbCmd.Flags().Int(flagPort, 4000, "Port to serve to run load balancing ") + + rootCmd.AddCommand(lbCmd) } diff --git a/cmd/cli/proxy.go b/cmd/cli/proxy.go index c80ec57..ba3208f 100644 --- a/cmd/cli/proxy.go +++ b/cmd/cli/proxy.go @@ -5,71 +5,92 @@ import ( handlers "github.com/kenriortega/ngonx/internal/proxy/handlers" services "github.com/kenriortega/ngonx/internal/proxy/services" "github.com/kenriortega/ngonx/pkg/badgerdb" - "github.com/kenriortega/ngonx/pkg/config" "github.com/kenriortega/ngonx/pkg/genkey" "github.com/kenriortega/ngonx/pkg/httpsrv" "github.com/kenriortega/ngonx/pkg/logger" + "github.com/kenriortega/ngonx/pkg/metric" + "github.com/spf13/cobra" ) -func StartProxy( - generateApiKey bool, - port int, - prevKey string, - config config.Config, -) { - - engine := config.ProxyCache.Engine - securityType := config.ProxySecurity.Type - key := config.ProxyCache.Key + "_" + securityType - - var proxyRepository domain.ProxyRepository - clientBadger := badgerdb.GetBadgerDB(false) - proxyRepository = domain.NewProxyRepository(clientBadger) - h := handlers.ProxyHandler{ - Service: services.NewProxyService(proxyRepository), - } - - if generateApiKey { - word := genkey.StringWithCharset() - apiKey := genkey.ApiKeyGenerator(word) - _, err := h.Service.SaveSecretKEY(engine, key, apiKey) +var proxyCmd = &cobra.Command{ + Use: "proxy", + Short: "Run ngonx as a reverse proxy", + Run: func(cmd *cobra.Command, args []string) { + port, err := cmd.Flags().GetInt(flagPort) if err != nil { - logger.LogError("genkey: Failed " + err.Error()) + logger.LogError(err.Error()) } - logger.LogInfo("genkey: Susscefull") - } - if prevKey != "" { - _, err := h.Service.SaveSecretKEY(engine, key, prevKey) + generateApiKey, err := cmd.Flags().GetBool(flagGenApiKey) if err != nil { - logger.LogError("prevKey: Failed " + err.Error()) + logger.LogError(err.Error()) + } + prevKey, err := cmd.Flags().GetString(flagPrevKey) + if err != nil { + logger.LogError(err.Error()) + } + // Exporter Metrics + go metric.ExposeMetricServer(configFromYaml.ProxyGateway.PortExporterProxy) + // proxy logic + engine := configFromYaml.ProxyCache.Engine + securityType := configFromYaml.ProxySecurity.Type + key := configFromYaml.ProxyCache.Key + "_" + securityType + + var proxyRepository domain.ProxyRepository + clientBadger := badgerdb.GetBadgerDB(false) + proxyRepository = domain.NewProxyRepository(clientBadger) + h := handlers.ProxyHandler{ + Service: services.NewProxyService(proxyRepository), } - logger.LogInfo("prevKey: Susscefull") - } - for _, endpoints := range config.ProxyGateway.EnpointsProxy { + if generateApiKey { + word := genkey.StringWithCharset() + apiKey := genkey.ApiKeyGenerator(word) + _, err := h.Service.SaveSecretKEY(engine, key, apiKey) + if err != nil { + logger.LogError("genkey: Failed " + err.Error()) + } + logger.LogInfo("genkey: Susscefull") + } + if prevKey != "" { + _, err := h.Service.SaveSecretKEY(engine, key, prevKey) + if err != nil { + logger.LogError("prevKey: Failed " + err.Error()) + } + logger.LogInfo("prevKey: Susscefull") + } - h.ProxyGateway(endpoints, engine, key, securityType) - } + for _, endpoints := range configFromYaml.ProxyGateway.EnpointsProxy { + + h.ProxyGateway(endpoints, engine, key, securityType) + } + + if configFromYaml.ProxySSL.Enable { + portSSL := configFromYaml.ProxyGateway.Port + configFromYaml.ProxySSL.SSLPort + server := httpsrv.NewServerSSL( + configFromYaml.ProxyGateway.Host, + portSSL, + nil, + ) + server.StartSSL( + configFromYaml.ProxySSL.CrtFile, + configFromYaml.ProxySSL.KeyFile, + ) + } else { + port = configFromYaml.ProxyGateway.Port + port + server := httpsrv.NewServer( + configFromYaml.ProxyGateway.Host, + port, + nil, + ) + server.Start() + } + }, +} - if config.ProxySSL.Enable { - portSSL := config.ProxyGateway.Port + config.ProxySSL.SSLPort - server := httpsrv.NewServerSSL( - config.ProxyGateway.Host, - portSSL, - nil, - ) - server.StartSSL( - config.ProxySSL.CrtFile, - config.ProxySSL.KeyFile, - ) - } else { - port = config.ProxyGateway.Port + port - server := httpsrv.NewServer( - config.ProxyGateway.Host, - port, - nil, - ) - server.Start() - } +func init() { + proxyCmd.Flags().Int(flagPort, 5000, "Port to serve to run proxy") + proxyCmd.Flags().Bool(flagGenApiKey, false, "Action for generate hash for protected routes") + proxyCmd.Flags().String(flagPrevKey, "", "Action for save a previous hash for protected routes to validate JWT") + rootCmd.AddCommand(proxyCmd) } diff --git a/cmd/cli/mngt.go b/cmd/cli/root.go similarity index 53% rename from cmd/cli/mngt.go rename to cmd/cli/root.go index 008ea7e..9411ce6 100644 --- a/cmd/cli/mngt.go +++ b/cmd/cli/root.go @@ -2,6 +2,7 @@ package cli import ( "net/http" + "os" "github.com/gorilla/mux" domain "github.com/kenriortega/ngonx/internal/mngt/domain" @@ -9,8 +10,41 @@ import ( services "github.com/kenriortega/ngonx/internal/mngt/services" "github.com/kenriortega/ngonx/pkg/config" "github.com/kenriortega/ngonx/pkg/httpsrv" + "github.com/kenriortega/ngonx/pkg/logger" + "github.com/spf13/cobra" ) +// rootCmd represents the base command when called without any subcommands +var rootCmd = &cobra.Command{ + Use: "ngonxctl", + Short: "A proxy reverse inspired on nginx & traefik", + Long: `This is Ngonx ctl a proxy reverse inspired on nginx & traefik`, +} + +func Execute() { + if err := rootCmd.Execute(); err != nil { + + logger.LogError(err.Error()) + os.Exit(1) + } + go StartMngt(configFromYaml) + +} +func init() { + cobra.OnInitialize(initConfig) + rootCmd.PersistentFlags().StringVarP(&cfgFile, flagCfgFile, "f", cfgFile, "File setting.yml") + rootCmd.PersistentFlags().StringVarP(&cfgPath, flagCfgPath, "p", cfgPath, "Config path only ") +} + +// initConfig reads in config file and ENV variables if set. +func initConfig() { + configFromYaml, errConfig = config.LoadConfig(cfgPath, cfgFile) + + if errConfig != nil { + logger.LogError("Yaml file not found please run command setup " + errConfig.Error()) + } +} + func StartMngt(config config.Config) { r := mux.NewRouter() repo := domain.NewMngtRepositoryStorage() diff --git a/cmd/cli/setup.go b/cmd/cli/setup.go new file mode 100644 index 0000000..8e2f555 --- /dev/null +++ b/cmd/cli/setup.go @@ -0,0 +1,25 @@ +package cli + +import ( + "log" + + "github.com/spf13/cobra" +) + +var setupCmd = &cobra.Command{ + Use: "setup", + Short: "Create configuration file it`s doesn`t exist", + Run: func(cmd *cobra.Command, args []string) { + settingsFile, err := cmd.Flags().GetString(flagCfgFile) + if err != nil { + log.Fatalf(err.Error()) + } + configFromYaml.CreateSettingFile(settingsFile) + + }, +} + +func init() { + setupCmd.Flags().String(flagCfgFile, cfgFile, "Only config filename.yaml") + rootCmd.AddCommand(setupCmd) +} diff --git a/cmd/cli/static.go b/cmd/cli/static.go index 9a4b424..80fc629 100644 --- a/cmd/cli/static.go +++ b/cmd/cli/static.go @@ -5,34 +5,41 @@ import ( "os" "github.com/kenriortega/ngonx/pkg/httpsrv" - - "github.com/kenriortega/ngonx/pkg/config" + "github.com/spf13/cobra" ) -func StartStaticServer( - config config.Config, -) { - frontEnd := os.DirFS(config.StaticServer.StaticFile) - if config.ServerSSL.Enable { +var staticCmd = &cobra.Command{ + Use: "static", + Short: "Run ngonx as a static web server", + Run: func(cmd *cobra.Command, args []string) { + frontEnd := os.DirFS(configFromYaml.StaticServer.StaticFile) + if configFromYaml.ServerSSL.Enable { + + http.Handle("/", http.FileServer(http.FS(frontEnd))) + + portSSL := configFromYaml.ServerSSL.SSLPort - http.Handle("/", http.FileServer(http.FS(frontEnd))) + server := httpsrv.NewServerSSL(configFromYaml.StaticServer.Host, portSSL, nil) + server.StartSSL( + configFromYaml.ServerSSL.CrtFile, + configFromYaml.ServerSSL.KeyFile, + ) - portSSL := config.ServerSSL.SSLPort + } else { + http.Handle("/", http.FileServer(http.FS(frontEnd))) - server := httpsrv.NewServerSSL(config.StaticServer.Host, portSSL, nil) - server.StartSSL( - config.ServerSSL.CrtFile, - config.ServerSSL.KeyFile, - ) + server := httpsrv.NewServer( + configFromYaml.StaticServer.Host, + configFromYaml.StaticServer.Port, + nil, + ) + server.Start() + } + + }, +} - } else { - http.Handle("/", http.FileServer(http.FS(frontEnd))) +func init() { - server := httpsrv.NewServer( - config.StaticServer.Host, - config.StaticServer.Port, - nil, - ) - server.Start() - } + rootCmd.AddCommand(staticCmd) } diff --git a/cmd/cli/version.go b/cmd/cli/version.go new file mode 100644 index 0000000..e3c3397 --- /dev/null +++ b/cmd/cli/version.go @@ -0,0 +1,36 @@ +package cli + +import ( + "fmt" + + "github.com/spf13/cobra" +) + +var ( + buildTime string + version string + versionHash string +) + +var versionCmd = &cobra.Command{ + Use: "version", + Short: "Print the version number of ngonxctl", + Run: func(cmd *cobra.Command, args []string) { + fmt.Printf("Version:\t%s\n", version) + fmt.Printf("Version Git Hash:\t%s\n", shortGitCommit(versionHash)) + fmt.Printf("Build time:\t%s\n", buildTime) + + }, +} + +func shortGitCommit(fullGitCommit string) string { + shortCommit := "" + if len(fullGitCommit) >= 6 { + shortCommit = fullGitCommit[0:6] + } + + return shortCommit +} +func init() { + rootCmd.AddCommand(versionCmd) +} diff --git a/cmd/main.go b/cmd/main.go index 1ab7ce3..686a2d4 100644 --- a/cmd/main.go +++ b/cmd/main.go @@ -1,92 +1,17 @@ package main import ( - "flag" - "fmt" - "os" "runtime" "github.com/kenriortega/ngonx/cmd/cli" - "github.com/kenriortega/ngonx/pkg/config" - "github.com/kenriortega/ngonx/pkg/logger" - "github.com/kenriortega/ngonx/pkg/metric" -) - -var ( - buildTime string - version string - versionHash string - configFromYaml config.Config - errConfig error - portProxy int - service = "proxy" - setup = false - generateApiKey = false - serverList = "" - portLB = 3030 - pathSettingsFile, _ = os.Getwd() - settingsFile = "ngonx.yaml" - prevKey = "" - displayVersion = false - portExporterProxy = 10000 ) func init() { - flag.BoolVar(&displayVersion, "version", displayVersion, "Display version and exit") - flag.BoolVar(&setup, "setup", setup, "Create yaml file configuration") - flag.StringVar(&pathSettingsFile, "configPath", pathSettingsFile, "Config path only not filename.yaml") - flag.StringVar(&settingsFile, "configFile", settingsFile, "Only config filename.yaml default ngonx.yaml") - flag.StringVar(&service, "type", service, "Main Service default is proxy") - flag.IntVar(&portProxy, "proxyPort", portProxy, "Port to serve to run proxy") - flag.BoolVar(&generateApiKey, "genkey", generateApiKey, "Action for generate hash for protected routes") - flag.StringVar(&prevKey, "prevkey", prevKey, "Action for save a previous hash for protected routes to validate JWT") - flag.StringVar(&serverList, "backends", serverList, "Load balanced backends, use commas to separate") - flag.IntVar(&portLB, "lbPort", portLB, "Port to serve to run load balancing default 3030") - flag.IntVar(&portExporterProxy, "portExporter", portExporterProxy, "Port to serve expose metrics from prometheus default 10000") - flag.Parse() - numcpu := runtime.NumCPU() - runtime.GOMAXPROCS(numcpu) + runtime.GOMAXPROCS(numcpu) // Try to use all available CPUs. } func main() { - - if setup { - logger.LogInfo("config: Creating setting file by default") - configFromYaml.CreateSettingFile(settingsFile) - os.Exit(0) - } else { - configFromYaml, errConfig = config.LoadConfig(pathSettingsFile, settingsFile) - - if errConfig != nil { - logger.LogError("Yaml file not found please run command setup " + errConfig.Error()) - } - } - - if displayVersion { - fmt.Printf("Version:\t%s\n", version) - fmt.Printf("Version Git Hash:\t%s\n", versionHash) - fmt.Printf("Build time:\t%s\n", buildTime) - os.Exit(0) - } - // Exporter Metrics - go metric.ExposeMetricServer(portExporterProxy) - // Admin pannel - go cli.StartMngt(configFromYaml) - - switch service { - case "lb": - cli.StartLB(serverList, portLB) - case "proxy": - cli.StartProxy( - generateApiKey, - portProxy, - prevKey, - configFromYaml, - ) - case "static": - cli.StartStaticServer(configFromYaml) - } - + cli.Execute() } diff --git a/go.mod b/go.mod index 539b79e..c5e4cf7 100644 --- a/go.mod +++ b/go.mod @@ -9,6 +9,7 @@ require ( github.com/go-redis/redis/v8 v8.11.3 github.com/gorilla/mux v1.8.0 github.com/prometheus/client_golang v1.11.0 + github.com/spf13/cobra v1.2.1 // indirect github.com/spf13/viper v1.8.1 go.uber.org/zap v1.19.0 ) diff --git a/go.sum b/go.sum index b78c2d3..0fdf2a5 100644 --- a/go.sum +++ b/go.sum @@ -79,6 +79,7 @@ github.com/coreos/go-semver v0.2.0/go.mod h1:nnelYz7RCh+5ahJtPPxZlU+153eP4D4r3Ee github.com/coreos/go-semver v0.3.0/go.mod h1:nnelYz7RCh+5ahJtPPxZlU+153eP4D4r3EedlOD2RNk= github.com/coreos/go-systemd/v22 v22.3.2/go.mod h1:Y58oyj3AT4RCenI/lSvhwexgC+NSVTIJ3seZv2GcEnc= github.com/cpuguy83/go-md2man v1.0.10/go.mod h1:SmD6nW6nTyfqj6ABTjUi3V3JVMnlJmwcJI5acqYI6dE= +github.com/cpuguy83/go-md2man/v2 v2.0.0/go.mod h1:maD7wRr/U5Z6m/iR4s+kqSMx2CaBsrgA7czyZG/E6dU= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= @@ -223,6 +224,7 @@ github.com/hashicorp/serf v0.8.2/go.mod h1:6hOLApaqBFA1NXqRQAsxw9QxuDEvNxSQRwA/J github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU= github.com/ianlancetaylor/demangle v0.0.0-20181102032728-5e5cf60278f6/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc= github.com/ianlancetaylor/demangle v0.0.0-20200824232613-28f6c0f3b639/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc= +github.com/inconshreveable/mousetrap v1.0.0 h1:Z8tu5sraLXCXIcARxBp/8cbvlwVa7Z1NHg9XEKhtSvM= github.com/inconshreveable/mousetrap v1.0.0/go.mod h1:PxqpIevigyE2G7u3NXJIT2ANytuPF1OarO4DADm73n8= github.com/jpillora/backoff v1.0.0/go.mod h1:J/6gKK9jxlEcS3zixgDgUAsiuZ7yrSoa/FX5e0EB2j4= github.com/json-iterator/go v1.1.6/go.mod h1:+SdeFBvtyEkXs7REEP0seUULqWtbJapLOCVDaaPEHmU= @@ -316,8 +318,10 @@ github.com/prometheus/procfs v0.6.0/go.mod h1:cz+aTbrPOrUb4q7XlbU9ygM+/jj0fzG6c1 github.com/rogpeppe/fastuuid v1.2.0/go.mod h1:jVj6XXZzXRy/MSR5jhDC/2q6DgLz+nrA6LYCDYWNEvQ= github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4= github.com/russross/blackfriday v1.5.2/go.mod h1:JO/DiYxRf+HjHt06OyowR9PTA263kcR/rfWxYHBV53g= +github.com/russross/blackfriday/v2 v2.0.1/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= github.com/ryanuber/columnize v0.0.0-20160712163229-9b3edd62028f/go.mod h1:sm1tb6uqfes/u+d4ooFouqFdy9/2g9QGwK3SQygK0Ts= github.com/sean-/seed v0.0.0-20170313163322-e2103e2c3529/go.mod h1:DxrIzT+xaE7yg65j358z/aeFdxmN0P9QXhEzd20vsDc= +github.com/shurcooL/sanitized_anchor_name v1.0.0/go.mod h1:1NzhyTcUVG4SuEtjjoZeVRXNmyL/1OwPU0+IJeTBvfc= github.com/sirupsen/logrus v1.2.0/go.mod h1:LxeOpSwHxABJmUn/MG1IvRgCAasNZTLOkJPxbbu5VWo= github.com/sirupsen/logrus v1.4.2/go.mod h1:tLMulIdttU9McNUspp0xgXVQah82FyeX6MwdIuYE2rE= github.com/sirupsen/logrus v1.6.0/go.mod h1:7uNnSEd1DgxDLC74fIahvMZmmYsHGZGEOFrfsX/uA88= @@ -335,6 +339,8 @@ github.com/spf13/cast v1.3.0/go.mod h1:Qx5cxh0v+4UWYiBimWS+eyWzqEqokIECu5etghLkU github.com/spf13/cast v1.3.1 h1:nFm6S0SMdyzrzcmThSipiEubIDy8WEXKNZ0UOgiRpng= github.com/spf13/cast v1.3.1/go.mod h1:Qx5cxh0v+4UWYiBimWS+eyWzqEqokIECu5etghLkUJE= github.com/spf13/cobra v0.0.5/go.mod h1:3K3wKZymM7VvHMDS9+Akkh4K60UwM26emMESw8tLCHU= +github.com/spf13/cobra v1.2.1 h1:+KmjbUw1hriSNMF55oPrkZcb27aECyrj8V2ytv7kWDw= +github.com/spf13/cobra v1.2.1/go.mod h1:ExllRjgxM/piMAM+3tAZvg8fsklGAf3tPfi+i8t68Nk= github.com/spf13/jwalterweatherman v1.0.0/go.mod h1:cQK4TGJAtQXfYWX+Ddv3mKDzgVb68N+wFjFa4jdeBTo= github.com/spf13/jwalterweatherman v1.1.0 h1:ue6voC5bR5F8YxI5S67j9i582FU4Qvo2bmqnqMYADFk= github.com/spf13/jwalterweatherman v1.1.0/go.mod h1:aNWZUN0dPAAO/Ljvb5BEdw96iTZ0EXowPYD95IqWIGo= diff --git a/internal/proxy/handlers/proxy.go b/internal/proxy/handlers/proxy.go index 7d60f4c..fed0ffe 100644 --- a/internal/proxy/handlers/proxy.go +++ b/internal/proxy/handlers/proxy.go @@ -107,7 +107,6 @@ func (ph *ProxyHandler) ProxyGateway(endpoints domain.ProxyEndpoint, engine, key } func metricRegister(req *http.Request, target *url.URL) { - timer := prometheus.NewTimer(metric.DurationHttpRequest.WithLabelValues(target.String())) metric.CountersByEndpoint.With( prometheus.Labels{ "proxyPath": req.RequestURI, @@ -123,7 +122,6 @@ func metricRegister(req *http.Request, target *url.URL) { }, ).Inc() - timer.ObserveDuration() } // checkJWTSecretKeyFromRequest check jwt for request diff --git a/makefile b/makefile index 47986b4..fc67ff0 100644 --- a/makefile +++ b/makefile @@ -6,18 +6,19 @@ git_hash := $(shell git rev-parse --short HEAD || echo 'development') version = $(shell git tag | sort -V | tail -1 || echo 'development') # Get current date current_time = $(shell date +"%Y-%m-%d:T%H:%M:%S") +name:="ngonxctl" # Add linker flags -linker_flags = '-s -X main.buildTime=${current_time} -X main.versionHash=${git_hash} -X main.version=${version}' +linker_flags = '-s -X github.com/kenriortega/ngonx/cmd/cli.buildTime=${current_time} -X github.com/kenriortega/ngonx/cmd/cli.versionHash=${git_hash} -X github.com/kenriortega/ngonx/cmd/cli.version=${version}' # Build binaries for current OS and Linux .PHONY: compile: @echo "Building binaries..." - GOOS=linux GOARCH=amd64 go build -ldflags=${linker_flags} -o ./build/ngonxctl-${version}-linux-amd64 cmd/main.go - CGO_ENABLED=0 GOOS=windows GOARCH=amd64 go build -ldflags=${linker_flags} -o ./build/ngonxctl-${version}-windows-amd64.exe cmd/main.go + GOOS=linux GOARCH=amd64 go build -ldflags=${linker_flags} -o ./build/${name}-${version}-linux-amd64 cmd/main.go + CGO_ENABLED=0 GOOS=windows GOARCH=amd64 go build -ldflags=${linker_flags} -o ./build/${name}-${version}-windows-amd64.exe cmd/main.go gocert: go run ./tools/generate_cert.go @@ -27,4 +28,4 @@ gossl: #Only use if you have installed UPX compress compress: - ./upx -9 -q ./build/ngonxctl-${version}-linux-amd64 \ No newline at end of file + ./upx -9 -q ./build/${name}-${version}-linux-amd64 \ No newline at end of file diff --git a/pkg/metric/client.go b/pkg/metric/client.go index 7f58ea7..1a77c7b 100644 --- a/pkg/metric/client.go +++ b/pkg/metric/client.go @@ -5,9 +5,7 @@ import ( "log" "net/http" - "github.com/kenriortega/ngonx/pkg/logger" "github.com/prometheus/client_golang/prometheus" - "github.com/prometheus/client_golang/prometheus/promauto" "github.com/prometheus/client_golang/prometheus/promhttp" ) @@ -25,11 +23,6 @@ var ( }, ) - DurationHttpRequest = promauto.NewHistogramVec(prometheus.HistogramOpts{ - Name: "http_response_time_seconds_microservices", - Help: "Duration of HTTP requests.", - }, []string{"path"}) - TotalRequests = prometheus.NewCounterVec( prometheus.CounterOpts{ Name: "http_requests_total", @@ -40,10 +33,7 @@ var ( ) func init() { - err := prometheus.Register(DurationHttpRequest) - if err != nil { - logger.LogError(err.Error()) - } + prometheus.MustRegister(CountersByEndpoint) prometheus.MustRegister(TotalRequests) }