Skip to content

Commit

Permalink
added request id header functionality
Browse files Browse the repository at this point in the history
  • Loading branch information
TheFireMike committed Dec 22, 2020
1 parent 4ab216c commit 54f46aa
Show file tree
Hide file tree
Showing 13 changed files with 116 additions and 40 deletions.
4 changes: 2 additions & 2 deletions api/logger.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,14 +15,14 @@ func LoggerMiddleware() echo.MiddlewareFunc {
res := c.Response()
start := time.Now()

logger := log.Logger

if err = next(c); err != nil {
c.Error(err)
}

stop := time.Now()

logger := log.Logger.With().Str("request_id", res.Header().Get(echo.HeaderXRequestID)).Logger()

evt := logger.Info()
evt.Str("remote_ip", c.RealIP())
evt.Str("host", req.Host)
Expand Down
File renamed without changes.
40 changes: 23 additions & 17 deletions api/request_handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,8 @@ func StartAPI() {

e.Use(statistics.Middleware())

e.Use(RequestIDMiddleware())

e.Use(LoggerMiddleware())

// swagger:operation POST /identify identify identify
Expand Down Expand Up @@ -504,7 +506,7 @@ func identify(ctx echo.Context) error {
if err := ctx.Bind(&r); err != nil {
return err
}
resp, err := handleAPIRequest(&r, &r.BaseRequest.DeviceData.IPAddress)
resp, err := handleAPIRequest(ctx, &r, &r.BaseRequest.DeviceData.IPAddress)
if err != nil {
return handleError(ctx, err)
}
Expand All @@ -516,7 +518,7 @@ func checkIdentify(ctx echo.Context) error {
if err := ctx.Bind(&r); err != nil {
return err
}
resp, err := handleAPIRequest(&r, &r.BaseRequest.DeviceData.IPAddress)
resp, err := handleAPIRequest(ctx, &r, &r.BaseRequest.DeviceData.IPAddress)
if err != nil {
return handleError(ctx, err)
}
Expand All @@ -528,7 +530,7 @@ func checkSNMP(ctx echo.Context) error {
if err := ctx.Bind(&r); err != nil {
return err
}
resp, err := handleAPIRequest(&r, &r.BaseRequest.DeviceData.IPAddress)
resp, err := handleAPIRequest(ctx, &r, &r.BaseRequest.DeviceData.IPAddress)
if err != nil {
return handleError(ctx, err)
}
Expand All @@ -540,7 +542,7 @@ func checkInterfaceMetrics(ctx echo.Context) error {
if err := ctx.Bind(&r); err != nil {
return err
}
resp, err := handleAPIRequest(&r, &r.BaseRequest.DeviceData.IPAddress)
resp, err := handleAPIRequest(ctx, &r, &r.BaseRequest.DeviceData.IPAddress)
if err != nil {
return handleError(ctx, err)
}
Expand All @@ -552,7 +554,7 @@ func checkTholaServer(ctx echo.Context) error {
if err := ctx.Bind(&r); err != nil {
return err
}
resp, err := handleAPIRequest(&r, nil)
resp, err := handleAPIRequest(ctx, &r, nil)
if err != nil {
return handleError(ctx, err)
}
Expand All @@ -564,7 +566,7 @@ func checkUPS(ctx echo.Context) error {
if err := ctx.Bind(&r); err != nil {
return err
}
resp, err := handleAPIRequest(&r, &r.BaseRequest.DeviceData.IPAddress)
resp, err := handleAPIRequest(ctx, &r, &r.BaseRequest.DeviceData.IPAddress)
if err != nil {
return handleError(ctx, err)
}
Expand All @@ -576,7 +578,7 @@ func checkMemoryUsage(ctx echo.Context) error {
if err := ctx.Bind(&r); err != nil {
return err
}
resp, err := handleAPIRequest(&r, &r.BaseRequest.DeviceData.IPAddress)
resp, err := handleAPIRequest(ctx, &r, &r.BaseRequest.DeviceData.IPAddress)
if err != nil {
return handleError(ctx, err)
}
Expand All @@ -588,7 +590,7 @@ func checkCpuLoad(ctx echo.Context) error {
if err := ctx.Bind(&r); err != nil {
return err
}
resp, err := handleAPIRequest(&r, &r.BaseRequest.DeviceData.IPAddress)
resp, err := handleAPIRequest(ctx, &r, &r.BaseRequest.DeviceData.IPAddress)
if err != nil {
return handleError(ctx, err)
}
Expand All @@ -600,7 +602,7 @@ func checkMetrics(ctx echo.Context) error {
if err := ctx.Bind(&r); err != nil {
return err
}
resp, err := handleAPIRequest(&r, &r.BaseRequest.DeviceData.IPAddress)
resp, err := handleAPIRequest(ctx, &r, &r.BaseRequest.DeviceData.IPAddress)
if err != nil {
return handleError(ctx, err)
}
Expand All @@ -612,7 +614,7 @@ func readInterfaces(ctx echo.Context) error {
if err := ctx.Bind(&r); err != nil {
return err
}
resp, err := handleAPIRequest(&r, &r.BaseRequest.DeviceData.IPAddress)
resp, err := handleAPIRequest(ctx, &r, &r.BaseRequest.DeviceData.IPAddress)
if err != nil {
return handleError(ctx, err)
}
Expand All @@ -624,7 +626,7 @@ func readCountInterfaces(ctx echo.Context) error {
if err := ctx.Bind(&r); err != nil {
return err
}
resp, err := handleAPIRequest(&r, &r.BaseRequest.DeviceData.IPAddress)
resp, err := handleAPIRequest(ctx, &r, &r.BaseRequest.DeviceData.IPAddress)
if err != nil {
return handleError(ctx, err)
}
Expand All @@ -636,7 +638,7 @@ func readCPULoad(ctx echo.Context) error {
if err := ctx.Bind(&r); err != nil {
return err
}
resp, err := handleAPIRequest(&r, &r.BaseRequest.DeviceData.IPAddress)
resp, err := handleAPIRequest(ctx, &r, &r.BaseRequest.DeviceData.IPAddress)
if err != nil {
return handleError(ctx, err)
}
Expand All @@ -648,7 +650,7 @@ func readMemoryUsage(ctx echo.Context) error {
if err := ctx.Bind(&r); err != nil {
return err
}
resp, err := handleAPIRequest(&r, &r.BaseRequest.DeviceData.IPAddress)
resp, err := handleAPIRequest(ctx, &r, &r.BaseRequest.DeviceData.IPAddress)
if err != nil {
return handleError(ctx, err)
}
Expand All @@ -660,7 +662,7 @@ func readUPS(ctx echo.Context) error {
if err := ctx.Bind(&r); err != nil {
return err
}
resp, err := handleAPIRequest(&r, &r.BaseRequest.DeviceData.IPAddress)
resp, err := handleAPIRequest(ctx, &r, &r.BaseRequest.DeviceData.IPAddress)
if err != nil {
return handleError(ctx, err)
}
Expand All @@ -672,7 +674,7 @@ func readAvailableComponents(ctx echo.Context) error {
if err := ctx.Bind(&r); err != nil {
return err
}
resp, err := handleAPIRequest(&r, &r.BaseRequest.DeviceData.IPAddress)
resp, err := handleAPIRequest(ctx, &r, &r.BaseRequest.DeviceData.IPAddress)
if err != nil {
return handleError(ctx, err)
}
Expand Down Expand Up @@ -719,11 +721,15 @@ func getDeviceLock(ip string) *sync.Mutex {
return lock
}

func handleAPIRequest(r request.Request, ip *string) (request.Response, error) {
func handleAPIRequest(echoCTX echo.Context, r request.Request, ip *string) (request.Response, error) {
if ip != nil && !viper.GetBool("request.no-ip-lock") {
lock := getDeviceLock(*ip)
lock.Lock()
defer lock.Unlock()
}
return request.ProcessRequest(context.Background(), r)

logger := log.With().Str("request_id", echoCTX.Request().Header.Get(echo.HeaderXRequestID)).Logger()
ctx := logger.WithContext(context.Background())

return request.ProcessRequest(ctx, r)
}
23 changes: 23 additions & 0 deletions api/request_id.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package api

import (
"github.com/labstack/echo"
"github.com/rs/xid"
)

func RequestIDMiddleware() echo.MiddlewareFunc {
return func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
req := c.Request()
res := c.Response()
rid := req.Header.Get(echo.HeaderXRequestID)
if rid == "" {
rid = xid.New().String()
req.Header.Set(echo.HeaderXRequestID, rid)
}
res.Header().Set(echo.HeaderXRequestID, rid)

return next(c)
}
}
}
4 changes: 3 additions & 1 deletion cmd/check.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,9 @@ var checkCMD = &cobra.Command{
viper.Set("format", "check-plugin")
}

zerolog.SetGlobalLevel(zerolog.Disabled)
if !cmd.Flags().Changed("loglevel") {
zerolog.SetGlobalLevel(zerolog.Disabled)
}
return nil
},
Run: func(cmd *cobra.Command, args []string) {
Expand Down
13 changes: 8 additions & 5 deletions cmd/device.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"github.com/inexio/thola/core/database"
"github.com/inexio/thola/core/parser"
"github.com/inexio/thola/core/request"
"github.com/rs/xid"
"github.com/rs/zerolog/log"
flag "github.com/spf13/pflag"
"github.com/spf13/viper"
Expand All @@ -21,29 +22,31 @@ func addBinarySpecificDeviceFlags(fs *flag.FlagSet) {
}

func handleRequest(r request.Request) {
ctx := context.Background()
logger := log.With().Str("request_id", xid.New().String()).Logger()
ctx := logger.WithContext(context.Background())

db, err := database.GetDB(ctx)
if err != nil {
handleError(err)
handleError(ctx, err)
os.Exit(3)
}

resp, err := request.ProcessRequest(ctx, r)
if err != nil {
handleError(err)
handleError(ctx, err)
_ = db.CloseConnection(ctx)
os.Exit(3)
}

err = db.CloseConnection(ctx)
if err != nil {
handleError(err)
handleError(ctx, err)
os.Exit(3)
}

b, err := parser.Parse(resp, viper.GetString("format"))
if err != nil {
log.Error().Err(err).Msg("Request successful, but failed to parse response")
log.Ctx(ctx).Error().Err(err).Msg("Request successful, but failed to parse response")
os.Exit(3)
}

Expand Down
13 changes: 10 additions & 3 deletions cmd/device_client.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"fmt"
"github.com/inexio/thola/core/parser"
"github.com/inexio/thola/core/request"
"github.com/rs/xid"
"github.com/rs/zerolog/log"
flag "github.com/spf13/pflag"
"github.com/spf13/viper"
Expand All @@ -20,17 +21,23 @@ func addBinarySpecificDeviceFlags(fs *flag.FlagSet) {
}

func handleRequest(r request.Request) {
ctx := context.Background()
rid := xid.New().String()
logger := log.With().Str("request_id", rid).Logger()
ctx := logger.WithContext(request.NewContextWithRequestID(context.Background(), rid))

log.Ctx(ctx).Trace().Msg("sending request")

resp, err := request.ProcessRequest(ctx, r)
if err != nil {
handleError(err)
handleError(ctx, err)
os.Exit(3)
}

log.Ctx(ctx).Trace().Msg("received response")

b, err := parser.Parse(resp, viper.GetString("format"))
if err != nil {
log.Error().Err(err).Msg("Request successful, but failed to parse response")
log.Ctx(ctx).Error().Err(err).Msg("Request successful, but failed to parse response")
os.Exit(3)
}

Expand Down
5 changes: 3 additions & 2 deletions cmd/device_init.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package cmd

import (
"context"
"fmt"
"github.com/inexio/thola/core/network"
"github.com/inexio/thola/core/parser"
Expand Down Expand Up @@ -209,10 +210,10 @@ func getBaseRequest() request.BaseRequest {
}
}

func handleError(err error) {
func handleError(ctx context.Context, err error) {
b, err := parser.Parse(err, viper.GetString("format"))
if err != nil {
log.Error().AnErr("parse_error", err).AnErr("original_error", err).Msg("failed to parse error")
log.Ctx(ctx).Error().AnErr("parse_error", err).AnErr("original_error", err).Msg("failed to parse error")
} else {
fmt.Printf("%s\n", b)
}
Expand Down
14 changes: 14 additions & 0 deletions cmd/root_client.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import (
func init() {
log.Logger = zerolog.New(zerolog.ConsoleWriter{Out: os.Stderr}).With().Timestamp().Logger()

rootCMD.PersistentFlags().String("loglevel", "error", "The loglevel")
rootCMD.PersistentFlags().String("format", "pretty", "Output format ('json', 'xml' or 'pretty')")
rootCMD.PersistentFlags().String("target-api", "", "The URL of the target API")
rootCMD.PersistentFlags().String("target-api-username", "", "The username for authorization on the target API")
Expand All @@ -33,6 +34,14 @@ func init() {
return
}

err = viper.BindPFlag("loglevel", rootCMD.PersistentFlags().Lookup("loglevel"))
if err != nil {
log.Error().
AnErr("Error", err).
Msg("Can't bind flag loglevel")
return
}

err = viper.BindPFlag("format", rootCMD.PersistentFlags().Lookup("format"))
if err != nil {
log.Error().
Expand Down Expand Up @@ -102,6 +111,11 @@ var rootCMD = &cobra.Command{
if !(viper.GetString("target-api-format") == "json" || viper.GetString("target-api-format") == "xml") {
return errors.New("invalid api format set")
}
loglevel, err := zerolog.ParseLevel(viper.GetString("loglevel"))
if err != nil {
return errors.New("invalid loglevel set")
}
zerolog.SetGlobalLevel(loglevel)
return nil
},
Run: func(cmd *cobra.Command, args []string) {
Expand Down
2 changes: 1 addition & 1 deletion core/network/snmp_client.go
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ func NewSNMPClientByConnectionData(ctx context.Context, ipAddress string, data *
if res.err != nil {
if !tholaerr.IsNetworkError(res.err) {
s := "non network error occurred during NewSNMPClient"
log.Error().Err(res.err).Msg(s)
log.Ctx(ctx).Error().Err(res.err).Msg(s)
if criticalError == nil {
criticalError = errors.Wrap(res.err, s)
}
Expand Down
Loading

0 comments on commit 54f46aa

Please sign in to comment.