Skip to content

Commit

Permalink
Merge pull request #13 from DrOctavius/main
Browse files Browse the repository at this point in the history
http middleware fixes
  • Loading branch information
DrOctavius authored Aug 9, 2022
2 parents 039dc61 + 4e702e3 commit ec114e7
Show file tree
Hide file tree
Showing 11 changed files with 105 additions and 54 deletions.
4 changes: 2 additions & 2 deletions core/config/autoloader/load.go
Original file line number Diff line number Diff line change
Expand Up @@ -81,9 +81,9 @@ func StartAutoLoader(c Config) error {
// the config can be modified by multiple processes at once if launched simultaneously!
// This is why each process will do its work and after finishing it, the next process will do the same thing!
// That will not degrade much in performance, but still will be a small slow down
if !lock.FLock(configFilePath, true) {
if isLockAcquired, lockErr := lock.FLock(configFilePath, true); !isLockAcquired || lockErr != nil {
// Here we have some kind of error?!
return err.New(0, "failed to lock config file")
return err.New(0, "failed to lock config file -> ", lockErr.Error())
}
// Release the file lock on return
defer lock.FRelease(configFilePath)
Expand Down
14 changes: 8 additions & 6 deletions core/console/menu/menu.go
Original file line number Diff line number Diff line change
Expand Up @@ -238,13 +238,15 @@ func (m *Menu) AddCommand(c *command.AddCmd) *Menu {
appLog.Info().Int("pid", _command.Process.Pid).Msg("getting pid")
}
} else {
if c.LockProcess && !lock.FLock(c.GetProcessLockName(), false) {
// handle locking error
//log.Println("Failed to lock the process!")
if logger.GetAppLogger() != nil {
appLog.Warn().Msg(color.Style{color.LightYellow}.Render("failed to lock the process"))
if c.LockProcess {
if isLockAcquired, lockErr := lock.FLock(c.GetProcessLockName(), false); !isLockAcquired || lockErr != nil {
// handle locking error
//log.Println("Failed to lock the process!")
if logger.GetAppLogger() != nil {
appLog.Warn().Msg(color.Style{color.LightYellow}.Render("failed to lock the process"))
}
return
}
return
}

// Destruct when leaving this...
Expand Down
63 changes: 43 additions & 20 deletions core/helpers/filesystem/lock/flock.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,11 @@ package lock
import (
"github.com/gofrs/flock"
"github.com/kyaxcorp/go-core/core/config"
"github.com/kyaxcorp/go-core/core/helpers/err/define"
fsPath "github.com/kyaxcorp/go-core/core/helpers/filesystem/path"
"github.com/kyaxcorp/go-core/core/helpers/folder"
"github.com/kyaxcorp/go-core/core/helpers/hash"
"log"
"github.com/kyaxcorp/go-core/core/logger/appLog"
"sync"
)

Expand All @@ -21,50 +22,72 @@ func getLockName(lockName string) string {
return hash.Sha256(lockName) + ".lock"
}

func getLockPath(lockName string) string {
return getLocksDir() + getLockName(lockName)
func getLockPath(lockName string) (string, error) {
locksDir, locksDirErr := getLocksDir()
if locksDirErr != nil {
return "", locksDirErr
}
return locksDir + getLockName(lockName), nil
}

func getLocksDir() string {
var err error = nil
func getLocksDir() (string, error) {
var pathErr error
locksPath := config.GetConfig().Application.LocksPath
locksPath, err = fsPath.GenRealPath(locksPath, true)
appLog.Info().Str("application_locks_path", locksPath).Msg("application locks path")

locksPath, pathErr = fsPath.GenRealPath(locksPath, true)

if err != nil {
log.Println(err)
if pathErr != nil {
return "", pathErr
}

if !folder.Exists(locksPath) {
folder.MkDir(locksPath)
}

return locksPath
appLog.Info().Str("locks_dir", locksPath).Msg("application generated real path")

return locksPath, nil
}

func FLock(lockName string, wait bool) bool {
func FLock(lockName string, wait bool) (bool, error) {
appLog.Info().
Str("lock_name", lockName).
Bool("wait", wait).
Msg("FLock called")
defer appLog.Info().Msg("leaving...")
lockNameHash := getLockName(lockName)
lockPath := getLockPath(lockName)
appLog.Info().
Str("lock_name_hashed", lockNameHash).
Msg("lock name hashed, getting lock path")
lockPath, lockPathErr := getLockPath(lockName)
if lockPathErr != nil {
appLog.Error().Err(lockPathErr).Msg("failed to get lock path")
return false, lockPathErr
}

appLog.Info().Str("lock_path", lockPath).Msg("lock path retrieved")

// log.Println(lockPath)
fileLock := flock.New(lockPath)
var locked bool
var err interface{} = nil
//var err interface{} = nil
var lockErr error
if wait {
err = fileLock.Lock()
lockErr = fileLock.Lock()
locked = true
} else {
locked, err = fileLock.TryLock()
locked, lockErr = fileLock.TryLock()
}

if err != nil {
if lockErr != nil {
// handle locking error
log.Println("Failed to lock the process!")
return false
return false, define.Err(0, "failed to lock the process -> ", lockErr.Error())
}

if !locked {
log.Println("Is Locked!")
return false
//log.Println("Is Locked!")
return false, nil
}

// Lock inside the main process and globally!
Expand All @@ -76,7 +99,7 @@ func FLock(lockName string, wait bool) bool {

//locks = append(locks, fileLock)

return true
return true, nil
}

func FRelease(lockName string) {
Expand Down
6 changes: 6 additions & 0 deletions core/listeners/http/middlewares/connection/constructor.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
package connection

func New() *ConnDetails {
c := &ConnDetails{}
return c
}
8 changes: 8 additions & 0 deletions core/listeners/http/middlewares/connection/context.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
package connection

import "github.com/gin-gonic/gin"

func (c *ConnDetails) SetGinContext(ctx *gin.Context) *ConnDetails {
c.C = ctx
return c
}
8 changes: 8 additions & 0 deletions core/listeners/http/middlewares/connection/logger.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
package connection

import "github.com/kyaxcorp/go-core/core/logger/model"

func (c *ConnDetails) SetLogger(logger *model.Logger) *ConnDetails {
c.Logger = logger
return c
}
26 changes: 3 additions & 23 deletions core/listeners/http/middlewares/connection/middleware.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,31 +2,11 @@ package connection

import (
"github.com/gin-gonic/gin"
"github.com/gookit/color"
"github.com/kyaxcorp/go-core/core/logger/model"
)

func GetMiddleware(logger *model.Logger) gin.HandlerFunc {
conn := GenerateConnDetails()
return conn.GetHandlerFunc(logger)
}

func (c *ConnDetails) GetHandlerFunc(logger *model.Logger) gin.HandlerFunc {
return func(gin *gin.Context) {

// Set the context to the struct!
c.C = gin
c.generateDetails()
// Debug the connection

logger.Logger.Info().
Str("host", c.Host).
Str("client_ip", c.ClientIPAddress).
Int("client_port", c.ClientPort).
Str("user_agent", c.UserAgent).
Str("remote_addr", c.RemoteAddr).
Str("request_path", c.RequestPath).
Str("referer", c.Referer).
Msg(color.Style{color.LightGreen, color.OpBold}.Render("new connection"))
func Middleware(logger *model.Logger) gin.HandlerFunc {
return func(context *gin.Context) {
New().SetGinContext(context).SetLogger(logger).Process()
}
}
7 changes: 6 additions & 1 deletion core/listeners/http/middlewares/connection/model.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
package connection

import "github.com/gin-gonic/gin"
import (
"github.com/gin-gonic/gin"
"github.com/kyaxcorp/go-core/core/logger/model"
)

const HttpContextConnDetailsKey = "CONN_DETAILS"

Expand All @@ -19,6 +22,8 @@ type ConnDetails struct {
IsSecure bool
Referer string

Logger *model.Logger

// Connection context
C *gin.Context
}
19 changes: 19 additions & 0 deletions core/listeners/http/middlewares/connection/process.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
package connection

import "github.com/gookit/color"

func (c *ConnDetails) Process() {
c.generateDetails()
// Debug the connection

c.Logger.Logger.Info().
Str("host", c.Host).
Str("client_ip", c.ClientIPAddress).
Int("client_port", c.ClientPort).
Str("user_agent", c.UserAgent).
Str("remote_addr", c.RemoteAddr).
Str("request_path", c.RequestPath).
Str("referer", c.Referer).
Msg(color.Style{color.LightGreen, color.OpBold}.Render("new connection"))

}
2 changes: 1 addition & 1 deletion core/listeners/http/server/server_constructor.go
Original file line number Diff line number Diff line change
Expand Up @@ -223,7 +223,7 @@ func New(
infoServer().Msg("setting default middleware for connections")
// We set as default middle related to connections
// TODO: maybe we should also log into a folder the arriving connections!
s.HttpServer.Use(connection.GetMiddleware(s.Logger))
s.HttpServer.Use(connection.Middleware(s.Logger))
// Latency in processing
s.HttpServer.Use(request_timing.GetMiddleware(s.Logger))

Expand Down
2 changes: 1 addition & 1 deletion core/listeners/websocket/server/server_constructor.go
Original file line number Diff line number Diff line change
Expand Up @@ -267,7 +267,7 @@ func New(
infoServer().Msg("setting default middleware for connections")
// We set as default middle related to connections
// TODO: maybe we should also log into a folder the arriving connections!
s.WSServer.Use(connection.GetMiddleware(s.Logger))
s.WSServer.Use(connection.Middleware(s.Logger))
// Latency in processing
s.WSServer.Use(request_timing.GetMiddleware(s.Logger))

Expand Down

0 comments on commit ec114e7

Please sign in to comment.