From 13026a9f7e5c6a7712aa5a4107594cd225621d28 Mon Sep 17 00:00:00 2001 From: Jacob Weinstock Date: Wed, 30 Sep 2020 09:00:14 -0600 Subject: [PATCH] Generic logging interface (#135) * use generic logging interface --- .gitignore | 3 + .travis.yml | 2 +- discover/discover.go | 31 +- discover/probe.go | 46 +- examples/main.go | 109 +++ go.mod | 7 +- go.sum | 37 +- logging/logging.go | 34 +- providers/dell/idrac8/actions_test.go | 6 +- providers/dell/idrac8/configure.go | 442 ++++++------ providers/dell/idrac8/idrac8.go | 80 +-- providers/dell/idrac8/idrac8_test.go | 13 +- providers/dell/idrac8/query.go | 29 +- providers/dell/idrac8/setupConnections.go | 6 +- providers/dell/idrac9/actions_test.go | 6 +- providers/dell/idrac9/configure.go | 530 ++++++++------- providers/dell/idrac9/idrac9.go | 102 +-- providers/dell/idrac9/idrac9_c6420_test.go | 13 +- providers/dell/idrac9/idrac9_test.go | 15 +- providers/dell/idrac9/query.go | 57 +- providers/dell/idrac9/redfish_helpers.go | 24 +- providers/dell/idrac9/setupConnections.go | 28 +- providers/dell/m1000e/actions_test.go | 6 +- providers/dell/m1000e/configure.go | 100 +-- providers/dell/m1000e/constructors.go | 80 +-- providers/dell/m1000e/m1000e.go | 43 +- providers/dell/m1000e/m1000e_test.go | 13 +- providers/dell/m1000e/setupConnections.go | 3 +- providers/hp/c7000/c7000.go | 11 +- providers/hp/c7000/c7000_test.go | 13 +- providers/hp/c7000/configure.go | 628 +++++++++--------- providers/hp/c7000/setupConnections.go | 19 +- providers/hp/c7000/xmlhelpers.go | 19 +- providers/hp/ilo/configure.go | 423 ++++++------ providers/hp/ilo/ilo.go | 61 +- providers/hp/ilo/ilo_test.go | 13 +- providers/hp/ilo/query.go | 172 ++--- providers/hp/ilo/setupConnection.go | 57 +- providers/supermicro/supermicrox/configure.go | 297 ++++----- .../supermicro/supermicrox/setupConnection.go | 28 +- .../supermicro/supermicrox/supermicrox.go | 92 +-- .../supermicrox/supermicrox_test.go | 13 +- 42 files changed, 1745 insertions(+), 1966 deletions(-) create mode 100644 examples/main.go diff --git a/.gitignore b/.gitignore index ecc1c714..271c501e 100644 --- a/.gitignore +++ b/.gitignore @@ -27,3 +27,6 @@ Session.vim tags # Persistent undo [._]*.un~ + +# vscode +*.code-workspace \ No newline at end of file diff --git a/.travis.yml b/.travis.yml index a9a0820e..6b18386d 100644 --- a/.travis.yml +++ b/.travis.yml @@ -8,7 +8,7 @@ env: install: - curl -sSfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh | sh -s -- -b $(go env GOPATH)/bin v1.31.0 before_script: -- golangci-lint run --no-config --disable-all --enable=vet --enable=gofmt --enable=gocyclo --enable=golint --enable=ineffassign --enable=misspell --enable=deadcode --tests=false ./... +- golangci-lint run --no-config --disable-all --enable=vet --enable=gofmt --enable=gocyclo --enable=golint --enable=ineffassign --enable=misspell --enable=deadcode --tests=false ./... script: - go test ./... notifications: diff --git a/discover/discover.go b/discover/discover.go index a61c80e4..a108b24c 100644 --- a/discover/discover.go +++ b/discover/discover.go @@ -1,14 +1,15 @@ package discover import ( + "context" "os" - log "github.com/sirupsen/logrus" - "github.com/bmc-toolbox/bmclib/errors" "github.com/bmc-toolbox/bmclib/internal/httpclient" - _ "github.com/bmc-toolbox/bmclib/logging" // this make possible to setup logging and properties at any stage + "github.com/bmc-toolbox/bmclib/logging" + "github.com/bmc-toolbox/bmclib/providers/dummy/ibmc" + "github.com/go-logr/logr" ) const ( @@ -24,16 +25,19 @@ const ( // ScanAndConnect will scan the bmc trying to learn the device type and return a working connection. func ScanAndConnect(host string, username string, password string, options ...Option) (bmcConnection interface{}, err error) { - log.WithFields(log.Fields{"step": "ScanAndConnect", "host": host}).Debug("detecting vendor") - opts := &Options{HintCallback: func(_ string) error { return nil }} for _, optFn := range options { optFn(opts) } + if opts.Logger == nil { + // create a default logger + opts.Logger = logging.DefaultLogger() + } + opts.Logger.V(1).Info("detecting vendor", "step", "ScanAndConnect", "host", host) // return a connection to our dummy device. if os.Getenv("BMCLIB_TEST") == "1" { - log.WithFields(log.Fields{"step": "ScanAndConnect", "host": host}).Debug("returning connection to dummy ibmc device.") + opts.Logger.V(1).Info("returning connection to dummy ibmc device.", "step", "ScanAndConnect", "host", host) bmc, err := ibmc.New(host, username, password) return bmc, err } @@ -45,7 +49,7 @@ func ScanAndConnect(host string, username string, password string, options ...Op var probe = Probe{client: client, username: username, password: password, host: host} - var devices = map[string]func() (interface{}, error){ + var devices = map[string]func(context.Context, logr.Logger) (interface{}, error){ ProbeHpIlo: probe.hpIlo, ProbeIdrac8: probe.idrac8, ProbeIdrac9: probe.idrac9, @@ -73,9 +77,9 @@ func ScanAndConnect(host string, username string, password string, options ...Op for _, probeID := range order { probeDevice := devices[probeID] - log.WithFields(log.Fields{"step": "ScanAndConnect", "host": host}).Debug("probing to identify device") + opts.Logger.V(1).Info("probing to identify device", "step", "ScanAndConnect", "host", host) - bmcConnection, err := probeDevice() + bmcConnection, err := probeDevice(opts.Context, opts.Logger) // if the device didn't match continue to probe if err != nil && (err == errors.ErrDeviceNotMatched) { @@ -98,6 +102,7 @@ func ScanAndConnect(host string, username string, password string, options ...Op return nil, errors.ErrVendorUnknown } +// Options to pass in type Options struct { // Hint is a probe ID that hints which probe should be probed first. Hint string @@ -107,6 +112,8 @@ type Options struct { // If your code persists the hint as "best effort", always return a nil error. Callback is // synchronous. HintCallback func(string) error + Logger logr.Logger + Context context.Context } // Option is part of the functional options pattern, see the `With*` functions and @@ -121,6 +128,12 @@ func WithHintCallBack(fn func(string) error) Option { return func(args *Options) { args.HintCallback = fn } } +// WithLogger sets the Options.Logger option +func WithLogger(log logr.Logger) Option { return func(args *Options) { args.Logger = log } } + +// WithContext sets the Options.Context option +func WithContext(ctx context.Context) Option { return func(args *Options) { args.Context = ctx } } + func swapProbe(order []string, hint string) { // With so few elements and since `==` uses SIMD, // looping is faster than having yet another hash map. diff --git a/discover/probe.go b/discover/probe.go index cff6173d..a6e0b377 100644 --- a/discover/probe.go +++ b/discover/probe.go @@ -2,6 +2,7 @@ package discover import ( "bytes" + "context" "encoding/xml" "fmt" "io" @@ -18,7 +19,7 @@ import ( "github.com/bmc-toolbox/bmclib/providers/hp/c7000" "github.com/bmc-toolbox/bmclib/providers/hp/ilo" "github.com/bmc-toolbox/bmclib/providers/supermicro/supermicrox" - log "github.com/sirupsen/logrus" + "github.com/go-logr/logr" ) var ( @@ -34,7 +35,7 @@ type Probe struct { password string } -func (p *Probe) hpIlo() (bmcConnection interface{}, err error) { +func (p *Probe) hpIlo(ctx context.Context, log logr.Logger) (bmcConnection interface{}, err error) { resp, err := p.client.Get(fmt.Sprintf("https://%s/xmldata?item=all", p.host)) if err != nil { @@ -68,7 +69,8 @@ func (p *Probe) hpIlo() (bmcConnection interface{}, err error) { if iloXML.HSI != nil { if strings.HasPrefix(iloXML.MP.Pn, "Integrated Lights-Out") { - return ilo.New(p.host, p.username, p.password) + log.V(1).Info("step", "ScanAndConnect", "host", p.host, "vendor", string(devices.HP), "msg", "it's a HP with iLo") + return ilo.New(ctx, p.host, p.username, p.password, log) } return bmcConnection, fmt.Errorf("it's an HP, but I cound't not identify the hardware type. Please verify") @@ -78,7 +80,7 @@ func (p *Probe) hpIlo() (bmcConnection interface{}, err error) { return bmcConnection, errors.ErrDeviceNotMatched } -func (p *Probe) hpC7000() (bmcConnection interface{}, err error) { +func (p *Probe) hpC7000(ctx context.Context, log logr.Logger) (bmcConnection interface{}, err error) { resp, err := p.client.Get(fmt.Sprintf("https://%s/xmldata?item=all", p.host)) if err != nil { @@ -106,8 +108,8 @@ func (p *Probe) hpC7000() (bmcConnection interface{}, err error) { } if iloXMLC.Infra2 != nil { - log.WithFields(log.Fields{"step": "ScanAndConnect", "host": p.host, "vendor": devices.HP}).Debug("it's a chassis") - return c7000.New(p.host, p.username, p.password) + log.V(1).Info("step", "ScanAndConnect", "host", p.host, "vendor", string(devices.HP), "msg", "it's a chassis") + return c7000.New(ctx, p.host, p.username, p.password, log) } } @@ -115,7 +117,7 @@ func (p *Probe) hpC7000() (bmcConnection interface{}, err error) { } // hpCl100 attempts to identify a cloudline device -func (p *Probe) hpCl100() (bmcConnection interface{}, err error) { +func (p *Probe) hpCl100(ctx context.Context, log logr.Logger) (bmcConnection interface{}, err error) { // HPE Cloudline CL100 resp, err := p.client.Get(fmt.Sprintf("https://%s/res/ok.png", p.host)) @@ -133,7 +135,7 @@ func (p *Probe) hpCl100() (bmcConnection interface{}, err error) { } // ensure the response we got included a png if resp.StatusCode == 200 && bytes.Contains(firstBytes, []byte("PNG")) { - log.WithFields(log.Fields{"step": "ScanAndConnect", "host": p.host, "vendor": devices.Cloudline}).Debug("it's a discrete") + log.V(1).Info("step", "ScanAndConnect", "host", p.host, "vendor", string(devices.Cloudline), "msg", "it's a discrete") return bmcConnection, errors.NewErrUnsupportedHardware("hpe cl100 not supported") } @@ -141,7 +143,7 @@ func (p *Probe) hpCl100() (bmcConnection interface{}, err error) { } -func (p *Probe) idrac8() (bmcConnection interface{}, err error) { +func (p *Probe) idrac8(ctx context.Context, log logr.Logger) (bmcConnection interface{}, err error) { resp, err := p.client.Get(fmt.Sprintf("https://%s/session?aimGetProp=hostname,gui_str_title_bar,OEMHostName,fwVersion,sysDesc", p.host)) if err != nil { @@ -157,14 +159,14 @@ func (p *Probe) idrac8() (bmcConnection interface{}, err error) { } if resp.StatusCode == 200 && containsAnySubStr(payload, idrac8SysDesc) { - log.WithFields(log.Fields{"step": "connection", "host": p.host, "vendor": devices.Dell}).Debug("it's a idrac8") - return idrac8.New(p.host, p.username, p.password) + log.V(1).Info("step", "connection", "host", p.host, "vendor", string(devices.Dell), "msg", "it's a idrac8") + return idrac8.New(ctx, p.host, p.username, p.password, log) } return bmcConnection, errors.ErrDeviceNotMatched } -func (p *Probe) idrac9() (bmcConnection interface{}, err error) { +func (p *Probe) idrac9(ctx context.Context, log logr.Logger) (bmcConnection interface{}, err error) { resp, err := p.client.Get(fmt.Sprintf("https://%s/sysmgmt/2015/bmc/info", p.host)) if err != nil { @@ -180,14 +182,14 @@ func (p *Probe) idrac9() (bmcConnection interface{}, err error) { } if resp.StatusCode == 200 && containsAnySubStr(payload, idrac9SysDesc) { - log.WithFields(log.Fields{"step": "connection", "host": p.host, "vendor": devices.Dell}).Debug("it's a idrac9") - return idrac9.New(p.host, p.username, p.password) + log.V(1).Info("step", "connection", "host", p.host, "vendor", string(devices.Dell), "msg", "it's a idrac9") + return idrac9.New(ctx, p.host, p.username, p.password, log) } return bmcConnection, errors.ErrDeviceNotMatched } -func (p *Probe) m1000e() (bmcConnection interface{}, err error) { +func (p *Probe) m1000e(ctx context.Context, log logr.Logger) (bmcConnection interface{}, err error) { resp, err := p.client.Get(fmt.Sprintf("https://%s/cgi-bin/webcgi/login", p.host)) if err != nil { return bmcConnection, err @@ -202,14 +204,14 @@ func (p *Probe) m1000e() (bmcConnection interface{}, err error) { } if resp.StatusCode == 200 && containsAnySubStr(payload, m1000eSysDesc) { - log.WithFields(log.Fields{"step": "connection", "host": p.host, "vendor": devices.Dell}).Debug("it's a m1000e chassis") - return m1000e.New(p.host, p.username, p.password) + log.V(1).Info("step", "connection", "host", p.host, "vendor", string(devices.Dell), "msg", "it's a m1000e chassis") + return m1000e.New(ctx, p.host, p.username, p.password, log) } return bmcConnection, errors.ErrDeviceNotMatched } -func (p *Probe) supermicrox() (bmcConnection interface{}, err error) { +func (p *Probe) supermicrox(ctx context.Context, log logr.Logger) (bmcConnection interface{}, err error) { resp, err := p.client.Get(fmt.Sprintf("https://%s/cgi/login.cgi", p.host)) if err != nil { return bmcConnection, err @@ -225,14 +227,14 @@ func (p *Probe) supermicrox() (bmcConnection interface{}, err error) { // looking for ATEN in the response payload isn't the most ideal way, although it is unique to Supermicros if resp.StatusCode == 200 && bytes.Contains(payload, []byte("ATEN International")) { - log.WithFields(log.Fields{"step": "connection", "host": p.host, "vendor": devices.Supermicro}).Debug("it's a supermicro") - return supermicrox.New(p.host, p.username, p.password) + log.V(1).Info("step", "connection", "host", p.host, "vendor", string(devices.Supermicro), "msg", "it's a supermicro") + return supermicrox.New(ctx, p.host, p.username, p.password, log) } return bmcConnection, errors.ErrDeviceNotMatched } -func (p *Probe) quanta() (bmcConnection interface{}, err error) { +func (p *Probe) quanta(ctx context.Context, log logr.Logger) (bmcConnection interface{}, err error) { resp, err := p.client.Get(fmt.Sprintf("https://%s/page/login.html", p.host)) if err != nil { return bmcConnection, err @@ -248,7 +250,7 @@ func (p *Probe) quanta() (bmcConnection interface{}, err error) { // ensure the response we got included a png if resp.StatusCode == 200 && bytes.Contains(payload, []byte("Quanta")) { - log.WithFields(log.Fields{"step": "ScanAndConnect", "host": p.host, "vendor": devices.Quanta}).Debug("it's a quanta") + log.V(1).Info("step", "ScanAndConnect", "host", p.host, "vendor", string(devices.Quanta), "msg", "it's a quanta") return bmcConnection, errors.NewErrUnsupportedHardware("quanta hardware not supported") } diff --git a/examples/main.go b/examples/main.go new file mode 100644 index 00000000..1470eebb --- /dev/null +++ b/examples/main.go @@ -0,0 +1,109 @@ +package main + +import ( + "os" + + "github.com/bmc-toolbox/bmclib/devices" + "github.com/bmc-toolbox/bmclib/discover" + "github.com/bombsimon/logrusr" + "github.com/sirupsen/logrus" +) + +// bmc lib takes in its opts a logger (https://github.com/go-logr/logr). +// If you do not define one, by default, it uses logrus (https://github.com/go-logr/logr) +// See the logr docs for more details, but the following implementations already exist: +// github.com/google/glog: glogr +// k8s.io/klog: klogr +// go.uber.org/zap: zapr +// log (the Go standard library logger): stdr +// github.com/sirupsen/logrus: logrusr +// github.com/wojas/genericr: genericr +func main() { + + ip := "" + user := "user" + pass := "password" + + logger := logrus.New() + logger.SetLevel(logrus.DebugLevel) + //logger.SetFormatter(&logrus.JSONFormatter{}) + + logger.Info("printing status with a user defined logger") + conn, err := withUserDefinedLogger(ip, user, pass, logger) + if err != nil { + logger.Fatal(err) + } + printStatus(conn, logger) + + logger.Info("printing status with the default builtin logger") + os.Setenv("BMCLIB_LOG_LEVEL", "debug") + conn, err = withDefaultBuiltinLogger(ip, user, pass) + if err != nil { + logger.Fatal(err) + } + printStatus(conn, logger) +} + +func withUserDefinedLogger(ip, user, pass string, logger *logrus.Logger) (interface{}, error) { + myLog := logrusr.NewLogger(logger) + opts := func(o *discover.Options) { + o.Logger = myLog + } + + return discover.ScanAndConnect(ip, user, pass, opts) +} + +func withDefaultBuiltinLogger(ip, user, pass string) (interface{}, error) { + return discover.ScanAndConnect(ip, user, pass) +} + +func printStatus(connection interface{}, logger *logrus.Logger) { + switch connection.(type) { + case devices.Bmc: + conn := connection.(devices.Bmc) + defer conn.Close() + + sr, err := conn.Serial() + if err != nil { + logger.Fatal(err) + } + logger.WithFields(logrus.Fields{"serial": sr}).Info("serial") + + md, err := conn.Model() + if err != nil { + logger.Fatal(err) + } + logger.WithFields(logrus.Fields{"model": md}).Info("model") + + mm, err := conn.Memory() + if err != nil { + logger.Fatal(err) + } + logger.WithFields(logrus.Fields{"memory": mm}).Info("memory") + + st, err := conn.Status() + if err != nil { + logger.Fatal(err) + } + logger.WithFields(logrus.Fields{"status": st}).Info("status") + + hw := conn.HardwareType() + logger.WithFields(logrus.Fields{"hwType": hw}).Info("hwType") + + state, err := conn.PowerState() + if err != nil { + logger.Fatal(err) + } + logger.WithFields(logrus.Fields{"state": state}).Info("state") + + case devices.Cmc: + cmc := connection.(devices.Cmc) + sts, err := cmc.Status() + if err != nil { + logger.Fatal(err) + } + logger.WithFields(logrus.Fields{"status": sts}).Info("status") + default: + logger.Fatal("Unknown device") + } +} diff --git a/go.mod b/go.mod index 15fe18ab..b0fd19c9 100644 --- a/go.mod +++ b/go.mod @@ -4,15 +4,18 @@ go 1.15 require ( github.com/BurntSushi/toml v0.3.1 // indirect + github.com/bombsimon/logrusr v0.0.0-20200131103305-03a291ce59b4 + github.com/go-logr/logr v0.2.1 github.com/go-playground/locales v0.12.1 // indirect github.com/go-playground/universal-translator v0.16.0 // indirect github.com/google/go-querystring v1.0.0 github.com/hashicorp/go-multierror v1.0.0 github.com/leodido/go-urn v1.1.0 // indirect - github.com/sirupsen/logrus v1.4.1 + github.com/sirupsen/logrus v1.6.0 github.com/spf13/viper v1.3.2 golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2 - golang.org/x/net v0.0.0-20190311183353-d8887717615a + golang.org/x/net v0.0.0-20190613194153-d28f0bde5980 + golang.org/x/sys v0.0.0-20200615200032-f1bc736245b1 // indirect golang.org/x/text v0.3.2 // indirect gopkg.in/go-playground/assert.v1 v1.2.1 // indirect gopkg.in/go-playground/validator.v9 v9.28.0 diff --git a/go.sum b/go.sum index e897890e..20e3a7d4 100644 --- a/go.sum +++ b/go.sum @@ -1,13 +1,19 @@ github.com/BurntSushi/toml v0.3.1 h1:WXkYYl6Yr3qBf1K79EBnL4mak0OimBfB0XUf9Vl28OQ= github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= github.com/armon/consul-api v0.0.0-20180202201655-eb2c6b5be1b6/go.mod h1:grANhF5doyWs3UAsr3K4I6qtAmlQcZDesFNEHPZAzj8= +github.com/bombsimon/logrusr v0.0.0-20200131103305-03a291ce59b4 h1:Myj4mlaLi25AoncNPb8uf+Riru0Mp4xw7S9RUxBCYxk= +github.com/bombsimon/logrusr v0.0.0-20200131103305-03a291ce59b4/go.mod h1:Jq0nHtvxabKE5EMwAAdgTaz7dfWE8C4i11NOltxGQpc= github.com/coreos/etcd v3.3.10+incompatible/go.mod h1:uF7uidLiAD3TWHmW31ZFd/JWoc32PjwdhPthX9715RE= github.com/coreos/go-etcd v2.0.0+incompatible/go.mod h1:Jez6KQU2B/sWsbdaef3ED8NzMklzPG4d5KIOhIy30Tk= github.com/coreos/go-semver v0.2.0/go.mod h1:nnelYz7RCh+5ahJtPPxZlU+153eP4D4r3EedlOD2RNk= +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= github.com/fsnotify/fsnotify v1.4.7 h1:IXs+QLmnXW2CcXuY+8Mzv/fWEsPGWxqefPtCP5CnV9I= github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo= +github.com/go-logr/logr v0.1.0/go.mod h1:ixOQHD9gLJUVQQ2ZOR7zLEifBX6tGkNJF4QyIY7sIas= +github.com/go-logr/logr v0.2.1 h1:fV3MLmabKIZ383XifUjFSwcoGee0v9qgPp8wy5svibE= +github.com/go-logr/logr v0.2.1/go.mod h1:z6/tIYblkpsD+a4lm/fGIIU9mZ+XfAiaFtq7xTgseGU= github.com/go-playground/locales v0.12.1 h1:2FITxuFt/xuCNP1Acdhv62OzaCiviiE4kotfhkmOqEc= github.com/go-playground/locales v0.12.1/go.mod h1:IUMDtCfWo/w/mtMfIE/IG2K+Ey3ygWanZIBtBW0W2TM= github.com/go-playground/universal-translator v0.16.0 h1:X++omBR/4cE2MNg91AoC3rmGrCjJ8eAeUP/K/EKx4DM= @@ -22,6 +28,15 @@ github.com/hashicorp/hcl v1.0.0 h1:0Anlzjpi4vEasTeNFn2mLJgTSwt0+6sfsiTG8qcWGx4= github.com/hashicorp/hcl v1.0.0/go.mod h1:E5yfLk+7swimpb2L/Alb/PJmXilQ/rhwaUYs4T20WEQ= github.com/konsorten/go-windows-terminal-sequences v1.0.1 h1:mweAR1A6xJ3oS2pRaGiHgQ4OO8tzTaLawm8vnODuwDk= github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= +github.com/konsorten/go-windows-terminal-sequences v1.0.2 h1:DB17ag19krx9CFsz4o3enTrPXyIXCl+2iCXH/aMAp9s= +github.com/konsorten/go-windows-terminal-sequences v1.0.2/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= +github.com/konsorten/go-windows-terminal-sequences v1.0.3 h1:CE8S1cTafDpPvMhIxNJKvHsGVBgn1xWYf1NbHQhywc8= +github.com/konsorten/go-windows-terminal-sequences v1.0.3/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= +github.com/kr/pretty v0.2.0 h1:s5hAObm+yFO5uHYt5dYjxi2rXrsnmRpJx4OYvIWUaQs= +github.com/kr/pretty v0.2.0/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI= +github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= +github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE= +github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= github.com/leodido/go-urn v1.1.0 h1:Sm1gr51B1kKyfD2BlRcLSiEkffoG96g6TPv6eRoEiB8= github.com/leodido/go-urn v1.1.0/go.mod h1:+cyI34gQWZcE1eQU7NVgKkkzdXDQHr1dBMtdAPozLkw= github.com/magiconair/properties v1.8.0 h1:LLgXmsheXeRoUOBOjtwPQCWIYqM/LU1ayDtDePerRcY= @@ -32,8 +47,10 @@ github.com/pelletier/go-toml v1.2.0 h1:T5zMGML61Wp+FlcbWjRDT7yAxhJNAiPPLOFECq181 github.com/pelletier/go-toml v1.2.0/go.mod h1:5z9KED0ma1S8pY6P1sdut58dfprrGBbd/94hg7ilaic= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= -github.com/sirupsen/logrus v1.4.1 h1:GL2rEmy6nsikmW0r8opw9JIRScdMF5hA8cOYLH7In1k= -github.com/sirupsen/logrus v1.4.1/go.mod h1:ni0Sbl8bgC9z8RoU9G6nDWqqs/fq4eDPysMBDgk/93Q= +github.com/sirupsen/logrus v1.4.2 h1:SPIRibHv4MatM3XXNO2BJeFLZwZ2LvZgfQ5+UNI2im4= +github.com/sirupsen/logrus v1.4.2/go.mod h1:tLMulIdttU9McNUspp0xgXVQah82FyeX6MwdIuYE2rE= +github.com/sirupsen/logrus v1.6.0 h1:UBcNElsrwanuuMsnGSlYmtmgbb23qDR5dG+6X6Oo89I= +github.com/sirupsen/logrus v1.6.0/go.mod h1:7uNnSEd1DgxDLC74fIahvMZmmYsHGZGEOFrfsX/uA88= github.com/spf13/afero v1.1.2 h1:m8/z1t7/fwjysjQRYbP0RD+bUIF/8tJwPdEZsI83ACI= github.com/spf13/afero v1.1.2/go.mod h1:j4pytiNVoe2o6bmDsKpLACNPDBIoEAkihy7loJ1B0CQ= github.com/spf13/cast v1.3.0 h1:oget//CVOEoFewqQxwr0Ej5yjygnqGkvggSE/gB35Q8= @@ -44,20 +61,26 @@ github.com/spf13/pflag v1.0.3 h1:zPAT6CGy6wXeQ7NtTnaTerfKOsV6V6F8agHXFiazDkg= github.com/spf13/pflag v1.0.3/go.mod h1:DYY7MBk1bdzusC3SYhjObp+wFpr4gzcvqqNjLnInEg4= github.com/spf13/viper v1.3.2 h1:VUFqw5KcqRf7i70GOzW7N+Q7+gxVBkSSqiXB12+JQ4M= github.com/spf13/viper v1.3.2/go.mod h1:ZiWeW+zYFKm7srdB9IoDzzZXaJaI5eL9QjNiN/DMA2s= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/testify v1.2.2 h1:bSDNvY7ZPG5RlJ8otE/7V6gMiyenm9RtJ7IUVIAoJ1w= github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= +github.com/stretchr/testify v1.4.0 h1:2E4SXV/wtOkTonXsotYi4li6zVWxYlZuYNCXe9XRJyk= +github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= github.com/ugorji/go/codec v0.0.0-20181204163529-d75b2dcb6bc8/go.mod h1:VFNgLljTbGfSG7qAOspJ7OScBnGdDN/yBr0sguwnwf0= github.com/xordataexchange/crypt v0.0.3-0.20170626215501-b2862e3d0a77/go.mod h1:aYKd//L2LvnjZzWKhF00oedf4jCCReLcmhLdhm1A27Q= golang.org/x/crypto v0.0.0-20181203042331-505ab145d0a9/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2 h1:VklqNMn3ovrHsnt90PveolxSbWFaJdECFbxSq0Mqo2M= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= -golang.org/x/net v0.0.0-20190311183353-d8887717615a h1:oWX7TPOiFAMXLq8o0ikBYfCJVlRHBcsciT5bXOrH628= -golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= -golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/net v0.0.0-20190613194153-d28f0bde5980 h1:dfGZHvZk057jK2MCeWus/TowKpJ8y4AmooUzdBSR9GU= +golang.org/x/net v0.0.0-20190613194153-d28f0bde5980/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/sys v0.0.0-20181205085412-a5c9d58dba9a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a h1:1BGLXjeY4akVXGgbC9HugT3Jv3hCI0z56oJR5vAMgBU= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190422165155-953cdadca894/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200124204421-9fbb57f87de9/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200615200032-f1bc736245b1 h1:ogLJMz+qpzav7lGMh10LMvAkM/fAoGlaiiHYiFYdm80= +golang.org/x/sys v0.0.0-20200615200032-f1bc736245b1/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/text v0.3.0 h1:g61tztE5qeGQ89tm6NTjjM9VPIm088od1l6aSorWRWg= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.2 h1:tW2bmiBqwgJj/UpqtC8EpXEZVYOwU0yG4iWbprSVAcs= @@ -65,9 +88,13 @@ golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15 h1:YR8cESwS4TdDjEe65xsg0ogRM/Nc3DYOhEAlW+xobZo= +gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/go-playground/assert.v1 v1.2.1 h1:xoYuJVE7KT85PYWrN730RguIQO0ePzVRfFMXadIrXTM= gopkg.in/go-playground/assert.v1 v1.2.1/go.mod h1:9RXL0bg/zibRAgZUYszZSwO/z8Y/a8bDuhia5mkpMnE= gopkg.in/go-playground/validator.v9 v9.28.0 h1:6pzvnzx1RWaaQiAmv6e1DvCFULRaz5cKoP5j1VcrLsc= gopkg.in/go-playground/validator.v9 v9.28.0/go.mod h1:+c9/zcJMFNgbLvly1L1V+PpxWdVbfP1avr/N00E2vyQ= gopkg.in/yaml.v2 v2.2.2 h1:ZCJp+EgiOT7lHqUV2J862kp8Qj64Jo6az82+3Td9dZw= gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.2.8 h1:obN1ZagJSUGI0Ek/LBmuj4SNLPfIny3KsKFopxRdj10= +gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= diff --git a/logging/logging.go b/logging/logging.go index 37904d86..2a0b7ee8 100644 --- a/logging/logging.go +++ b/logging/logging.go @@ -1,37 +1,27 @@ package logging import ( - "io" "os" - log "github.com/sirupsen/logrus" + "github.com/bombsimon/logrusr" + "github.com/go-logr/logr" + "github.com/sirupsen/logrus" ) -func init() { - log.SetFormatter(&log.JSONFormatter{}) - log.SetOutput(os.Stdout) +// DefaultLogger if no client logger is defined +func DefaultLogger() logr.Logger { + logrusLog := logrus.New() + logrusLog.SetFormatter(&logrus.JSONFormatter{}) + logrusLog.SetOutput(os.Stdout) switch os.Getenv("BMCLIB_LOG_LEVEL") { case "debug": - log.SetLevel(log.DebugLevel) + logrusLog.SetLevel(logrus.DebugLevel) case "trace": - log.SetLevel(log.TraceLevel) + logrusLog.SetLevel(logrus.TraceLevel) default: - log.SetLevel(log.InfoLevel) + logrusLog.SetLevel(logrus.InfoLevel) } -} - -// SetFormatter allows to format logrus formater -func SetFormatter(formater log.Formatter) { - log.SetFormatter(formater) -} - -// SetOutput allows to set logrus output -func SetOutput(out io.Writer) { - log.SetOutput(out) -} -// SetLevel allows to set logrus loglevel -func SetLevel(level log.Level) { - log.SetLevel(level) + return logrusr.NewLogger(logrusLog) } diff --git a/providers/dell/idrac8/actions_test.go b/providers/dell/idrac8/actions_test.go index 3a9f9bfc..973b8590 100644 --- a/providers/dell/idrac8/actions_test.go +++ b/providers/dell/idrac8/actions_test.go @@ -1,9 +1,12 @@ package idrac8 import ( + "context" "testing" "github.com/bmc-toolbox/bmclib/sshmock" + "github.com/bombsimon/logrusr" + "github.com/sirupsen/logrus" ) const ( @@ -53,7 +56,8 @@ func setupBMC() (func(), *IDrac8, error) { return nil, nil, err } - bmc, err := New(address, sshUsername, sshPassword) + testLogger := logrus.New() + bmc, err := New(context.TODO(), address, sshUsername, sshPassword, logrusr.NewLogger(testLogger)) if err != nil { tearDown() return nil, nil, err diff --git a/providers/dell/idrac8/configure.go b/providers/dell/idrac8/configure.go index 66cbf989..f2534a56 100644 --- a/providers/dell/idrac8/configure.go +++ b/providers/dell/idrac8/configure.go @@ -14,7 +14,6 @@ import ( "github.com/bmc-toolbox/bmclib/cfgresources" "github.com/bmc-toolbox/bmclib/devices" "github.com/bmc-toolbox/bmclib/internal/helper" - log "github.com/sirupsen/logrus" ) // This ensures the compiler errors if this type is missing @@ -86,25 +85,27 @@ func (i *IDrac8) User(cfgUsers []*cfgresources.User) (err error) { err = i.validateUserCfg(cfgUsers) if err != nil { msg := "User config validation failed." - log.WithFields(log.Fields{ - "step": "applyUserParams", - "IP": i.ip, - "Model": i.HardwareType(), - "Error": err, - }).Warn(msg) - return errors.New(msg) + err = errors.New(msg) + i.log.V(1).Error(err, msg, + "step", "applyUserParams", + "IP", i.ip, + "Model", i.HardwareType(), + "Error", err.Error(), + ) + return err } idracUsers, err := i.queryUsers() if err != nil { msg := "Unable to query existing users" - log.WithFields(log.Fields{ - "step": "applyUserParams", - "IP": i.ip, - "Model": i.HardwareType(), - "Error": err, - }).Warn(msg) - return errors.New(msg) + err = errors.New(msg) + i.log.V(1).Error(err, msg, + "step", "applyUserParams", + "IP", i.ip, + "Model", i.HardwareType(), + "Error", err.Error(), + ) + return err } ////for each configuration user @@ -118,13 +119,13 @@ func (i *IDrac8) User(cfgUsers []*cfgresources.User) (err error) { if uExists == false { userID, userInfo, err = getEmptyUserSlot(idracUsers) if err != nil { - log.WithFields(log.Fields{ - "IP": i.ip, - "Model": i.HardwareType(), - "step": helper.WhosCalling(), - "User": cfgUser.Name, - "Error": err, - }).Warn("Unable to add new User.") + i.log.V(1).Info("Unable to add new User.", + "IP", i.ip, + "Model", i.HardwareType(), + "step", helper.WhosCalling(), + "User", cfgUser.Name, + "Error", err.Error(), + ) continue } } @@ -145,13 +146,13 @@ func (i *IDrac8) User(cfgUsers []*cfgresources.User) (err error) { err = i.putUser(userID, userInfo) if err != nil { - log.WithFields(log.Fields{ - "IP": i.ip, - "Model": i.HardwareType(), - "step": helper.WhosCalling(), - "User": cfgUser.Name, - "Error": err, - }).Warn("Add/Update user request failed.") + i.log.V(1).Info("Add/Update user request failed.", + "IP", i.ip, + "Model", i.HardwareType(), + "step", helper.WhosCalling(), + "User", cfgUser.Name, + "Error", err.Error(), + ) continue } @@ -168,21 +169,17 @@ func (i *IDrac8) User(cfgUsers []*cfgresources.User) (err error) { err = i.putUser(userID, userInfo) if err != nil { - log.WithFields(log.Fields{ - "IP": i.ip, - "Model": i.HardwareType(), - "step": helper.WhosCalling(), - "User": cfgUser.Name, - "Error": err, - }).Warn("Disable user request failed.") + i.log.V(1).Info("Disable user request failed.", + "IP", i.ip, + "Model", i.HardwareType(), + "step", helper.WhosCalling(), + "User", cfgUser.Name, + "Error", err.Error(), + ) } } - log.WithFields(log.Fields{ - "IP": i.ip, - "Model": i.HardwareType(), - "User": cfgUser.Name, - }).Debug("User parameters applied.") + i.log.V(1).Info("User parameters applied.", "IP", i.ip, "Model", i.HardwareType(), "User", cfgUser.Name) } return err @@ -201,16 +198,12 @@ func (i *IDrac8) Syslog(cfg *cfgresources.Syslog) (err error) { enable := "Enabled" if cfg.Server == "" { - log.WithFields(log.Fields{ - "step": helper.WhosCalling(), - }).Warn("Syslog resource expects parameter: Server.") + i.log.V(1).Info("Syslog resource expects parameter: Server.", "step", helper.WhosCalling()) return } if cfg.Port == 0 { - log.WithFields(log.Fields{ - "step": helper.WhosCalling(), - }).Debug("Syslog resource port set to default: 514.") + i.log.V(1).Info("Syslog resource port set to default: 514.", "step", helper.WhosCalling()) port = 514 } else { port = cfg.Port @@ -218,9 +211,7 @@ func (i *IDrac8) Syslog(cfg *cfgresources.Syslog) (err error) { if cfg.Enable != true { enable = "Disabled" - log.WithFields(log.Fields{ - "step": helper.WhosCalling(), - }).Debug("Syslog resource declared with enable: false.") + i.log.V(1).Info("Syslog resource declared with enable: false.", "step", helper.WhosCalling()) } data := make(map[string]Syslog) @@ -235,20 +226,18 @@ func (i *IDrac8) Syslog(cfg *cfgresources.Syslog) (err error) { payload, err := json.Marshal(data) if err != nil { - log.WithFields(log.Fields{ - "step": helper.WhosCalling(), - }).Warn("Unable to marshal syslog payload.") + i.log.V(1).Error(err, "Unable to marshal syslog payload.", "step", helper.WhosCalling()) return err } endpoint := "sysmgmt/2012/server/configgroup/iDRAC.SysLog" response, _, err := i.put(endpoint, payload) if err != nil { - log.WithFields(log.Fields{ - "endpoint": endpoint, - "step": helper.WhosCalling(), - "response": fmt.Sprint(response), - }).Warn("request to set syslog configuration failed.") + i.log.V(1).Error(err, "request to set syslog configuration failed.", + "endpoint", endpoint, + "step", helper.WhosCalling(), + "response", fmt.Sprint(response), + ) return err } @@ -256,11 +245,11 @@ func (i *IDrac8) Syslog(cfg *cfgresources.Syslog) (err error) { endpoint = "data?set=alertStatus:1" response, _, err = i.post(endpoint, []byte{}, "") if err != nil { - log.WithFields(log.Fields{ - "endpoint": endpoint, - "step": helper.WhosCalling(), - "response": fmt.Sprint(response), - }).Warn("request to enable alerts failed.") + i.log.V(1).Error(err, "request to enable alerts failed.", + "endpoint", endpoint, + "step", helper.WhosCalling(), + "response", fmt.Sprint(response), + ) return err } @@ -268,18 +257,15 @@ func (i *IDrac8) Syslog(cfg *cfgresources.Syslog) (err error) { endpoint = "data?set=" + setAlertFilterPayload response, _, err = i.post(endpoint, []byte{}, "") if err != nil { - log.WithFields(log.Fields{ - "endpoint": endpoint, - "step": helper.WhosCalling(), - "response": fmt.Sprint(response), - }).Warn("request to set alerts filter configuration failed.") + i.log.V(1).Error(err, "request to set alerts filter configuration failed.", + "endpoint", endpoint, + "step", helper.WhosCalling(), + "response", fmt.Sprint(response), + ) return err } - log.WithFields(log.Fields{ - "IP": i.ip, - "Model": i.HardwareType(), - }).Debug("Syslog parameters applied.") + i.log.V(1).Info("Syslog parameters applied.", "IP", i.ip, "Model", i.HardwareType()) return err } @@ -289,16 +275,12 @@ func (i *IDrac8) Syslog(cfg *cfgresources.Syslog) (err error) { func (i *IDrac8) Ntp(cfg *cfgresources.Ntp) (err error) { if cfg.Server1 == "" { - log.WithFields(log.Fields{ - "step": "apply-ntp-cfg", - }).Warn("NTP resource expects parameter: server1.") + i.log.V(1).Info("NTP resource expects parameter: server1.", "step", "apply-ntp-cfg") return } if cfg.Timezone == "" { - log.WithFields(log.Fields{ - "step": "apply-ntp-cfg", - }).Warn("NTP resource expects parameter: timezone.") + i.log.V(1).Info("NTP resource expects parameter: timezone.", "step", "apply-ntp-cfg") return } @@ -312,9 +294,7 @@ func (i *IDrac8) applyNtpServerParam(cfg *cfgresources.Ntp) { var enable int if cfg.Enable != true { - log.WithFields(log.Fields{ - "step": helper.WhosCalling(), - }).Debug("Ntp resource declared with enable: false.") + i.log.V(1).Info("Ntp resource declared with enable: false.", "step", helper.WhosCalling()) enable = 0 } else { enable = 1 @@ -335,19 +315,16 @@ func (i *IDrac8) applyNtpServerParam(cfg *cfgresources.Ntp) { endpoint := fmt.Sprintf("data?%s", queryStr) response, err := i.get(endpoint, nil) if err != nil { - log.WithFields(log.Fields{ - "IP": i.ip, - "Model": i.HardwareType(), - "endpoint": endpoint, - "step": helper.WhosCalling(), - "response": string(response), - }).Warn("GET request failed.") + i.log.V(1).Info("GET request failed.", + "IP", i.ip, + "Model", i.HardwareType(), + "endpoint", endpoint, + "step", helper.WhosCalling(), + "response", string(response), + ) } - log.WithFields(log.Fields{ - "IP": i.ip, - "Model": i.HardwareType(), - }).Debug("NTP servers param applied.") + i.log.V(1).Info("NTP servers param applied.", "IP", i.ip, "Model", i.HardwareType()) } @@ -356,25 +333,25 @@ func (i *IDrac8) applyNtpServerParam(cfg *cfgresources.Ntp) { func (i *IDrac8) Ldap(cfg *cfgresources.Ldap) error { if cfg.Server == "" { - msg := "Ldap resource parameter Server required but not declared." - log.WithFields(log.Fields{ - "step": "applyLdapServerParam", - }).Warn(msg) - return errors.New(msg) + msg := "ldap resource parameter Server required but not declared." + err := errors.New(msg) + i.log.V(1).Error(err, msg, "step", "applyLdapServerParam") + return err } endpoint := fmt.Sprintf("data?set=xGLServer:%s", cfg.Server) response, err := i.get(endpoint, nil) if err != nil { msg := "Request to set ldap server failed." - log.WithFields(log.Fields{ - "IP": i.ip, - "Model": i.HardwareType(), - "endpoint": endpoint, - "step": helper.WhosCalling(), - "response": string(response), - }).Warn(msg) - return errors.New(msg) + err = errors.New(msg) + i.log.V(1).Error(err, msg, + "IP", i.ip, + "Model", i.HardwareType(), + "endpoint", endpoint, + "step", helper.WhosCalling(), + "response", string(response), + ) + return err } err = i.applyLdapSearchFilterParam(cfg) @@ -382,10 +359,7 @@ func (i *IDrac8) Ldap(cfg *cfgresources.Ldap) error { return err } - log.WithFields(log.Fields{ - "IP": i.ip, - "Model": i.HardwareType(), - }).Debug("Ldap server param set.") + i.log.V(1).Info("Ldap server param set.", "IP", i.ip, "Model", i.HardwareType()) return nil } @@ -395,30 +369,26 @@ func (i *IDrac8) applyLdapSearchFilterParam(cfg *cfgresources.Ldap) error { if cfg.SearchFilter == "" { msg := "Ldap resource parameter SearchFilter required but not declared." - log.WithFields(log.Fields{ - "step": "applyLdapSearchFilterParam", - }).Warn(msg) - return errors.New(msg) + err := errors.New(msg) + i.log.V(1).Error(err, msg, "step", "applyLdapSearchFilterParam") + return err } endpoint := fmt.Sprintf("data?set=xGLSearchFilter:%s", escapeLdapString(cfg.SearchFilter)) response, err := i.get(endpoint, nil) if err != nil { msg := "request to set ldap search filter failed." - log.WithFields(log.Fields{ - "IP": i.ip, - "Model": i.HardwareType(), - "endpoint": endpoint, - "step": helper.WhosCalling(), - "response": string(response), - }).Warn(msg) - return errors.New(msg) - } - - log.WithFields(log.Fields{ - "IP": i.ip, - "Model": i.HardwareType(), - }).Debug("Ldap search filter param applied.") + i.log.V(1).Error(err, msg, + "IP", i.ip, + "Model", i.HardwareType(), + "endpoint", endpoint, + "step", helper.WhosCalling(), + "response", string(response), + ) + return err + } + + i.log.V(1).Info("Ldap search filter param applied.", "IP", i.ip, "Model", i.HardwareType()) return nil } @@ -440,34 +410,30 @@ func (i *IDrac8) LdapGroup(cfgGroup []*cfgresources.LdapGroup, cfgLdap *cfgresou //first some preliminary checks if cfgLdap.Port == 0 { msg := "Ldap resource parameter Port required but not declared" - log.WithFields(log.Fields{ - "step": "applyLdapRoleGroupPrivParam", - }).Warn(msg) - return errors.New(msg) + err = errors.New(msg) + i.log.V(1).Error(err, msg, "step", "applyLdapRoleGroupPrivParam") + return err } if cfgLdap.BaseDn == "" { msg := "Ldap resource parameter BaseDn required but not declared." - log.WithFields(log.Fields{ - "step": "applyLdapRoleGroupPrivParam", - }).Warn(msg) - return errors.New(msg) + err = errors.New(msg) + i.log.V(1).Error(err, msg, "step", "applyLdapRoleGroupPrivParam") + return err } if cfgLdap.UserAttribute == "" { msg := "Ldap resource parameter userAttribute required but not declared." - log.WithFields(log.Fields{ - "step": "applyLdapRoleGroupPrivParam", - }).Warn(msg) - return errors.New(msg) + err = errors.New(msg) + i.log.V(1).Error(err, msg, "step", "applyLdapRoleGroupPrivParam") + return err } if cfgLdap.GroupAttribute == "" { msg := "Ldap resource parameter groupAttribute required but not declared." - log.WithFields(log.Fields{ - "step": "applyLdapRoleGroupPrivParam", - }).Warn(msg) - return errors.New(msg) + err = errors.New(msg) + i.log.V(1).Error(err, msg, "step", "applyLdapRoleGroupPrivParam") + return err } //for each ldap group @@ -481,38 +447,29 @@ func (i *IDrac8) LdapGroup(cfgGroup []*cfgresources.LdapGroup, cfgLdap *cfgresou if group.Role == "" { msg := "Ldap resource parameter Role required but not declared." - log.WithFields(log.Fields{ - "Role": group.Role, - "step": "applyLdapGroupParams", - }).Warn(msg) + i.log.V(1).Info(msg, "Role", group.Role, "step", "applyLdapGroupParams") continue } if group.Group == "" { msg := "Ldap resource parameter Group required but not declared." - log.WithFields(log.Fields{ - "Role": group.Role, - "step": "applyLdapGroupParams", - }).Warn(msg) - return errors.New(msg) + err = errors.New(msg) + i.log.V(1).Error(err, msg, "Role", group.Role, "step", "applyLdapGroupParams") + return err } if group.GroupBaseDn == "" { msg := "Ldap resource parameter GroupBaseDn required but not declared." - log.WithFields(log.Fields{ - "Role": group.Role, - "step": "applyLdapGroupParams", - }).Warn(msg) - return errors.New(msg) + err = errors.New(msg) + i.log.V(1).Error(err, msg, "Role", group.Role, "step", "applyLdapGroupParams") + return err } if !i.isRoleValid(group.Role) { msg := "Ldap resource Role must be a valid role: admin OR user." - log.WithFields(log.Fields{ - "Role": group.Role, - "step": "applyLdapGroupParams", - }).Warn(msg) - return errors.New(msg) + err = errors.New(msg) + i.log.V(1).Error(err, msg, "Role", group.Role, "step", "applyLdapGroupParams") + return err } groupDn := fmt.Sprintf("%s,%s", group.Group, group.GroupBaseDn) @@ -521,21 +478,21 @@ func (i *IDrac8) LdapGroup(cfgGroup []*cfgresources.LdapGroup, cfgLdap *cfgresou endpoint := fmt.Sprintf("data?set=xGLGroup%dName:%s", groupID, groupDn) response, err := i.get(endpoint, nil) if err != nil { - log.WithFields(log.Fields{ - "IP": i.ip, - "Model": i.HardwareType(), - "endpoint": endpoint, - "step": "applyLdapGroupParams", - "response": string(response), - }).Warn("GET request failed.") + i.log.V(1).Error(err, "GET request failed.", + "IP", i.ip, + "Model", i.HardwareType(), + "endpoint", endpoint, + "step", "applyLdapGroupParams", + "response", string(response), + ) return err } - log.WithFields(log.Fields{ - "IP": i.ip, - "Model": i.HardwareType(), - "Role": group.Role, - }).Debug("Ldap GroupDN config applied.") + i.log.V(1).Info("Ldap GroupDN config applied.", + "IP", i.ip, + "Model", i.HardwareType(), + "Role", group.Role, + ) switch group.Role { case "user": @@ -556,11 +513,11 @@ func (i *IDrac8) LdapGroup(cfgGroup []*cfgresources.LdapGroup, cfgLdap *cfgresou err = i.applyLdapRoleGroupPrivParam(cfgLdap, groupPrivilegeParam) if err != nil { - log.WithFields(log.Fields{ - "IP": i.ip, - "Model": i.HardwareType(), - "step": "applyLdapGroupParams", - }).Warn("Unable to set Ldap Role Group Privileges.") + i.log.V(1).Error(err, "Unable to set Ldap Role Group Privileges.", + "IP", i.ip, + "Model", i.HardwareType(), + "step", "applyLdapGroupParams", + ) return err } return err @@ -594,21 +551,18 @@ func (i *IDrac8) applyLdapRoleGroupPrivParam(cfg *cfgresources.Ldap, groupPrivil endpoint := "postset?ldapconf" responseCode, responseBody, err := i.post(endpoint, []byte(payload), "") if err != nil || responseCode != 200 { - log.WithFields(log.Fields{ - "IP": i.ip, - "Model": i.HardwareType(), - "endpoint": endpoint, - "step": helper.WhosCalling(), - "responseCode": responseCode, - "response": string(responseBody), - }).Warn("POST request failed.") + i.log.V(1).Error(err, "POST request failed.", + "IP", i.ip, + "Model", i.HardwareType(), + "endpoint", endpoint, + "step", helper.WhosCalling(), + "responseCode", responseCode, + "response", string(responseBody), + ) return err } - log.WithFields(log.Fields{ - "IP": i.ip, - "Model": i.HardwareType(), - }).Debug("Ldap Group role privileges applied.") + i.log.V(1).Info("Ldap Group role privileges applied.", "IP", i.ip, "Model", i.HardwareType()) return err } @@ -621,19 +575,16 @@ func (i *IDrac8) applyTimezoneParam(timezone string) { endpoint := fmt.Sprintf("data?set=tm_tz_str_zone:%s", timezone) response, err := i.get(endpoint, nil) if err != nil { - log.WithFields(log.Fields{ - "IP": i.ip, - "Model": i.HardwareType(), - "endpoint": endpoint, - "step": helper.WhosCalling(), - "response": string(response), - }).Warn("GET request failed.") + i.log.V(1).Info("GET request failed.", + "IP", i.ip, + "Model", i.HardwareType(), + "endpoint", endpoint, + "step", helper.WhosCalling(), + "response", string(response), + ) } - log.WithFields(log.Fields{ - "IP": i.ip, - "Model": i.HardwareType(), - }).Debug("Timezone param applied.") + i.log.V(1).Info("Timezone param applied.", "IP", i.ip, "Model", i.HardwareType()) } @@ -674,21 +625,18 @@ func (i *IDrac8) Network(cfg *cfgresources.Network) (reset bool, err error) { responseCode, responseBody, err := i.post(endpoint, []byte(payload), "") if err != nil || responseCode != 200 { - log.WithFields(log.Fields{ - "IP": i.ip, - "Model": i.HardwareType(), - "endpoint": endpoint, - "step": helper.WhosCalling(), - "responseCode": responseCode, - "response": string(responseBody), - }).Warn("POST request to set Network params failed.") + i.log.V(1).Error(err, "POST request to set Network params failed.", + "IP", i.ip, + "Model", i.HardwareType(), + "endpoint", endpoint, + "step", helper.WhosCalling(), + "responseCode", responseCode, + "response", string(responseBody), + ) return reset, err } - log.WithFields(log.Fields{ - "IP": i.ip, - "Model": i.HardwareType(), - }).Debug("Network config parameters applied.") + i.log.V(1).Info("Network config parameters applied.", "IP", i.ip, "Model", i.HardwareType()) return reset, err } @@ -713,13 +661,13 @@ func (i *IDrac8) GenerateCSR(cert *cfgresources.HTTPSCertAttributes) ([]byte, er body, err := i.get(queryString, nil) if err != nil { - log.WithFields(log.Fields{ - "IP": i.ip, - "Model": i.HardwareType(), - "endpoint": endpoint, - "step": helper.WhosCalling(), - "Error": err, - }).Warn("GET request failed.") + i.log.V(1).Error(err, "GET request failed.", + "IP", i.ip, + "Model", i.HardwareType(), + "endpoint", endpoint, + "step", helper.WhosCalling(), + "Error", err.Error(), + ) return []byte{}, err } @@ -771,13 +719,13 @@ func (i *IDrac8) UploadHTTPSCert(cert []byte, certFileName string, key []byte, k // 1. POST upload x509 cert status, body, err := i.post(endpoint, form.Bytes(), w.FormDataContentType()) if err != nil || status != 201 { - log.WithFields(log.Fields{ - "IP": i.ip, - "Model": i.HardwareType(), - "endpoint": endpoint, - "step": helper.WhosCalling(), - "status": status, - }).Warn("Cert form upload POST request failed, expected 201.") + i.log.V(1).Error(err, "Cert form upload POST request failed, expected 201.", + "IP", i.ip, + "Model", i.HardwareType(), + "endpoint", endpoint, + "step", helper.WhosCalling(), + "status", status, + ) return false, err } @@ -785,23 +733,23 @@ func (i *IDrac8) UploadHTTPSCert(cert []byte, certFileName string, key []byte, k var certStore = new(certStore) err = json.Unmarshal(body, certStore) if err != nil { - log.WithFields(log.Fields{ - "step": helper.WhosCalling(), - "IP": i.ip, - "Model": i.HardwareType(), - "Error": err, - }).Warn("Unable to unmarshal cert store response payload.") + i.log.V(1).Error(err, "Unable to unmarshal cert store response payload.", + "step", helper.WhosCalling(), + "IP", i.ip, + "Model", i.HardwareType(), + "Error", err.Error(), + ) return false, err } resourceURI, err := json.Marshal(certStore.File) if err != nil { - log.WithFields(log.Fields{ - "step": helper.WhosCalling(), - "IP": i.ip, - "Model": i.HardwareType(), - "Error": err, - }).Warn("Unable to marshal cert store resource URI.") + i.log.V(1).Error(err, "Unable to marshal cert store resource URI.", + "step", helper.WhosCalling(), + "IP", i.ip, + "Model", i.HardwareType(), + "Error", err.Error(), + ) return false, err } @@ -809,13 +757,13 @@ func (i *IDrac8) UploadHTTPSCert(cert []byte, certFileName string, key []byte, k endpoint = "sysmgmt/2012/server/network/ssl/cert" status, _, err = i.post(endpoint, []byte(resourceURI), "") if err != nil || status != 201 { - log.WithFields(log.Fields{ - "IP": i.ip, - "Model": i.HardwareType(), - "endpoint": endpoint, - "step": helper.WhosCalling(), - "status": status, - }).Warn("Cert form upload POST request failed, expected 201.") + i.log.V(1).Error(err, "Cert form upload POST request failed, expected 201.", + "IP", i.ip, + "Model", i.HardwareType(), + "endpoint", endpoint, + "step", helper.WhosCalling(), + "status", status, + ) return false, err } diff --git a/providers/dell/idrac8/idrac8.go b/providers/dell/idrac8/idrac8.go index 23241d88..c894c530 100644 --- a/providers/dell/idrac8/idrac8.go +++ b/providers/dell/idrac8/idrac8.go @@ -2,6 +2,7 @@ package idrac8 import ( "bytes" + "context" "encoding/json" "encoding/xml" "fmt" @@ -17,10 +18,7 @@ import ( "github.com/bmc-toolbox/bmclib/internal/httpclient" "github.com/bmc-toolbox/bmclib/internal/sshclient" "github.com/bmc-toolbox/bmclib/providers/dell" - - // this make possible to setup logging and properties at any stage - _ "github.com/bmc-toolbox/bmclib/logging" - log "github.com/sirupsen/logrus" + "github.com/go-logr/logr" ) const ( @@ -38,16 +36,18 @@ type IDrac8 struct { st1 string st2 string iDracInventory *dell.IDracInventory + ctx context.Context + log logr.Logger } // New returns a new IDrac8 ready to be used -func New(host string, username string, password string) (*IDrac8, error) { +func New(ctx context.Context, host string, username string, password string, log logr.Logger) (*IDrac8, error) { sshClient, err := sshclient.New(host, username, password) if err != nil { return nil, err } - return &IDrac8{ip: host, username: username, password: password, sshClient: sshClient}, err + return &IDrac8{ip: host, username: username, password: password, sshClient: sshClient, ctx: ctx, log: log}, err } // CheckCredentials verify whether the credentials are valid or not @@ -80,15 +80,8 @@ func (i *IDrac8) put(endpoint string, payload []byte) (statusCode int, response } } - if log.GetLevel() == log.TraceLevel { - dump, err := httputil.DumpRequestOut(req, true) - if err == nil { - log.Println(fmt.Sprintf("[Request] %s/%s", bmcURL, endpoint)) - log.Println(">>>>>>>>>>>>>>>") - log.Printf("%s\n\n", dump) - log.Println(">>>>>>>>>>>>>>>") - } - } + reqDump, _ := httputil.DumpRequestOut(req, true) + i.log.V(2).Info("requestTrace", "requestDump", string(reqDump), "url", fmt.Sprintf("%s/%s", bmcURL, endpoint)) resp, err := i.httpClient.Do(req) if err != nil { @@ -96,15 +89,8 @@ func (i *IDrac8) put(endpoint string, payload []byte) (statusCode int, response } defer resp.Body.Close() - if log.GetLevel() == log.TraceLevel { - dump, err := httputil.DumpResponse(resp, true) - if err == nil { - log.Println("[Response]") - log.Println("<<<<<<<<<<<<<<") - log.Printf("%s\n\n", dump) - log.Println("<<<<<<<<<<<<<<") - } - } + respDump, _ := httputil.DumpResponse(resp, true) + i.log.V(2).Info("responseTrace", "responseDump", string(respDump)) response, err = ioutil.ReadAll(resp.Body) if err != nil { @@ -153,30 +139,16 @@ func (i *IDrac8) post(endpoint string, data []byte, formDataContentType string) req.AddCookie(c) } - if log.GetLevel() == log.TraceLevel { - dump, err := httputil.DumpRequestOut(req, true) - if err == nil { - log.Println(fmt.Sprintf("[Request] https://%s/%s", i.ip, endpoint)) - log.Println(">>>>>>>>>>>>>>>") - log.Printf("%s\n\n", dump) - log.Println(">>>>>>>>>>>>>>>") - } - } + reqDump, _ := httputil.DumpRequestOut(req, true) + i.log.V(2).Info("requestTrace", "requestDump", string(reqDump), "url", fmt.Sprintf("https://%s/%s", i.ip, endpoint)) resp, err := i.httpClient.Do(req) if err != nil { return 0, []byte{}, err } defer resp.Body.Close() - if log.GetLevel() == log.TraceLevel { - dump, err := httputil.DumpResponse(resp, true) - if err == nil { - log.Println("[Response]") - log.Println("<<<<<<<<<<<<<<") - log.Printf("%s\n\n", dump) - log.Println("<<<<<<<<<<<<<<") - } - } + respDump, _ := httputil.DumpResponse(resp, true) + i.log.V(2).Info("responseTrace", "responseDump", string(respDump)) body, err = ioutil.ReadAll(resp.Body) if err != nil { @@ -189,7 +161,7 @@ func (i *IDrac8) post(endpoint string, data []byte, formDataContentType string) // get calls a given json endpoint of the ilo and returns the data func (i *IDrac8) get(endpoint string, extraHeaders *map[string]string) (payload []byte, err error) { - log.WithFields(log.Fields{"step": "bmc connection", "vendor": dell.VendorID, "ip": i.ip, "endpoint": endpoint}).Debug("retrieving data from bmc") + i.log.V(1).Info("retrieving data from bmc", "step", "bmc connection", "vendor", dell.VendorID, "ip", i.ip, "endpoint", endpoint) bmcURL := fmt.Sprintf("https://%s", i.ip) req, err := http.NewRequest("GET", fmt.Sprintf("%s/%s", bmcURL, endpoint), nil) @@ -213,30 +185,16 @@ func (i *IDrac8) get(endpoint string, extraHeaders *map[string]string) (payload req.AddCookie(cookie) } } - if log.GetLevel() == log.TraceLevel { - dump, err := httputil.DumpRequestOut(req, true) - if err == nil { - log.Println(fmt.Sprintf("[Request] https://%s/%s", bmcURL, endpoint)) - log.Println(">>>>>>>>>>>>>>>") - log.Printf("%s\n\n", dump) - log.Println(">>>>>>>>>>>>>>>") - } - } + reqDump, _ := httputil.DumpRequestOut(req, true) + i.log.V(2).Info("requestTrace", "requestDump", string(reqDump), "url", fmt.Sprintf("%s/%s", bmcURL, endpoint)) resp, err := i.httpClient.Do(req) if err != nil { return payload, err } defer resp.Body.Close() - if log.GetLevel() == log.TraceLevel { - dump, err := httputil.DumpResponse(resp, true) - if err == nil { - log.Println("[Response]") - log.Println("<<<<<<<<<<<<<<") - log.Printf("%s\n\n", dump) - log.Println("<<<<<<<<<<<<<<") - } - } + respDump, _ := httputil.DumpResponse(resp, true) + i.log.V(2).Info("responseTrace", "responseDump", string(respDump)) payload, err = ioutil.ReadAll(resp.Body) if err != nil { diff --git a/providers/dell/idrac8/idrac8_test.go b/providers/dell/idrac8/idrac8_test.go index 2e9b6e37..6314cf5c 100644 --- a/providers/dell/idrac8/idrac8_test.go +++ b/providers/dell/idrac8/idrac8_test.go @@ -1,12 +1,15 @@ package idrac8 import ( + "context" "net/http" "net/http/httptest" "strings" "testing" "github.com/bmc-toolbox/bmclib/devices" + "github.com/bombsimon/logrusr" + "github.com/sirupsen/logrus" "github.com/spf13/viper" ) @@ -5223,8 +5226,13 @@ var ( } ) +func init() { + if viper.GetBool("debug") != true { + viper.SetDefault("debug", true) + } +} + func setup() (bmc *IDrac8, err error) { - viper.SetDefault("debug", true) mux = http.NewServeMux() server = httptest.NewTLSServer(mux) ip := strings.TrimPrefix(server.URL, "https://") @@ -5238,7 +5246,8 @@ func setup() (bmc *IDrac8, err error) { }) } - bmc, err = New(ip, username, password) + testLogger := logrus.New() + bmc, err = New(context.TODO(), ip, username, password, logrusr.NewLogger(testLogger)) if err != nil { return bmc, err } diff --git a/providers/dell/idrac8/query.go b/providers/dell/idrac8/query.go index 041b27a5..7aa24e3c 100644 --- a/providers/dell/idrac8/query.go +++ b/providers/dell/idrac8/query.go @@ -11,7 +11,6 @@ import ( "time" "github.com/bmc-toolbox/bmclib/internal/helper" - log "github.com/sirupsen/logrus" ) // CurrentHTTPSCert returns the current x509 certficates configured on the BMC @@ -77,26 +76,26 @@ func (i *IDrac8) queryUsers() (userInfo UserInfo, err error) { response, err := i.get(endpoint, &map[string]string{}) if err != nil { - log.WithFields(log.Fields{ - "IP": i.ip, - "Model": i.HardwareType(), - "endpoint": endpoint, - "step": helper.WhosCalling(), - "Error": err, - }).Warn("GET request failed.") + i.log.V(1).Error(err, "GET request failed.", + "IP", i.ip, + "Model", i.HardwareType(), + "endpoint", endpoint, + "step", helper.WhosCalling(), + "Error", err.Error(), + ) return userInfo, err } xmlData := XMLRoot{} err = xml.Unmarshal(response, &xmlData) if err != nil { - log.WithFields(log.Fields{ - "step": "queryUserInfo", - "resource": "User", - "IP": i.ip, - "Model": i.HardwareType(), - "Error": err, - }).Warn("Unable to unmarshal payload.") + i.log.V(1).Error(err, "Unable to unmarshal payload.", + "step", "queryUserInfo", + "resource", "User", + "IP", i.ip, + "Model", i.HardwareType(), + "Error", err.Error(), + ) return userInfo, err } diff --git a/providers/dell/idrac8/setupConnections.go b/providers/dell/idrac8/setupConnections.go index ecfbb18c..aa9f46ce 100644 --- a/providers/dell/idrac8/setupConnections.go +++ b/providers/dell/idrac8/setupConnections.go @@ -13,10 +13,6 @@ import ( "github.com/bmc-toolbox/bmclib/internal/httpclient" "github.com/bmc-toolbox/bmclib/providers/dell" multierror "github.com/hashicorp/go-multierror" - - // this make possible to setup logging and properties at any stage - _ "github.com/bmc-toolbox/bmclib/logging" - log "github.com/sirupsen/logrus" ) func (i *IDrac8) httpLogin() (err error) { @@ -29,7 +25,7 @@ func (i *IDrac8) httpLogin() (err error) { return err } - log.WithFields(log.Fields{"step": "bmc connection", "vendor": dell.VendorID, "ip": i.ip}).Debug("connecting to bmc") + i.log.V(1).Info("connecting to bmc", "step", "bmc connection", "vendor", dell.VendorID, "ip", i.ip) data := fmt.Sprintf("user=%s&password=%s", i.username, i.password) url := fmt.Sprintf("https://%s/data/login", i.ip) diff --git a/providers/dell/idrac9/actions_test.go b/providers/dell/idrac9/actions_test.go index a7a323d6..fa35bb31 100644 --- a/providers/dell/idrac9/actions_test.go +++ b/providers/dell/idrac9/actions_test.go @@ -1,9 +1,12 @@ package idrac9 import ( + "context" "testing" "github.com/bmc-toolbox/bmclib/sshmock" + "github.com/bombsimon/logrusr" + "github.com/sirupsen/logrus" ) const ( @@ -53,7 +56,8 @@ func setupBMC() (func(), *IDrac9, error) { return nil, nil, err } - bmc, err := New(address, sshUsername, sshPassword) + testLogger := logrus.New() + bmc, err := New(context.TODO(), address, sshUsername, sshPassword, logrusr.NewLogger(testLogger)) if err != nil { tearDown() return nil, nil, err diff --git a/providers/dell/idrac9/configure.go b/providers/dell/idrac9/configure.go index 12eb23e6..719a182b 100644 --- a/providers/dell/idrac9/configure.go +++ b/providers/dell/idrac9/configure.go @@ -13,7 +13,6 @@ import ( "github.com/bmc-toolbox/bmclib/devices" "github.com/bmc-toolbox/bmclib/internal/helper" - log "github.com/sirupsen/logrus" "gopkg.in/go-playground/validator.v9" ) @@ -56,10 +55,7 @@ func (i *IDrac9) Bios(cfg *cfgresources.Bios) (err error) { validate := validator.New() err = validate.Struct(newBiosSettings) if err != nil { - log.WithFields(log.Fields{ - "step": "applyBiosParams", - "Error": err, - }).Fatal("Config validation failed.") + i.log.V(1).Error(err, "Config validation failed.", "step", "applyBiosParams", "Error", err.Error()) return err } @@ -67,12 +63,12 @@ func (i *IDrac9) Bios(cfg *cfgresources.Bios) (err error) { currentBiosSettings, err := i.getBiosSettings() if err != nil || currentBiosSettings == nil { msg := "Unable to get current bios settings through redfish." - log.WithFields(log.Fields{ - "IP": i.ip, - "Model": i.HardwareType(), - "step": helper.WhosCalling(), - "Error": err, - }).Warn(msg) + i.log.V(1).Error(err, msg, + "IP", i.ip, + "Model", i.HardwareType(), + "step", helper.WhosCalling(), + "Error", err.Error(), + ) return errors.New(msg) } @@ -82,59 +78,60 @@ func (i *IDrac9) Bios(cfg *cfgresources.Bios) (err error) { //retrieve fields that is the config to be applied toApplyBiosSettings, err := diffBiosSettings(newBiosSettings, currentBiosSettings) if err != nil { - log.WithFields(log.Fields{ - "IP": i.ip, - "Model": i.HardwareType(), - "step": helper.WhosCalling(), - "Error": err, - }).Fatal("diffBiosSettings returned error.") + i.log.V(1).Error(err, "diffBiosSettings returned error.", + "IP", i.ip, + "Model", i.HardwareType(), + "step", helper.WhosCalling(), + "Error", err.Error(), + ) + return err } - log.WithFields(log.Fields{ - "IP": i.ip, - "Model": i.HardwareType(), - "step": helper.WhosCalling(), - "Changes (Ignore empty fields)": fmt.Sprintf("%+v", toApplyBiosSettings), - }).Info("Bios configuration to be applied.") + i.log.V(0).Info("Bios configuration to be applied", + "IP", i.ip, + "Model", i.HardwareType(), + "step", helper.WhosCalling(), + "Changes (Ignore empty fields)", fmt.Sprintf("%+v", toApplyBiosSettings), + ) //purge any existing pending bios setting jobs //or we will not be able to set any params err = i.purgeJobsForBiosSettings() if err != nil { - log.WithFields(log.Fields{ - "step": "applyBiosParams", - "resource": "Bios", - "IP": i.ip, - "Model": i.HardwareType(), - "Bios settings pending": err, - }).Warn("Unable to purge pending bios setting jobs.") + i.log.V(1).Info("Unable to purge pending bios setting jobs.", + "step", "applyBiosParams", + "resource", "Bios", + "IP", i.ip, + "Model", i.HardwareType(), + "Bios settings pending", err.Error(), + ) } err = i.setBiosSettings(toApplyBiosSettings) if err != nil { msg := "setBiosAttributes returned error." - log.WithFields(log.Fields{ - "IP": i.ip, - "Model": i.HardwareType(), - "step": helper.WhosCalling(), - "Error": err, - }).Warn(msg) + i.log.V(1).Error(err, msg, + "IP", i.ip, + "Model", i.HardwareType(), + "step", helper.WhosCalling(), + "Error", err.Error(), + ) return errors.New(msg) } - log.WithFields(log.Fields{ - "IP": i.ip, - "Model": i.HardwareType(), - "step": helper.WhosCalling(), - }).Info("Bios configuration update job queued in iDrac.") + i.log.V(0).Info("Bios configuration update job queued in iDrac.", + "IP", i.ip, + "Model", i.HardwareType(), + "step", helper.WhosCalling(), + ) } else { - log.WithFields(log.Fields{ - "IP": i.ip, - "Model": i.HardwareType(), - "step": helper.WhosCalling(), - }).Info("Bios configuration is up to date.") + i.log.V(0).Info("Bios configuration is up to date.", + "IP", i.ip, + "Model", i.HardwareType(), + "step", helper.WhosCalling(), + ) } return err @@ -150,24 +147,24 @@ func (i *IDrac9) User(cfgUsers []*cfgresources.User) (err error) { err = i.validateCfg(cfgUsers) if err != nil { msg := "Config validation failed." - log.WithFields(log.Fields{ - "step": "applyUserParams", - "IP": i.ip, - "Model": i.HardwareType(), - "Error": err, - }).Warn(msg) + i.log.V(1).Error(err, msg, + "step", "applyUserParams", + "IP", i.ip, + "Model", i.HardwareType(), + "Error", err.Error(), + ) return errors.New(msg) } idracUsers, err := i.queryUsers() if err != nil { msg := "Unable to query existing users" - log.WithFields(log.Fields{ - "step": "applyUserParams", - "IP": i.ip, - "Model": i.HardwareType(), - "Error": err, - }).Warn(msg) + i.log.V(1).Error(err, msg, + "step", "applyUserParams", + "IP", i.ip, + "Model", i.HardwareType(), + "Error", err.Error(), + ) return errors.New(msg) } @@ -183,13 +180,13 @@ func (i *IDrac9) User(cfgUsers []*cfgresources.User) (err error) { if uExists == false { userID, userInfo, err = getEmptyUserSlot(idracUsers) if err != nil { - log.WithFields(log.Fields{ - "IP": i.ip, - "Model": i.HardwareType(), - "step": helper.WhosCalling(), - "User": cfgUser.Name, - "Error": err, - }).Warn("Unable to add new User.") + i.log.V(1).Error(err, "Unable to add new User.", + "IP", i.ip, + "Model", i.HardwareType(), + "step", helper.WhosCalling(), + "User", cfgUser.Name, + "Error", err.Error(), + ) continue } } @@ -210,13 +207,13 @@ func (i *IDrac9) User(cfgUsers []*cfgresources.User) (err error) { err = i.putUser(userID, userInfo) if err != nil { - log.WithFields(log.Fields{ - "IP": i.ip, - "Model": i.HardwareType(), - "step": helper.WhosCalling(), - "User": cfgUser.Name, - "Error": err, - }).Warn("Add/Update user request failed.") + i.log.V(1).Error(err, "Add/Update user request failed.", + "IP", i.ip, + "Model", i.HardwareType(), + "step", helper.WhosCalling(), + "User", cfgUser.Name, + "Error", err.Error(), + ) continue } @@ -227,24 +224,24 @@ func (i *IDrac9) User(cfgUsers []*cfgresources.User) (err error) { endpoint := fmt.Sprintf("sysmgmt/2017/server/user?userid=%d", userID) statusCode, response, err := i.delete(endpoint) if err != nil { - log.WithFields(log.Fields{ - "IP": i.ip, - "Model": i.HardwareType(), - "step": helper.WhosCalling(), - "User": cfgUser.Name, - "Error": err, - "StatusCode": statusCode, - "Response": response, - }).Warn("Delete user request failed.") + i.log.V(1).Error(err, "Delete user request failed.", + "IP", i.ip, + "Model", i.HardwareType(), + "step", helper.WhosCalling(), + "User", cfgUser.Name, + "Error", err.Error(), + "StatusCode", statusCode, + "Response", response, + ) continue } } - log.WithFields(log.Fields{ - "IP": i.ip, - "Model": i.HardwareType(), - "User": cfgUser.Name, - }).Debug("User parameters applied.") + i.log.V(1).Info("User parameters applied.", + "IP", i.ip, + "Model", i.HardwareType(), + "User", cfgUser.Name, + ) } @@ -266,21 +263,23 @@ func (i *IDrac9) Ldap(cfg *cfgresources.Ldap) (err error) { if cfg.Server == "" { msg := "Ldap resource parameter Server required but not declared." - log.WithFields(log.Fields{ - "IP": i.ip, - "Model": i.HardwareType(), - "step": helper.WhosCalling, - }).Warn(msg) - return errors.New(msg) + err = errors.New(msg) + i.log.V(1).Error(err, msg, + "IP", i.ip, + "Model", i.HardwareType(), + "step", helper.WhosCalling, + ) + return err } if cfg.BaseDn == "" { msg := "Ldap resource parameter BaseDn required but not declared." - log.WithFields(log.Fields{ - "Model": i.HardwareType(), - "step": helper.WhosCalling, - }).Warn(msg) - return errors.New(msg) + err = errors.New(msg) + i.log.V(1).Error(err, msg, + "Model", i.HardwareType(), + "step", helper.WhosCalling, + ) + return err } if cfg.Enable { @@ -318,14 +317,15 @@ func (i *IDrac9) Ldap(cfg *cfgresources.Ldap) (err error) { err = i.putLdap(payload) if err != nil { - msg := "Ldap params PUT request failed." - log.WithFields(log.Fields{ - "IP": i.ip, - "Model": i.HardwareType(), - "step": helper.WhosCalling(), - "Error": err, - }).Warn(msg) - return errors.New("Ldap params put request failed") + msg := "ldap params PUT request failed." + err = errors.New(msg) + i.log.V(1).Error(err, msg, + "IP", i.ip, + "Model", i.HardwareType(), + "step", helper.WhosCalling(), + "Error", err.Error(), + ) + return err } return err @@ -339,13 +339,14 @@ func (i *IDrac9) LdapGroup(cfg []*cfgresources.LdapGroup, cfgLdap *cfgresources. idracLdapRoleGroups, err := i.queryLdapRoleGroups() if err != nil { msg := "Unable to query existing users" - log.WithFields(log.Fields{ - "step": "applyUserParams", - "IP": i.ip, - "Model": i.HardwareType(), - "Error": err, - }).Warn(msg) - return errors.New(msg) + err = errors.New(msg) + i.log.V(1).Error(err, msg, + "step", "applyUserParams", + "IP", i.ip, + "Model", i.HardwareType(), + "Error", err.Error(), + ) + return err } //for each configuration ldap role group @@ -365,14 +366,14 @@ func (i *IDrac9) LdapGroup(cfg []*cfgresources.LdapGroup, cfgLdap *cfgresources. if rExists == false { roleID, role, err = getEmptyLdapRoleGroupSlot(idracLdapRoleGroups) if err != nil { - log.WithFields(log.Fields{ - "IP": i.ip, - "Model": i.HardwareType(), - "step": helper.WhosCalling(), - "Ldap Role Group": cfgRole.Group, - "Role Group DN": cfgRole.Role, - "Error": err, - }).Warn("Unable to add new Ldap Role Group.") + i.log.V(1).Error(err, "Unable to add new Ldap Role Group.", + "IP", i.ip, + "Model", i.HardwareType(), + "step", helper.WhosCalling(), + "Ldap Role Group", cfgRole.Group, + "Role Group DN", cfgRole.Role, + "Error", err.Error(), + ) continue } } @@ -388,14 +389,14 @@ func (i *IDrac9) LdapGroup(cfg []*cfgresources.LdapGroup, cfgLdap *cfgresources. err = i.putLdapRoleGroup(roleID, role) if err != nil { - log.WithFields(log.Fields{ - "IP": i.ip, - "Model": i.HardwareType(), - "step": helper.WhosCalling(), - "Ldap Role Group": cfgRole.Group, - "Role Group DN": cfgRole.Role, - "Error": err, - }).Warn("Add/Update LDAP Role Group request failed.") + i.log.V(1).Error(err, "Add/Update LDAP Role Group request failed.", + "IP", i.ip, + "Model", i.HardwareType(), + "step", helper.WhosCalling(), + "Ldap Role Group", cfgRole.Group, + "Role Group DN", cfgRole.Role, + "Error", err.Error(), + ) continue } @@ -408,25 +409,25 @@ func (i *IDrac9) LdapGroup(cfg []*cfgresources.LdapGroup, cfgLdap *cfgresources. role.Privilege = "0" err = i.putLdapRoleGroup(roleID, role) if err != nil { - log.WithFields(log.Fields{ - "IP": i.ip, - "Model": i.HardwareType(), - "step": helper.WhosCalling(), - "Ldap Role Group": cfgRole.Group, - "Role Group DN": cfgRole.Role, - "Error": err, - }).Warn("Remove LDAP Role Group request failed.") + i.log.V(1).Error(err, "Remove LDAP Role Group request failed.", + "IP", i.ip, + "Model", i.HardwareType(), + "step", helper.WhosCalling(), + "Ldap Role Group", cfgRole.Group, + "Role Group DN", cfgRole.Role, + "Error", err.Error(), + ) continue } } - log.WithFields(log.Fields{ - "IP": i.ip, - "Model": i.HardwareType(), - "Step": helper.WhosCalling(), - "Ldap Role Group": cfgRole.Role, - "Role Group DN": cfgRole.Role, - }).Debug("Ldap Role Group parameters applied.") + i.log.V(1).Info("Ldap Role Group parameters applied.", + "IP", i.ip, + "Model", i.HardwareType(), + "Step", helper.WhosCalling(), + "Ldap Role Group", cfgRole.Role, + "Role Group DN", cfgRole.Role, + ) } @@ -447,45 +448,48 @@ func (i *IDrac9) Ntp(cfg *cfgresources.Ntp) (err error) { if cfg.Server1 == "" { msg := "NTP resource expects parameter: server1." - log.WithFields(log.Fields{ - "IP": i.ip, - "Model": i.HardwareType(), - "Step": helper.WhosCalling(), - }).Warn(msg) - return errors.New(msg) + err = errors.New(msg) + i.log.V(1).Error(err, msg, + "IP", i.ip, + "Model", i.HardwareType(), + "Step", helper.WhosCalling(), + ) + return err } if cfg.Timezone == "" { msg := "NTP resource expects parameter: timezone." - log.WithFields(log.Fields{ - "IP": i.ip, - "Model": i.HardwareType(), - "Step": helper.WhosCalling(), - }).Warn(msg) - return errors.New(msg) + err = errors.New(msg) + i.log.V(1).Error(err, msg, + "IP", i.ip, + "Model", i.HardwareType(), + "Step", helper.WhosCalling(), + ) + return err } _, validTimezone := Timezones[cfg.Timezone] if !validTimezone { msg := "NTP resource a valid timezone parameter, for valid timezones see dell/idrac9/model.go" - log.WithFields(log.Fields{ - "IP": i.ip, - "Model": i.HardwareType(), - "step": helper.WhosCalling(), - "Unknown Timezone": cfg.Timezone, - }).Warn(msg) - return errors.New(msg) + err = errors.New(msg) + i.log.V(1).Error(err, msg, + "IP", i.ip, + "Model", i.HardwareType(), + "step", helper.WhosCalling(), + "Unknown Timezone", cfg.Timezone, + ) + return err } err = i.putTimezone(Timezone{Timezone: cfg.Timezone}) if err != nil { - log.WithFields(log.Fields{ - "IP": i.ip, - "Model": i.HardwareType(), - "step": helper.WhosCalling(), - "Timezone": cfg.Timezone, - "Error": err, - }).Warn("PUT timezone request failed.") + i.log.V(1).Error(err, "PUT timezone request failed.", + "IP", i.ip, + "Model", i.HardwareType(), + "step", helper.WhosCalling(), + "Timezone", cfg.Timezone, + "Error", err.Error(), + ) return err } @@ -498,19 +502,19 @@ func (i *IDrac9) Ntp(cfg *cfgresources.Ntp) (err error) { err = i.putNtpConfig(payload) if err != nil { - log.WithFields(log.Fields{ - "IP": i.ip, - "Model": i.HardwareType(), - "step": helper.WhosCalling(), - "Error": err, - }).Warn("PUT Ntp request failed.") + i.log.V(1).Error(err, "PUT Ntp request failed.", + "IP", i.ip, + "Model", i.HardwareType(), + "step", helper.WhosCalling(), + "Error", err.Error(), + ) return err } - log.WithFields(log.Fields{ - "IP": i.ip, - "Model": i.HardwareType(), - }).Debug("NTP servers param applied.") + i.log.V(1).Info("NTP servers param applied.", + "IP", i.ip, + "Model", i.HardwareType(), + ) return err } @@ -528,18 +532,16 @@ func (i *IDrac9) Syslog(cfg *cfgresources.Syslog) (err error) { enable := "Enabled" if cfg.Server == "" { - log.WithFields(log.Fields{ - "IP": i.ip, - "Model": i.HardwareType(), - "step": helper.WhosCalling(), - }).Warn("Syslog resource expects parameter: Server.") + i.log.V(1).Info("Syslog resource expects parameter: Server.", + "IP", i.ip, + "Model", i.HardwareType(), + "step", helper.WhosCalling(), + ) return } if cfg.Port == 0 { - log.WithFields(log.Fields{ - "step": helper.WhosCalling(), - }).Debug("Syslog resource port set to default: 514.") + i.log.V(1).Info("Syslog resource port set to default: 514.", "step", helper.WhosCalling()) port = 514 } else { port = cfg.Port @@ -547,9 +549,7 @@ func (i *IDrac9) Syslog(cfg *cfgresources.Syslog) (err error) { if cfg.Enable != true { enable = "Disabled" - log.WithFields(log.Fields{ - "step": helper.WhosCalling(), - }).Debug("Syslog resource declared with enable: false.") + i.log.V(1).Info("Syslog resource declared with enable: false.", "step", helper.WhosCalling()) } payload := Syslog{ @@ -561,43 +561,40 @@ func (i *IDrac9) Syslog(cfg *cfgresources.Syslog) (err error) { } err = i.putSyslog(payload) if err != nil { - log.WithFields(log.Fields{ - "IP": i.ip, - "Model": i.HardwareType(), - "step": helper.WhosCalling(), - "Error": err, - }).Warn("PUT Syslog request failed.") + i.log.V(1).Error(err, "PUT Syslog request failed.", + "IP", i.ip, + "Model", i.HardwareType(), + "step", helper.WhosCalling(), + "Error", err.Error(), + ) return err } // Enable alerts err = i.putAlertEnable(AlertEnable{"Enabled"}) if err != nil { - log.WithFields(log.Fields{ - "IP": i.ip, - "Model": i.HardwareType(), - "step": helper.WhosCalling(), - "Error": err, - }).Warn("PUT to enable Alerts failed request failed.") + i.log.V(1).Error(err, "PUT to enable Alerts failed request failed.", + "IP", i.ip, + "Model", i.HardwareType(), + "step", helper.WhosCalling(), + "Error", err.Error(), + ) return err } // Configure alerts err = i.putAlertConfig() if err != nil { - log.WithFields(log.Fields{ - "IP": i.ip, - "Model": i.HardwareType(), - "step": helper.WhosCalling(), - "Error": err, - }).Warn("PUT to configure alerts failed request failed.") + i.log.V(1).Error(err, "PUT to configure alerts failed request failed.", + "IP", i.ip, + "Model", i.HardwareType(), + "step", helper.WhosCalling(), + "Error", err.Error(), + ) return err } - log.WithFields(log.Fields{ - "IP": i.ip, - "Model": i.HardwareType(), - }).Debug("Syslog and alert parameters applied.") + i.log.V(1).Info("Syslog and alert parameters applied.", "IP", i.ip, "Model", i.HardwareType()) return err } @@ -652,48 +649,45 @@ func (i *IDrac9) Network(cfg *cfgresources.Network) (reset bool, err error) { err = i.putIPv4(ipv4) if err != nil { - log.WithFields(log.Fields{ - "IP": i.ip, - "Model": i.HardwareType(), - "step": helper.WhosCalling(), - "Error": err, - }).Warn("PUT IPv4 request failed.") + i.log.V(1).Info("PUT IPv4 request failed.", + "IP", i.ip, + "Model", i.HardwareType(), + "step", helper.WhosCalling(), + "Error", err.Error(), + ) } err = i.putSerialOverLan(serialOverLan) if err != nil { - log.WithFields(log.Fields{ - "IP": i.ip, - "Model": i.HardwareType(), - "step": helper.WhosCalling(), - "Error": err, - }).Warn("PUT SerialOverLan request failed.") + i.log.V(1).Info("PUT SerialOverLan request failed.", + "IP", i.ip, + "Model", i.HardwareType(), + "step", helper.WhosCalling(), + "Error", err.Error(), + ) } err = i.putSerialRedirection(serialRedirection) if err != nil { - log.WithFields(log.Fields{ - "IP": i.ip, - "Model": i.HardwareType(), - "step": helper.WhosCalling(), - "Error": err, - }).Warn("PUT SerialRedirection request failed.") + i.log.V(1).Info("PUT SerialRedirection request failed.", + "IP", i.ip, + "Model", i.HardwareType(), + "step", helper.WhosCalling(), + "Error", err.Error(), + ) } err = i.putIpmiOverLan(ipmiOverLan) if err != nil { - log.WithFields(log.Fields{ - "IP": i.ip, - "Model": i.HardwareType(), - "step": helper.WhosCalling(), - "Error": err, - }).Warn("PUT IpmiOverLan request failed.") - } - - log.WithFields(log.Fields{ - "IP": i.ip, - "Model": i.HardwareType(), - }).Debug("Network config parameters applied.") + i.log.V(1).Info("PUT IpmiOverLan request failed.", + "IP", i.ip, + "Model", i.HardwareType(), + "step", helper.WhosCalling(), + "Error", err.Error(), + ) + } + + i.log.V(1).Info("Network config parameters applied.", "IP", i.ip, "Model", i.HardwareType()) return reset, err } @@ -764,13 +758,13 @@ func (i *IDrac9) UploadHTTPSCert(cert []byte, certFileName string, key []byte, k // 1. POST upload x509 cert status, body, err := i.post(endpoint, form.Bytes(), w.FormDataContentType()) if err != nil || status != 201 { - log.WithFields(log.Fields{ - "IP": i.ip, - "Model": i.HardwareType(), - "endpoint": endpoint, - "step": helper.WhosCalling(), - "status": status, - }).Warn("Cert form upload POST request failed, expected 201.") + i.log.V(1).Error(err, "Cert form upload POST request failed, expected 201.", + "IP", i.ip, + "Model", i.HardwareType(), + "endpoint", endpoint, + "step", helper.WhosCalling(), + "status", status, + ) return false, err } @@ -778,23 +772,23 @@ func (i *IDrac9) UploadHTTPSCert(cert []byte, certFileName string, key []byte, k var certStore = new(certStore) err = json.Unmarshal(body, certStore) if err != nil { - log.WithFields(log.Fields{ - "step": helper.WhosCalling(), - "IP": i.ip, - "Model": i.HardwareType(), - "Error": err, - }).Warn("Unable to unmarshal cert store response payload.") + i.log.V(1).Error(err, "Unable to unmarshal cert store response payload.", + "step", helper.WhosCalling(), + "IP", i.ip, + "Model", i.HardwareType(), + "Error", err.Error(), + ) return false, err } resourceURI, err := json.Marshal(certStore.File) if err != nil { - log.WithFields(log.Fields{ - "step": helper.WhosCalling(), - "IP": i.ip, - "Model": i.HardwareType(), - "Error": err, - }).Warn("Unable to marshal cert store resource URI.") + i.log.V(1).Error(err, "Unable to marshal cert store resource URI.", + "step", helper.WhosCalling(), + "IP", i.ip, + "Model", i.HardwareType(), + "Error", err.Error(), + ) return false, err } @@ -802,13 +796,13 @@ func (i *IDrac9) UploadHTTPSCert(cert []byte, certFileName string, key []byte, k endpoint = "sysmgmt/2012/server/network/ssl/cert" status, _, err = i.post(endpoint, []byte(resourceURI), "") if err != nil || status != 201 { - log.WithFields(log.Fields{ - "IP": i.ip, - "Model": i.HardwareType(), - "endpoint": endpoint, - "step": helper.WhosCalling(), - "status": status, - }).Warn("Cert form upload POST request failed, expected 201.") + i.log.V(1).Error(err, "Cert form upload POST request failed, expected 201.", + "IP", i.ip, + "Model", i.HardwareType(), + "endpoint", endpoint, + "step", helper.WhosCalling(), + "status", status, + ) return false, err } diff --git a/providers/dell/idrac9/idrac9.go b/providers/dell/idrac9/idrac9.go index 9d8fbfcc..01d7732f 100644 --- a/providers/dell/idrac9/idrac9.go +++ b/providers/dell/idrac9/idrac9.go @@ -2,6 +2,7 @@ package idrac9 import ( "bytes" + "context" "encoding/json" "fmt" "io/ioutil" @@ -11,6 +12,7 @@ import ( "strconv" "strings" + "github.com/go-logr/logr" "github.com/hashicorp/go-multierror" "github.com/bmc-toolbox/bmclib/devices" @@ -18,10 +20,6 @@ import ( "github.com/bmc-toolbox/bmclib/internal/httpclient" "github.com/bmc-toolbox/bmclib/internal/sshclient" "github.com/bmc-toolbox/bmclib/providers/dell" - - // this make possible to setup logging and properties at any stage - _ "github.com/bmc-toolbox/bmclib/logging" - log "github.com/sirupsen/logrus" ) const ( @@ -38,16 +36,18 @@ type IDrac9 struct { httpClient *http.Client sshClient *sshclient.SSHClient iDracInventory *dell.IDracInventory + ctx context.Context + log logr.Logger } // New returns a new IDrac9 ready to be used -func New(host string, username string, password string) (*IDrac9, error) { +func New(ctx context.Context, host string, username string, password string, log logr.Logger) (*IDrac9, error) { sshClient, err := sshclient.New(host, username, password) if err != nil { return nil, err } - return &IDrac9{ip: host, username: username, password: password, sshClient: sshClient}, nil + return &IDrac9{ip: host, username: username, password: password, sshClient: sshClient, ctx: ctx, log: log}, nil } // CheckCredentials verify whether the credentials are valid or not @@ -61,7 +61,7 @@ func (i *IDrac9) CheckCredentials() (err error) { // get calls a given json endpoint of the ilo and returns the data func (i *IDrac9) get(endpoint string, extraHeaders *map[string]string) (payload []byte, err error) { - log.WithFields(log.Fields{"step": "bmc connection", "vendor": dell.VendorID, "ip": i.ip, "endpoint": endpoint}).Debug("retrieving data from bmc") + i.log.V(1).Info("retrieving data from bmc", "step", "bmc connection", "vendor", dell.VendorID, "ip", i.ip, "endpoint", endpoint) bmcURL := fmt.Sprintf("https://%s", i.ip) req, err := http.NewRequest("GET", fmt.Sprintf("%s/%s", bmcURL, endpoint), nil) @@ -77,15 +77,8 @@ func (i *IDrac9) get(endpoint string, extraHeaders *map[string]string) (payload } } - if log.GetLevel() == log.TraceLevel { - dump, err := httputil.DumpRequestOut(req, true) - if err == nil { - log.Println(fmt.Sprintf("[Request] %s/%s", bmcURL, endpoint)) - log.Println(">>>>>>>>>>>>>>>") - log.Printf("%s\n\n", dump) - log.Println(">>>>>>>>>>>>>>>") - } - } + reqDump, _ := httputil.DumpRequestOut(req, true) + i.log.V(2).Info("requestTrace", "requestDump", string(reqDump), "url", fmt.Sprintf("%s/%s", bmcURL, endpoint)) resp, err := i.httpClient.Do(req) if err != nil { @@ -93,15 +86,8 @@ func (i *IDrac9) get(endpoint string, extraHeaders *map[string]string) (payload } defer resp.Body.Close() - if log.GetLevel() == log.TraceLevel { - dump, err := httputil.DumpResponse(resp, true) - if err == nil { - log.Println("[Response]") - log.Println("<<<<<<<<<<<<<<") - log.Printf("%s\n\n", dump) - log.Println("<<<<<<<<<<<<<<") - } - } + respDump, _ := httputil.DumpResponse(resp, true) + i.log.V(2).Info("responseTrace", "responseDump", string(respDump)) payload, err = ioutil.ReadAll(resp.Body) if err != nil { @@ -126,15 +112,8 @@ func (i *IDrac9) put(endpoint string, payload []byte) (statusCode int, response req.Header.Add("XSRF-TOKEN", i.xsrfToken) - if log.GetLevel() == log.TraceLevel { - dump, err := httputil.DumpRequestOut(req, true) - if err == nil { - log.Println(fmt.Sprintf("[Request] %s/%s", bmcURL, endpoint)) - log.Println(">>>>>>>>>>>>>>>") - log.Printf("%s\n\n", dump) - log.Println(">>>>>>>>>>>>>>>") - } - } + reqDump, _ := httputil.DumpRequestOut(req, true) + i.log.V(2).Info("requestTrace", "requestDump", string(reqDump), "url", fmt.Sprintf("%s/%s", bmcURL, endpoint)) resp, err := i.httpClient.Do(req) if err != nil { @@ -142,15 +121,8 @@ func (i *IDrac9) put(endpoint string, payload []byte) (statusCode int, response } defer resp.Body.Close() - if log.GetLevel() == log.TraceLevel { - dump, err := httputil.DumpResponse(resp, true) - if err == nil { - log.Println("[Response]") - log.Println("<<<<<<<<<<<<<<") - log.Printf("%s\n\n", dump) - log.Println("<<<<<<<<<<<<<<") - } - } + respDump, _ := httputil.DumpResponse(resp, true) + i.log.V(2).Info("responseTrace", "responseDump", string(respDump)) response, err = ioutil.ReadAll(resp.Body) if err != nil { @@ -176,15 +148,8 @@ func (i *IDrac9) delete(endpoint string) (statusCode int, payload []byte, err er req.Header.Add("XSRF-TOKEN", i.xsrfToken) - if log.GetLevel() == log.TraceLevel { - dump, err := httputil.DumpRequestOut(req, true) - if err == nil { - log.Println(fmt.Sprintf("[Request] %s", fmt.Sprintf("%s/%s", bmcURL, endpoint))) - log.Println(">>>>>>>>>>>>>>>") - log.Printf("%s\n\n", dump) - log.Println(">>>>>>>>>>>>>>>") - } - } + reqDump, _ := httputil.DumpRequestOut(req, true) + i.log.V(2).Info("requestTrace", "requestDump", string(reqDump), "url", fmt.Sprintf("%s/%s", bmcURL, endpoint)) resp, err := i.httpClient.Do(req) if err != nil { @@ -192,15 +157,8 @@ func (i *IDrac9) delete(endpoint string) (statusCode int, payload []byte, err er } defer resp.Body.Close() - if log.GetLevel() == log.TraceLevel { - dump, err := httputil.DumpResponse(resp, true) - if err == nil { - log.Println("[Response]") - log.Println("<<<<<<<<<<<<<<") - log.Printf("%s\n\n", dump) - log.Println("<<<<<<<<<<<<<<") - } - } + respDump, _ := httputil.DumpResponse(resp, true) + i.log.V(2).Info("responseTrace", "responseDump", string(respDump)) payload, err = ioutil.ReadAll(resp.Body) if err != nil { @@ -235,30 +193,16 @@ func (i *IDrac9) post(endpoint string, data []byte, formDataContentType string) req.Header.Set("Content-Type", formDataContentType) } - if log.GetLevel() == log.TraceLevel { - dump, err := httputil.DumpRequestOut(req, true) - if err == nil { - log.Println(fmt.Sprintf("[Request] https://%s/%s", i.ip, endpoint)) - log.Println(">>>>>>>>>>>>>>>") - log.Printf("%s\n\n", dump) - log.Println(">>>>>>>>>>>>>>>") - } - } + reqDump, _ := httputil.DumpRequestOut(req, true) + i.log.V(2).Info("requestTrace", "requestDump", string(reqDump), "url", fmt.Sprintf("https://%s/%s", i.ip, endpoint)) resp, err := i.httpClient.Do(req) if err != nil { return 0, []byte{}, err } defer resp.Body.Close() - if log.GetLevel() == log.TraceLevel { - dump, err := httputil.DumpResponse(resp, true) - if err == nil { - log.Println("[Response]") - log.Println("<<<<<<<<<<<<<<") - log.Printf("%s\n\n", dump) - log.Println("<<<<<<<<<<<<<<") - } - } + respDump, _ := httputil.DumpResponse(resp, true) + i.log.V(2).Info("responseTrace", "responseDump", string(respDump)) body, err = ioutil.ReadAll(resp.Body) if err != nil { diff --git a/providers/dell/idrac9/idrac9_c6420_test.go b/providers/dell/idrac9/idrac9_c6420_test.go index 77456ae0..39b86382 100644 --- a/providers/dell/idrac9/idrac9_c6420_test.go +++ b/providers/dell/idrac9/idrac9_c6420_test.go @@ -1,11 +1,14 @@ package idrac9 import ( + "context" "net/http" "net/http/httptest" "strings" "testing" + "github.com/bombsimon/logrusr" + "github.com/sirupsen/logrus" "github.com/spf13/viper" ) @@ -3883,8 +3886,13 @@ var ( } ) +func init() { + if viper.GetBool("debug") != true { + viper.SetDefault("debug", true) + } +} + func setupC6420() (bmc *IDrac9, err error) { - viper.SetDefault("debug", true) muxC6420 = http.NewServeMux() serverC6420 = httptest.NewTLSServer(muxC6420) ip := strings.TrimPrefix(serverC6420.URL, "https://") @@ -3898,7 +3906,8 @@ func setupC6420() (bmc *IDrac9, err error) { }) } - bmc, err = New(ip, username, password) + testLogger := logrus.New() + bmc, err = New(context.TODO(), ip, username, password, logrusr.NewLogger(testLogger)) if err != nil { return bmc, err } diff --git a/providers/dell/idrac9/idrac9_test.go b/providers/dell/idrac9/idrac9_test.go index 0c5f611d..857071ea 100644 --- a/providers/dell/idrac9/idrac9_test.go +++ b/providers/dell/idrac9/idrac9_test.go @@ -1,12 +1,15 @@ package idrac9 import ( + "context" "net/http" "net/http/httptest" "strings" "testing" "github.com/bmc-toolbox/bmclib/devices" + "github.com/bombsimon/logrusr" + "github.com/sirupsen/logrus" "github.com/spf13/viper" ) @@ -3264,8 +3267,13 @@ var ( } ) +func init() { + if viper.GetBool("debug") != true { + viper.SetDefault("debug", true) + } +} + func setup() (bmc *IDrac9, err error) { - viper.SetDefault("debug", true) mux = http.NewServeMux() server = httptest.NewTLSServer(mux) ip := strings.TrimPrefix(server.URL, "https://") @@ -3279,7 +3287,8 @@ func setup() (bmc *IDrac9, err error) { }) } - bmc, err = New(ip, username, password) + testLogger := logrus.New() + bmc, err = New(context.TODO(), ip, username, password, logrusr.NewLogger(testLogger)) if err != nil { return bmc, err } @@ -3665,7 +3674,7 @@ func TestDiskDisks(t *testing.T) { func TestIDracPsu(t *testing.T) { expectedAnswer := []*devices.Psu{ - &devices.Psu{ + { Serial: "h16z4m2_ps1", CapacityKw: 2, PartNumber: "0j5wmga02", diff --git a/providers/dell/idrac9/query.go b/providers/dell/idrac9/query.go index 868d9f7a..a512168e 100644 --- a/providers/dell/idrac9/query.go +++ b/providers/dell/idrac9/query.go @@ -8,7 +8,6 @@ import ( "time" "github.com/bmc-toolbox/bmclib/internal/helper" - log "github.com/sirupsen/logrus" ) // CurrentHTTPSCert returns the current x509 certficates configured on the BMC @@ -61,26 +60,26 @@ func (i *IDrac9) queryUsers() (users map[int]User, err error) { data, err := i.get(endpoint, &map[string]string{}) if err != nil { - log.WithFields(log.Fields{ - "IP": i.ip, - "Model": i.HardwareType(), - "endpoint": endpoint, - "step": helper.WhosCalling(), - "Error": err, - }).Warn("GET request failed.") + i.log.V(1).Error(err, "GET request failed.", + "IP", i.ip, + "Model", i.HardwareType(), + "endpoint", endpoint, + "step", helper.WhosCalling(), + "Error", err.Error(), + ) return users, err } userData := make(idracUsers) err = json.Unmarshal(data, &userData) if err != nil { - log.WithFields(log.Fields{ - "step": "queryUserInfo", - "resource": "User", - "IP": i.ip, - "Model": i.HardwareType(), - "Error": err, - }).Warn("Unable to unmarshal payload.") + i.log.V(1).Error(err, "Unable to unmarshal payload.", + "IP", i.ip, + "Model", i.HardwareType(), + "resource", "User", + "step", "queryUserInfo", + "Error", err.Error(), + ) return users, err } @@ -93,26 +92,26 @@ func (i *IDrac9) queryLdapRoleGroups() (ldapRoleGroups LdapRoleGroups, err error data, err := i.get(endpoint, &map[string]string{}) if err != nil { - log.WithFields(log.Fields{ - "IP": i.ip, - "Model": i.HardwareType(), - "endpoint": endpoint, - "step": helper.WhosCalling(), - "Error": err, - }).Warn("GET request failed.") + i.log.V(1).Error(err, "GET request failed.", + "IP", i.ip, + "Model", i.HardwareType(), + "endpoint", endpoint, + "step", helper.WhosCalling(), + "Error", err.Error(), + ) return ldapRoleGroups, err } idracLdapRoleGroups := make(idracLdapRoleGroups) err = json.Unmarshal(data, &idracLdapRoleGroups) if err != nil { - log.WithFields(log.Fields{ - "step": "queryUserInfo", - "resource": "User", - "IP": i.ip, - "Model": i.HardwareType(), - "Error": err, - }).Warn("Unable to unmarshal payload.") + i.log.V(1).Error(err, "Unable to unmarshal payload.", + "IP", i.ip, + "Model", i.HardwareType(), + "resource", "User", + "step", "queryUserInfo", + "Error", err.Error(), + ) return ldapRoleGroups, err } diff --git a/providers/dell/idrac9/redfish_helpers.go b/providers/dell/idrac9/redfish_helpers.go index 9ca2fd3e..9c4d58a1 100644 --- a/providers/dell/idrac9/redfish_helpers.go +++ b/providers/dell/idrac9/redfish_helpers.go @@ -12,8 +12,6 @@ import ( "reflect" "strings" - log "github.com/sirupsen/logrus" - bmclibErrors "github.com/bmc-toolbox/bmclib/errors" ) @@ -298,15 +296,8 @@ func (i *IDrac9) queryRedfish(method string, endpoint string, payload []byte) (s } } - if log.GetLevel() == log.TraceLevel { - dump, err := httputil.DumpRequestOut(req, true) - if err == nil { - log.Println(fmt.Sprintf("[Request] %s/%s", bmcURL, endpoint)) - log.Println(">>>>>>>>>>>>>>>") - log.Printf("%s\n\n", dump) - log.Println(">>>>>>>>>>>>>>>") - } - } + reqDump, _ := httputil.DumpRequestOut(req, true) + i.log.V(2).Info("requestTrace", "requestDump", string(reqDump), "url", fmt.Sprintf("%s/%s", bmcURL, endpoint)) resp, err := i.httpClient.Do(req) if err != nil { @@ -314,15 +305,8 @@ func (i *IDrac9) queryRedfish(method string, endpoint string, payload []byte) (s } defer resp.Body.Close() - if log.GetLevel() == log.TraceLevel { - dump, err := httputil.DumpResponse(resp, true) - if err == nil { - log.Println("[Response]") - log.Println("<<<<<<<<<<<<<<") - log.Printf("%s\n\n", dump) - log.Println("<<<<<<<<<<<<<<") - } - } + respDump, _ := httputil.DumpResponse(resp, true) + i.log.V(2).Info("responseTrace", "responseDump", string(respDump)) if resp.StatusCode == 401 { return resp.StatusCode, response, bmclibErrors.Err401Redfish diff --git a/providers/dell/idrac9/setupConnections.go b/providers/dell/idrac9/setupConnections.go index e7414e68..082c4a46 100644 --- a/providers/dell/idrac9/setupConnections.go +++ b/providers/dell/idrac9/setupConnections.go @@ -12,10 +12,6 @@ import ( "github.com/bmc-toolbox/bmclib/internal/httpclient" "github.com/bmc-toolbox/bmclib/providers/dell" multierror "github.com/hashicorp/go-multierror" - - // this make possible to setup logging and properties at any stage - _ "github.com/bmc-toolbox/bmclib/logging" - log "github.com/sirupsen/logrus" ) func (i *IDrac9) httpLogin() (err error) { @@ -28,7 +24,7 @@ func (i *IDrac9) httpLogin() (err error) { return err } - log.WithFields(log.Fields{"step": "bmc connection", "vendor": dell.VendorID, "ip": i.ip}).Debug("connecting to bmc") + i.log.V(1).Info("connecting to bmc", "step", "bmc connection", "vendor", dell.VendorID, "ip", i.ip) url := fmt.Sprintf("https://%s/sysmgmt/2015/bmc/session", i.ip) req, err := http.NewRequest("POST", url, nil) @@ -38,15 +34,8 @@ func (i *IDrac9) httpLogin() (err error) { req.Header.Add("user", fmt.Sprintf("\"%s\"", i.username)) req.Header.Add("password", fmt.Sprintf("\"%s\"", i.password)) - if log.GetLevel() == log.TraceLevel { - dump, err := httputil.DumpRequestOut(req, true) - if err == nil { - log.Println(fmt.Sprintf("[Request] %s", url)) - log.Println(">>>>>>>>>>>>>>>") - log.Printf("%s\n\n", dump) - log.Println(">>>>>>>>>>>>>>>") - } - } + reqDump, _ := httputil.DumpRequestOut(req, true) + i.log.V(2).Info("requestTrace", "requestDump", string(reqDump), "url", url) resp, err := httpClient.Do(req) if err != nil { @@ -68,15 +57,8 @@ func (i *IDrac9) httpLogin() (err error) { } defer resp.Body.Close() - if log.GetLevel() == log.TraceLevel { - dump, err := httputil.DumpResponse(resp, false) - if err == nil { - log.Println("[Response]") - log.Println("<<<<<<<<<<<<<<") - log.Printf("%s\n\n", dump) - log.Println("<<<<<<<<<<<<<<") - } - } + respDump, _ := httputil.DumpResponse(resp, true) + i.log.V(2).Info("responseTrace", "responseDump", string(respDump)) iDracAuth := &dell.IDracAuth{} err = json.Unmarshal(payload, iDracAuth) diff --git a/providers/dell/m1000e/actions_test.go b/providers/dell/m1000e/actions_test.go index ce11a887..74e0f6be 100644 --- a/providers/dell/m1000e/actions_test.go +++ b/providers/dell/m1000e/actions_test.go @@ -1,9 +1,12 @@ package m1000e import ( + "context" "testing" "github.com/bmc-toolbox/bmclib/sshmock" + "github.com/bombsimon/logrusr" + "github.com/sirupsen/logrus" ) const ( @@ -120,7 +123,8 @@ func setupBMC() (func(), *M1000e, error) { return nil, nil, err } - bmc, err := New(address, sshUsername, sshPassword) + testLogger := logrus.New() + bmc, err := New(context.TODO(), address, sshUsername, sshPassword, logrusr.NewLogger(testLogger)) if err != nil { tearDown() return nil, nil, err diff --git a/providers/dell/m1000e/configure.go b/providers/dell/m1000e/configure.go index 654bd38d..0ebbba16 100644 --- a/providers/dell/m1000e/configure.go +++ b/providers/dell/m1000e/configure.go @@ -12,7 +12,6 @@ import ( "github.com/bmc-toolbox/bmclib/cfgresources" "github.com/bmc-toolbox/bmclib/devices" "github.com/google/go-querystring/query" - log "github.com/sirupsen/logrus" ) // This ensures the compiler errors if this type is missing @@ -99,10 +98,7 @@ func (m *M1000e) User(cfgUsers []*cfgresources.User) (err error) { return err } - log.WithFields(log.Fields{ - "IP": m.ip, - "Model": m.HardwareType(), - }).Debug("User account config parameters applied.") + m.log.V(1).Info("User account config parameters applied.", "IP", m.ip, "Model", m.HardwareType()) } @@ -124,10 +120,7 @@ func (m *M1000e) Syslog(cfg *cfgresources.Syslog) (err error) { return err } - log.WithFields(log.Fields{ - "IP": m.ip, - "Model": m.HardwareType(), - }).Debug("Interface config parameters applied.") + m.log.V(1).Info("Interface config parameters applied.", "IP", m.ip, "Model", m.HardwareType()) return err } @@ -150,10 +143,7 @@ func (m *M1000e) Ntp(cfg *cfgresources.Ntp) (err error) { return err } - log.WithFields(log.Fields{ - "IP": m.ip, - "Model": m.HardwareType(), - }).Debug("DateTime config parameters applied.") + m.log.V(1).Info("DateTime config parameters applied.", "IP", m.ip, "Model", m.HardwareType()) return err } @@ -171,10 +161,7 @@ func (m *M1000e) Ldap(cfg *cfgresources.Ldap) (err error) { return err } - log.WithFields(log.Fields{ - "IP": m.ip, - "Model": m.HardwareType(), - }).Debug("Ldap config parameters applied.") + m.log.V(1).Info("Ldap config parameters applied.", "IP", m.ip, "Model", m.HardwareType()) return err } @@ -194,10 +181,7 @@ func (m *M1000e) applyLdapRoleCfg(cfg LdapArgParams, roleID int) (err error) { return err } - log.WithFields(log.Fields{ - "IP": m.ip, - "Model": m.HardwareType(), - }).Debug("Ldap Role group config parameters applied.") + m.log.V(1).Info("Ldap Role group config parameters applied.", "IP", m.ip, "Model", m.HardwareType()) return err } @@ -209,34 +193,34 @@ func (m *M1000e) LdapGroup(cfg []*cfgresources.LdapGroup, cfgLdap *cfgresources. for _, group := range cfg { ldapRoleParams, err := m.newLdapRoleCfg(group, roleID) if err != nil { - log.WithFields(log.Fields{ - "step": "applyLdapGroupParams", - "Ldap role": group.Role, - "IP": m.ip, - "Model": m.HardwareType(), - "Error": err, - }).Warn("Unable to apply Ldap role group config.") + m.log.V(1).Error(err, "Unable to apply Ldap role group config.", + "step", "applyLdapGroupParams", + "Ldap role", group.Role, + "IP", m.ip, + "Model", m.HardwareType(), + "Error", err.Error(), + ) return err } err = m.applyLdapRoleCfg(ldapRoleParams, roleID) if err != nil { - log.WithFields(log.Fields{ - "step": "applyLdapGroupParams", - "Ldap role": group.Role, - "IP": m.ip, - "Model": m.HardwareType(), - "Error": err, - }).Warn("Unable to apply Ldap role group config.") + m.log.V(1).Error(err, "Unable to apply Ldap role group config.", + "step", "applyLdapGroupParams", + "Ldap role", group.Role, + "IP", m.ip, + "Model", m.HardwareType(), + "Error", err, + ) return err } - log.WithFields(log.Fields{ - "IP": m.ip, - "Model": m.HardwareType(), - "Role": group.Role, - "Group": group.Group, - }).Debug("Ldap group parameters applied.") + m.log.V(1).Info("Ldap group parameters applied.", + "IP", m.ip, + "Model", m.HardwareType(), + "Role", group.Role, + "Group", group.Group, + ) roleID++ } @@ -287,7 +271,7 @@ func (m *M1000e) CurrentHTTPSCert() (c []*x509.Certificate, b bool, e error) { // return err // } // -// log.WithFields(log.Fields{ +// m.log.V(1).Info("", // "IP": m.ip, // "Model": m.HardwareType(), // }).Debug("SSL certs uploaded.") @@ -304,7 +288,7 @@ func (m *M1000e) CurrentHTTPSCert() (c []*x509.Certificate, b bool, e error) { // // file, err := os.Open(SslKey) // if err != nil { -// log.WithFields(log.Fields{ +// m.log.V(1).Info("", // "step": "ssl-multipart-upload", // }).Fatal("Declared SSL key file doesnt exist: ", SslKey) // return err @@ -334,7 +318,7 @@ func (m *M1000e) CurrentHTTPSCert() (c []*x509.Certificate, b bool, e error) { // // file, err = os.Open(SslCert) // if err != nil { -// log.WithFields(log.Fields{ +// m.log.V(1).Info("", // "step": "ssl-multipart-upload", // }).Fatal("Declared SSL cert file doesnt exist: ", SslCert) // return err @@ -409,15 +393,9 @@ func (m *M1000e) post(endpoint string, form *url.Values) (err error) { return err } req.Header.Add("Content-Type", "application/x-www-form-urlencoded") - if log.GetLevel() == log.TraceLevel { - dump, err := httputil.DumpRequestOut(req, true) - if err == nil { - log.Println(fmt.Sprintf("[Request] https://%s/cgi-bin/webcgi/%s", m.ip, endpoint)) - log.Println(">>>>>>>>>>>>>>>") - log.Printf("%s\n\n", dump) - log.Println(">>>>>>>>>>>>>>>") - } - } + + reqDump, _ := httputil.DumpRequestOut(req, true) + m.log.V(2).Info("requestTrace", "requestDump", string(reqDump), "url", fmt.Sprintf("https://%s/cgi-bin/webcgi/%s", m.ip, endpoint)) //XXX to debug //fmt.Printf("--> %+v\n", form.Encode()) @@ -427,15 +405,8 @@ func (m *M1000e) post(endpoint string, form *url.Values) (err error) { return err } defer resp.Body.Close() - if log.GetLevel() == log.TraceLevel { - dump, err := httputil.DumpResponse(resp, true) - if err == nil { - log.Println("[Response]") - log.Println("<<<<<<<<<<<<<<") - log.Printf("%s\n\n", dump) - log.Println("<<<<<<<<<<<<<<") - } - } + respDump, _ := httputil.DumpResponse(resp, true) + m.log.V(2).Info("responseTrace", "responseDump", string(respDump)) _, err = ioutil.ReadAll(resp.Body) if err != nil { @@ -459,10 +430,7 @@ func (m *M1000e) ApplySecurityCfg(cfg LoginSecurityParams) (err error) { return err } - log.WithFields(log.Fields{ - "IP": m.ip, - "Model": m.HardwareType(), - }).Debug("Security config parameters applied.") + m.log.V(1).Info("Security config parameters applied.", "IP", m.ip, "Model", m.HardwareType()) return err } diff --git a/providers/dell/m1000e/constructors.go b/providers/dell/m1000e/constructors.go index fe2c73a7..7440358a 100644 --- a/providers/dell/m1000e/constructors.go +++ b/providers/dell/m1000e/constructors.go @@ -5,7 +5,6 @@ import ( "fmt" "github.com/bmc-toolbox/bmclib/cfgresources" - log "github.com/sirupsen/logrus" ) //func (m *M1000e) newSslCfg(ssl *cfgresources.Ssl) (MFormParams map[string]string) { @@ -27,15 +26,17 @@ import ( func (m *M1000e) newDatetimeCfg(ntp *cfgresources.Ntp) DatetimeParams { if ntp.Timezone == "" { - log.WithFields(log.Fields{ - "step": "apply-ntp-cfg", - }).Fatal("Ntp resource parameter timezone required but not declared.") + // TODO update method with error return and return err in this if, was doing logrus.Fatal here + msg := "ntp resource parameter timezone required but not declared" + err := errors.New(msg) + m.log.V(0).Error(err, msg, "step", "apply-ntp-cfg") } if ntp.Server1 == "" { - log.WithFields(log.Fields{ - "step": "apply-ntp-cfg", - }).Fatal("Ntp resource parameter server1 required but not declared.") + // TODO update method with error return and return err in this if, was doing logrus.Fatal here + msg := "ntp resource parameter server1 required but not declared." + err := errors.New(msg) + m.log.V(0).Error(err, msg, "step", "apply-ntp-cfg") } dateTime := DatetimeParams{ @@ -60,21 +61,15 @@ func (m *M1000e) newDirectoryServicesCfg(ldap *cfgresources.Ldap) DirectoryServi var userAttribute, groupAttribute string if ldap.Server == "" { - log.WithFields(log.Fields{ - "step": "newDirectoryServicesCfg", - }).Warn("Ldap resource parameter Server required but not declared.") + m.log.V(1).Info("Ldap resource parameter Server required but not declared.", "step", "newDirectoryServicesCfg") } if ldap.Port == 0 { - log.WithFields(log.Fields{ - "step": "newDirectoryServicesCfg", - }).Warn("Ldap resource parameter Port required but not declared.") + m.log.V(1).Info("Ldap resource parameter Port required but not declared.", "step", "newDirectoryServicesCfg") } if ldap.BaseDn == "" { - log.WithFields(log.Fields{ - "step": "newDirectoryServicesCfg", - }).Warn("Ldap resource parameter baseDn required but not declared.") + m.log.V(1).Info("Ldap resource parameter baseDn required but not declared.", "step", "newDirectoryServicesCfg") } if ldap.UserAttribute == "" { @@ -154,29 +149,23 @@ func (m *M1000e) newLdapRoleCfg(cfg *cfgresources.LdapGroup, roleID int) (ldapAr if cfg.Group == "" { msg := "Ldap resource parameter Group required but not declared." - log.WithFields(log.Fields{ - "Role": cfg.Role, - "step": "newLdapRoleCfg", - }).Warn(msg) - return ldapArgCfg, errors.New(msg) + err = errors.New(msg) + m.log.V(1).Error(err, msg, "Role", cfg.Role, "step", "newLdapRoleCfg") + return ldapArgCfg, err } if cfg.GroupBaseDn == "" && cfg.Enable { msg := "Ldap resource parameter GroupBaseDn required but not declared." - log.WithFields(log.Fields{ - "Role": cfg.Role, - "step": "newLdapRoleCfg", - }).Warn(msg) - return ldapArgCfg, errors.New(msg) + err = errors.New(msg) + m.log.V(1).Error(err, msg, "Role", cfg.Role, "step", "newLdapRoleCfg") + return ldapArgCfg, err } if !m.isRoleValid(cfg.Role) { msg := "Ldap resource Role must be a valid role: admin OR user." - log.WithFields(log.Fields{ - "Role": cfg.Role, - "step": "newLdapRoleCfg", - }).Warn(msg) - return ldapArgCfg, errors.New(msg) + err = errors.New(msg) + m.log.V(1).Error(err, msg, "Role", cfg.Role, "step", "newLdapRoleCfg") + return ldapArgCfg, err } groupDn := fmt.Sprintf("cn=%s,%s", cfg.Group, cfg.GroupBaseDn) @@ -219,9 +208,10 @@ func (m *M1000e) newInterfaceCfg(syslog *cfgresources.Syslog) InterfaceParams { var syslogPort int if syslog.Server == "" { - log.WithFields(log.Fields{ - "step": "apply-interface-cfg", - }).Fatal("Syslog resource expects parameter: Server.") + // TODO update method with error return and return err in this if, was doing logrus.Fatal here + msg := "syslog resource expects parameter: Server" + err := errors.New(msg) + m.log.V(0).Error(err, msg, "step", "apply-interface-cfg") } if syslog.Port == 0 { @@ -276,22 +266,24 @@ func (m *M1000e) newUserCfg(user *cfgresources.User, userID int) UserParams { var cmcGroup, privilege int if user.Name == "" { - log.WithFields(log.Fields{ - "step": "apply-user-cfg", - }).Fatal("User resource expects parameter: Name.") + // TODO update method with error return and return err in this if, was doing logrus.Fatal here + msg := "user resource expects parameter: Name" + err := errors.New(msg) + m.log.V(0).Error(err, msg, "step", "apply-user-cfg") } if user.Password == "" { - log.WithFields(log.Fields{ - "step": "apply-user-cfg", - }).Fatal("User resource expects parameter: Password.") + // TODO update method with error return and return err in this if, was doing logrus.Fatal here + msg := "user resource expects parameter: Password" + err := errors.New(msg) + m.log.V(0).Error(err, msg, "step", "apply-user-cfg") } if m.isRoleValid(user.Role) == false { - log.WithFields(log.Fields{ - "step": "apply-user-cfg", - "role": user.Role, - }).Fatal("User resource Role must be declared and a valid role: admin.") + // TODO update method with error return and return err in this if, was doing logrus.Fatal here + msg := "user resource Role must be declared and a valid role: admin" + err := errors.New(msg) + m.log.V(0).Error(err, msg, "step", "apply-user-cfg", "role", user.Role) } if user.Role == "admin" { diff --git a/providers/dell/m1000e/m1000e.go b/providers/dell/m1000e/m1000e.go index f6e01d9b..9ec6c339 100644 --- a/providers/dell/m1000e/m1000e.go +++ b/providers/dell/m1000e/m1000e.go @@ -2,6 +2,7 @@ package m1000e import ( "bytes" + "context" "encoding/json" "fmt" "io/ioutil" @@ -14,10 +15,7 @@ import ( "github.com/bmc-toolbox/bmclib/errors" "github.com/bmc-toolbox/bmclib/internal/sshclient" "github.com/bmc-toolbox/bmclib/providers/dell" - - // this make possible to setup logging and properties at any stage - _ "github.com/bmc-toolbox/bmclib/logging" - log "github.com/sirupsen/logrus" + "github.com/go-logr/logr" ) const ( @@ -42,16 +40,18 @@ type M1000e struct { cmcTemp *dell.CMCTemp cmcWWN *dell.CMCWWN SessionToken string //required to set config + ctx context.Context + log logr.Logger } // New returns a connection to M1000e -func New(host string, username string, password string) (*M1000e, error) { +func New(ctx context.Context, host string, username string, password string, log logr.Logger) (*M1000e, error) { sshClient, err := sshclient.New(host, username, password) if err != nil { return nil, err } - return &M1000e{ip: host, username: username, password: password, sshClient: sshClient}, nil + return &M1000e{ip: host, username: username, password: password, sshClient: sshClient, ctx: ctx, log: log}, nil } // CheckCredentials verify whether the credentials are valid or not @@ -64,7 +64,7 @@ func (m *M1000e) CheckCredentials() (err error) { } func (m *M1000e) get(endpoint string) (payload []byte, err error) { - log.WithFields(log.Fields{"step": "chassis connection", "vendor": dell.VendorID, "ip": m.ip, "endpoint": endpoint}).Debug("retrieving data from chassis") + m.log.V(1).Info("retrieving data from chassis", "step", "chassis connection", "vendor", string(dell.VendorID), "ip", m.ip, "endpoint", endpoint) resp, err := m.httpClient.Get(fmt.Sprintf("https://%s/cgi-bin/webcgi/%s", m.ip, endpoint)) if err != nil { @@ -345,7 +345,13 @@ func (m *M1000e) StorageBlades() (storageBlades []*devices.StorageBlade, err err storageBlade.PowerKw = float64(dellBlade.ActualPwrConsump) / 1000 temp, err := strconv.Atoi(dellBlade.BladeTemperature) if err != nil { - log.WithFields(log.Fields{"operation": "connection", "ip": m.ip, "position": storageBlade.BladePosition, "type": "chassis", "error": err}).Warning("Auditing blade") + m.log.V(1).Info("Auditing blade", + "operation", "connection", + "ip", m.ip, + "position", storageBlade.BladePosition, + "type", "chassis", + "error", err.Error(), + ) continue } storageBlade.TempC = temp @@ -385,7 +391,12 @@ func (m *M1000e) Blades() (blades []*devices.Blade, err error) { blade.PowerKw = float64(dellBlade.ActualPwrConsump) / 1000 temp, err := strconv.Atoi(dellBlade.BladeTemperature) if err != nil { - log.WithFields(log.Fields{"operation": "connection", "ip": m.ip, "position": blade.BladePosition, "type": "chassis"}).Warning(err) + m.log.V(1).Info(err.Error(), + "operation", "connection", + "ip", m.ip, + "position", blade.BladePosition, + "type", "chassis", + ) continue } else { blade.TempC = temp @@ -421,7 +432,12 @@ func (m *M1000e) Blades() (blades []*devices.Blade, err error) { if strings.HasPrefix(blade.BmcAddress, "[") { payload, err := m.get(fmt.Sprintf("blade_status?id=%d&cat=C10&tab=T41&id=P78", blade.BladePosition)) if err != nil { - log.WithFields(log.Fields{"operation": "connection", "ip": m.ip, "position": blade.BladePosition, "type": "chassis"}).Warning(err) + m.log.V(1).Info(err.Error(), + "operation", "connection", + "ip", m.ip, + "position", blade.BladePosition, + "type", "chassis", + ) } else { ip := findBmcIP.FindStringSubmatch(string(payload)) if len(ip) > 0 { @@ -432,7 +448,12 @@ func (m *M1000e) Blades() (blades []*devices.Blade, err error) { for _, nic := range dellBlade.Nics { if nic.BladeNicName == "" { - log.WithFields(log.Fields{"operation": "connection", "ip": m.ip, "position": blade.BladePosition, "type": "chassis"}).Error("Network card information missing, please verify") + m.log.V(1).Info("Network card information missing, please verify", + "operation", "connection", + "ip", m.ip, + "position", blade.BladePosition, + "type", "chassis", + ) continue } n := &devices.Nic{ diff --git a/providers/dell/m1000e/m1000e_test.go b/providers/dell/m1000e/m1000e_test.go index 2a681622..45aab6fc 100644 --- a/providers/dell/m1000e/m1000e_test.go +++ b/providers/dell/m1000e/m1000e_test.go @@ -1,12 +1,15 @@ package m1000e import ( + "context" "net/http" "net/http/httptest" "strings" "testing" "github.com/bmc-toolbox/bmclib/devices" + "github.com/bombsimon/logrusr" + "github.com/sirupsen/logrus" "github.com/spf13/viper" ) @@ -1680,8 +1683,13 @@ var ( } ) +func init() { + if viper.GetBool("debug") != true { + viper.SetDefault("debug", true) + } +} + func setup() (r *M1000e, err error) { - viper.SetDefault("debug", true) mux = http.NewServeMux() server = httptest.NewTLSServer(mux) ip := strings.TrimPrefix(server.URL, "https://") @@ -1701,7 +1709,8 @@ func setup() (r *M1000e, err error) { }) } - r, err = New(ip, username, password) + testLogger := logrus.New() + r, err = New(context.TODO(), ip, username, password, logrusr.NewLogger(testLogger)) if err != nil { return r, err } diff --git a/providers/dell/m1000e/setupConnections.go b/providers/dell/m1000e/setupConnections.go index 1d2e55f4..a9fe92ba 100644 --- a/providers/dell/m1000e/setupConnections.go +++ b/providers/dell/m1000e/setupConnections.go @@ -14,7 +14,6 @@ import ( multierror "github.com/hashicorp/go-multierror" "github.com/bmc-toolbox/bmclib/providers/dell" - log "github.com/sirupsen/logrus" ) // retrieves ST2 which is required to submit form data @@ -69,7 +68,7 @@ func (m *M1000e) httpLogin() (err error) { if m.httpClient != nil { return } - log.WithFields(log.Fields{"step": "chassis connection", "vendor": dell.VendorID, "ip": m.ip}).Debug("connecting to chassis") + m.log.V(1).Info("connecting to chassis", "step", "chassis connection", "vendor", string(dell.VendorID), "ip", m.ip) form := url.Values{} form.Add("user", m.username) diff --git a/providers/hp/c7000/c7000.go b/providers/hp/c7000/c7000.go index 21a995da..1f08b248 100644 --- a/providers/hp/c7000/c7000.go +++ b/providers/hp/c7000/c7000.go @@ -1,6 +1,7 @@ package c7000 import ( + "context" "encoding/xml" "fmt" "io/ioutil" @@ -12,9 +13,7 @@ import ( "github.com/bmc-toolbox/bmclib/internal/httpclient" "github.com/bmc-toolbox/bmclib/internal/sshclient" "github.com/bmc-toolbox/bmclib/providers/hp" - - // this make possible to setup logging and properties at any stage - _ "github.com/bmc-toolbox/bmclib/logging" + "github.com/go-logr/logr" ) const ( @@ -31,10 +30,12 @@ type C7000 struct { httpClient *http.Client sshClient *sshclient.SSHClient Rimp *hp.Rimp + ctx context.Context + log logr.Logger } // New returns a connection to C7000 -func New(host string, username string, password string) (*C7000, error) { +func New(ctx context.Context, host string, username string, password string, log logr.Logger) (*C7000, error) { client, err := httpclient.Build() if err != nil { return nil, err @@ -66,7 +67,7 @@ func New(host string, username string, password string) (*C7000, error) { return nil, err } - return &C7000{ip: host, username: username, password: password, Rimp: Rimp, sshClient: sshClient}, nil + return &C7000{ip: host, username: username, password: password, Rimp: Rimp, sshClient: sshClient, ctx: ctx, log: log}, nil } // CheckCredentials verify whether the credentials are valid or not diff --git a/providers/hp/c7000/c7000_test.go b/providers/hp/c7000/c7000_test.go index a9355f40..7c335e10 100644 --- a/providers/hp/c7000/c7000_test.go +++ b/providers/hp/c7000/c7000_test.go @@ -1,12 +1,15 @@ package c7000 import ( + "context" "net/http" "net/http/httptest" "strings" "testing" "github.com/bmc-toolbox/bmclib/devices" + "github.com/bombsimon/logrusr" + "github.com/sirupsen/logrus" "github.com/spf13/viper" ) @@ -2404,8 +2407,13 @@ var ( } ) +func init() { + if viper.GetBool("debug") != true { + viper.SetDefault("debug", true) + } +} + func setup() (r *C7000, err error) { - viper.SetDefault("debug", true) mux = http.NewServeMux() server = httptest.NewTLSServer(mux) ip := strings.TrimPrefix(server.URL, "https://") @@ -2421,7 +2429,8 @@ func setup() (r *C7000, err error) { }) } - r, err = New(ip, username, password) + testLogger := logrus.New() + r, err = New(context.TODO(), ip, username, password, logrusr.NewLogger(testLogger)) if err != nil { return r, err } diff --git a/providers/hp/c7000/configure.go b/providers/hp/c7000/configure.go index a406aec4..6a4ae48f 100644 --- a/providers/hp/c7000/configure.go +++ b/providers/hp/c7000/configure.go @@ -2,10 +2,10 @@ package c7000 import ( "crypto/x509" + "errors" "github.com/bmc-toolbox/bmclib/cfgresources" "github.com/bmc-toolbox/bmclib/devices" - log "github.com/sirupsen/logrus" ) // This ensures the compiler errors if this type is missing @@ -70,25 +70,25 @@ func (c *C7000) Power(cfg *cfgresources.Power) (err error) { func (c *C7000) Ldap(cfg *cfgresources.Ldap) (err error) { err = c.applysetLdapInfo4(cfg) if err != nil { - log.WithFields(log.Fields{ - "step": "applyLdapParams", - "resource": "Ldap", - "IP": c.ip, - "Model": c.HardwareType(), - "Error": err, - }).Warn("applyLdapParams returned error.") + c.log.V(1).Info("applyLdapParams returned error.", + "step", "applyLdapParams", + "resource", "Ldap", + "IP", c.ip, + "Model", c.HardwareType(), + "Error", err.Error(), + ) return err } err = c.applyEnableLdapAuth(cfg.Enable) if err != nil { - log.WithFields(log.Fields{ - "step": "applyLdapParams", - "resource": "Ldap", - "IP": c.ip, - "Model": c.HardwareType(), - "Error": err, - }).Warn("applyLdapParams returned error.") + c.log.V(1).Info("applyLdapParams returned error.", + "step", "applyLdapParams", + "resource", "Ldap", + "IP", c.ip, + "Model", c.HardwareType(), + "Error", err.Error(), + ) return err } @@ -115,25 +115,25 @@ func (c *C7000) Ldap(cfg *cfgresources.Ldap) (err error) { // func (c *C7000) applysetLdapInfo4(cfg *cfgresources.Ldap) (err error) { if cfg.Server == "" { - log.WithFields(log.Fields{ - "step": "applysetLdapInfo4", - "Model": c.HardwareType(), - }).Warn("Ldap resource parameter Server required but not declared.") + c.log.V(1).Info("Ldap resource parameter Server required but not declared.", + "step", "applysetLdapInfo4", + "Model", c.HardwareType(), + ) return err } if cfg.Port == 0 { - log.WithFields(log.Fields{ - "step": "applysetLdapInfo4", - "Model": c.HardwareType(), - }).Warn("Ldap resource parameter Port required but not declared.") + c.log.V(1).Info("Ldap resource parameter Port required but not declared.", + "step", "applysetLdapInfo4", + "Model", c.HardwareType(), + ) return err } if cfg.BaseDn == "" { - log.WithFields(log.Fields{ - "step": "applysetLdapInfo4", - }).Warn("Ldap resource parameter BaseDn required but not declared.") + c.log.V(1).Info("Ldap resource parameter BaseDn required but not declared.", + "step", "applysetLdapInfo4", + ) return err } @@ -156,20 +156,20 @@ func (c *C7000) applysetLdapInfo4(cfg *cfgresources.Ldap) (err error) { statusCode, _, err := c.postXML(payload) if statusCode != 200 || err != nil { - log.WithFields(log.Fields{ - "step": "applysetLdapInfo4", - "IP": c.ip, - "Model": c.HardwareType(), - "statusCode": statusCode, - "Error": err, - }).Warn("Ldap applysetLdapInfo4 apply request returned non 200.") + c.log.V(1).Info("Ldap applysetLdapInfo4 apply request returned non 200.", + "step", "applysetLdapInfo4", + "IP", c.ip, + "Model", c.HardwareType(), + "statusCode", statusCode, + "Error", err.Error(), + ) return err } - log.WithFields(log.Fields{ - "IP": c.ip, - "Model": c.HardwareType(), - }).Debug("Ldap Server parameters applied.") + c.log.V(1).Info("Ldap Server parameters applied.", + "IP", c.ip, + "Model", c.HardwareType(), + ) return err } @@ -182,20 +182,20 @@ func (c *C7000) applyEnableLdapAuth(enable bool) (err error) { payload := enableLdapAuthentication{EnableLdap: enable, EnableLocalUsers: true} statusCode, _, err := c.postXML(payload) if statusCode != 200 || err != nil { - log.WithFields(log.Fields{ - "step": "applyEnableLdapAuth", - "IP": c.ip, - "Model": c.HardwareType(), - "statusCode": statusCode, - "Error": err, - }).Warn("Ldap applyEnableLdapAuth apply request returned non 200.") + c.log.V(1).Info("Ldap applyEnableLdapAuth apply request returned non 200.", + "step", "applyEnableLdapAuth", + "IP", c.ip, + "Model", c.HardwareType(), + "statusCode", statusCode, + "Error", err.Error(), + ) return err } - log.WithFields(log.Fields{ - "IP": c.ip, - "Model": c.HardwareType(), - }).Debug("Ldap Enabled.") + c.log.V(1).Info("Ldap Enabled.", + "IP", c.ip, + "Model", c.HardwareType(), + ) return err } @@ -210,11 +210,11 @@ func (c *C7000) LdapGroup(cfg []*cfgresources.LdapGroup, cfgLdap *cfgresources.L for _, group := range cfg { if group.Group == "" { - log.WithFields(log.Fields{ - "step": "applyLdapGroupParams", - "Model": c.HardwareType(), - "Ldap role": group.Role, - }).Warn("Ldap resource parameter Group required but not declared.") + c.log.V(1).Info("Ldap resource parameter Group required but not declared.", + "step", "applyLdapGroupParams", + "Model", c.HardwareType(), + "Ldap role", group.Role, + ) return } @@ -222,13 +222,13 @@ func (c *C7000) LdapGroup(cfg []*cfgresources.LdapGroup, cfgLdap *cfgresources.L if !group.Enable { c.applyRemoveLdapGroup(group.Group) if err != nil { - log.WithFields(log.Fields{ - "step": "applyRemoveLdapGroup", - "resource": "Ldap", - "IP": c.ip, - "Model": c.HardwareType(), - "Error": err, - }).Warn("Remove Ldap Group returned error.") + c.log.V(1).Info("Remove Ldap Group returned error.", + "step", "applyRemoveLdapGroup", + "resource", "Ldap", + "IP", c.ip, + "Model", c.HardwareType(), + "Error", err.Error(), + ) return } @@ -236,58 +236,58 @@ func (c *C7000) LdapGroup(cfg []*cfgresources.LdapGroup, cfgLdap *cfgresources.L } if !c.isRoleValid(group.Role) { - log.WithFields(log.Fields{ - "step": "applyLdapGroupParams", - "role": group.Role, - "Model": c.HardwareType(), - }).Warn("Ldap resource Role must be a valid role: admin OR user.") + c.log.V(1).Info("Ldap resource Role must be a valid role: admin OR user.", + "step", "applyLdapGroupParams", + "role", group.Role, + "Model", c.HardwareType(), + ) return } //1. addLdapGroup err = c.applyAddLdapGroup(group.Group) if err != nil { - log.WithFields(log.Fields{ - "step": "applyAddLdapGroup", - "resource": "Ldap", - "IP": c.ip, - "Model": c.HardwareType(), - "Error": err, - }).Warn("addLdapGroup returned error.") + c.log.V(1).Info("addLdapGroup returned error.", + "step", "applyAddLdapGroup", + "resource", "Ldap", + "IP", c.ip, + "Model", c.HardwareType(), + "Error", err.Error(), + ) return } //2. setLdapGroupBayACL err = c.applyLdapGroupBayACL(group.Role, group.Group) if err != nil { - log.WithFields(log.Fields{ - "step": "setLdapGroupBayACL", - "resource": "Ldap", - "IP": c.ip, - "Model": c.HardwareType(), - "Error": err, - }).Warn("addLdapGroup returned error.") + c.log.V(1).Info("addLdapGroup returned error.", + "step", "setLdapGroupBayACL", + "resource", "Ldap", + "IP", c.ip, + "Model", c.HardwareType(), + "Error", err.Error(), + ) return } //3. applyAddLdapGroupBayAccess err = c.applyAddLdapGroupBayAccess(group.Group) if err != nil { - log.WithFields(log.Fields{ - "step": "applyAddLdapGroupBayAccess", - "resource": "Ldap", - "IP": c.ip, - "Model": c.HardwareType(), - "Error": err, - }).Warn("addLdapGroup returned error.") + c.log.V(1).Info("addLdapGroup returned error.", + "step", "applyAddLdapGroupBayAccess", + "resource", "Ldap", + "IP", c.ip, + "Model", c.HardwareType(), + "Error", err.Error(), + ) return } } - log.WithFields(log.Fields{ - "IP": c.ip, - "Model": c.HardwareType(), - }).Debug("Ldap config applied") + c.log.V(1).Info("Ldap config applied", + "IP", c.ip, + "Model", c.HardwareType(), + ) return } @@ -300,30 +300,30 @@ func (c *C7000) applyRemoveLdapGroup(group string) (err error) { payload := removeLdapGroup{LdapGroup: ldapGroup{Text: group}} statusCode, _, err := c.postXML(payload) if statusCode == 200 || statusCode == 500 { // 500 indicates the group exists. - log.WithFields(log.Fields{ - "step": "applyRemoveLdapGroup", - "IP": c.ip, - "Model": c.HardwareType(), - "statusCode": statusCode, - }).Debug("Ldap applyRemoveLdapGroup applied.") + c.log.V(1).Info("Ldap applyRemoveLdapGroup applied.", + "step", "applyRemoveLdapGroup", + "IP", c.ip, + "Model", c.HardwareType(), + "statusCode", statusCode, + ) return nil } if statusCode >= 300 || err != nil { - log.WithFields(log.Fields{ - "step": "applyRemoveLdapGroup", - "IP": c.ip, - "Model": c.HardwareType(), - "statusCode": statusCode, - }).Warn("Ldap applyRemoveLdapGroup request returned non 200.") + c.log.V(1).Info("Ldap applyRemoveLdapGroup request returned non 200.", + "step", "applyRemoveLdapGroup", + "IP", c.ip, + "Model", c.HardwareType(), + "statusCode", statusCode, + ) return err } - log.WithFields(log.Fields{ - "IP": c.ip, - "Model": c.HardwareType(), - "Group": group, - }).Debug("Ldap group removed.") + c.log.V(1).Info("Ldap group removed.", + "IP", c.ip, + "Model", c.HardwareType(), + "Group", group, + ) return nil } @@ -336,29 +336,29 @@ func (c *C7000) applyAddLdapGroup(group string) (err error) { payload := addLdapGroup{LdapGroup: ldapGroup{Text: group}} statusCode, _, err := c.postXML(payload) if statusCode == 200 || statusCode == 500 { // 500 indicates the group exists. - log.WithFields(log.Fields{ - "step": "applyAddLdapGroup", - "IP": c.ip, - "Model": c.HardwareType(), - "statusCode": statusCode, - }).Debug("Ldap applyAddLdapGroup applied.") + c.log.V(1).Info("Ldap applyAddLdapGroup applied.", + "step", "applyAddLdapGroup", + "IP", c.ip, + "Model", c.HardwareType(), + "statusCode", statusCode, + ) return nil } if statusCode >= 300 || err != nil { - log.WithFields(log.Fields{ - "step": "applyAddLdapGroup", - "IP": c.ip, - "Model": c.HardwareType(), - "statusCode": statusCode, - }).Warn("Ldap applyAddLdapGroup request returned non 200.") + c.log.V(1).Info("Ldap applyAddLdapGroup request returned non 200.", + "step", "applyAddLdapGroup", + "IP", c.ip, + "Model", c.HardwareType(), + "statusCode", statusCode, + ) return err } - log.WithFields(log.Fields{ - "IP": c.ip, - "Model": c.HardwareType(), - }).Debug("Ldap group added.") + c.log.V(1).Info("Ldap group added.", + "IP", c.ip, + "Model", c.HardwareType(), + ) return nil } @@ -380,22 +380,22 @@ func (c *C7000) applyLdapGroupBayACL(role string, group string) (err error) { payload := setLdapGroupBayACL{LdapGroup: ldapGroup{Text: group}, ACL: ACL{Text: userACL}} statusCode, _, err := c.postXML(payload) if statusCode != 200 || err != nil { - log.WithFields(log.Fields{ - "step": "applyLdapGroupBayACL", - "IP": c.ip, - "Model": c.HardwareType(), - "statusCode": statusCode, - "Error": err, - }).Warn("LDAP applyLdapGroupBayACL request returned non 200.") + c.log.V(1).Info("LDAP applyLdapGroupBayACL request returned non 200.", + "step", "applyLdapGroupBayACL", + "IP", c.ip, + "Model", c.HardwareType(), + "statusCode", statusCode, + "Error", err.Error(), + ) return err } - log.WithFields(log.Fields{ - "IP": c.ip, - "Model": c.HardwareType(), - "Role": role, - "Group": group, - }).Debug("Ldap group ACL added.") + c.log.V(1).Info("Ldap group ACL added.", + "IP", c.ip, + "Model", c.HardwareType(), + "Role", role, + "Group", group, + ) return err } @@ -465,21 +465,21 @@ func (c *C7000) applyAddLdapGroupBayAccess(group string) (err error) { statusCode, _, err := c.postXML(payload) if statusCode != 200 || err != nil { - log.WithFields(log.Fields{ - "step": "applyAddLdapGroupBayAccess", - "IP": c.ip, - "Model": c.HardwareType(), - "statusCode": statusCode, - "Error": err, - }).Warn("LDAP applyAddLdapGroupBayAccess apply request returned non 200.") + c.log.V(1).Info("LDAP applyAddLdapGroupBayAccess apply request returned non 200.", + "step", "applyAddLdapGroupBayAccess", + "IP", c.ip, + "Model", c.HardwareType(), + "statusCode", statusCode, + "Error", err.Error(), + ) return err } - log.WithFields(log.Fields{ - "IP": c.ip, - "Model": c.HardwareType(), - "Group": group, - }).Debug("Ldap interconnect and bay ACLs added.") + c.log.V(1).Info("Ldap interconnect and bay ACLs added.", + "IP", c.ip, + "Model", c.HardwareType(), + "Group", group, + ) return err } @@ -490,25 +490,31 @@ func (c *C7000) User(users []*cfgresources.User) (err error) { for _, cfg := range users { if cfg.Name == "" { - log.WithFields(log.Fields{ - "step": "applyUserParams", - "Model": c.HardwareType(), - }).Fatal("User resource expects parameter: Name.") + err = errors.New("user resource expects parameter: Name") + c.log.V(1).Error(err, "user resource expects parameter: Name", + "step", "applyUserParams", + "Model", c.HardwareType(), + ) + return err } if cfg.Password == "" { - log.WithFields(log.Fields{ - "step": "applyUserParams", - "Model": c.HardwareType(), - }).Fatal("User resource expects parameter: Password.") + err = errors.New("user resource expects parameter: Password") + c.log.V(1).Error(err, "user resource expects parameter: Password", + "step", "applyUserParams", + "Model", c.HardwareType(), + ) + return err } if c.isRoleValid(cfg.Role) == false { - log.WithFields(log.Fields{ - "step": "applyUserParams", - "Model": c.HardwareType(), - "Role": cfg.Role, - }).Fatal("User resource Role must be declared and a valid role: admin.") + err = errors.New("user resource Role must be declared and a valid role: admin") + c.log.V(1).Error(err, "user resource Role must be declared and a valid role: admin", + "step", "applyUserParams", + "Model", c.HardwareType(), + "Role", cfg.Role, + ) + return err } username := Username{Text: cfg.Name} @@ -524,11 +530,11 @@ func (c *C7000) User(users []*cfgresources.User) (err error) { return err } - log.WithFields(log.Fields{ - "IP": c.ip, - "Model": c.HardwareType(), - "User": cfg.Name, - }).Debug("User removed.") + c.log.V(1).Info("User removed.", + "IP", c.ip, + "Model", c.HardwareType(), + "User", cfg.Name, + ) //user exists and was removed. return err @@ -542,13 +548,13 @@ func (c *C7000) User(users []*cfgresources.User) (err error) { //user exists if statusCode == 400 { - log.WithFields(log.Fields{ - "step": "applyUserParams", - "user": cfg.Name, - "IP": c.ip, - "Model": c.HardwareType(), - "Return code": statusCode, - }).Debug("User already exists, setting password.") + c.log.V(1).Info("User already exists, setting password.", + "step", "applyUserParams", + "user", cfg.Name, + "IP", c.ip, + "Model", c.HardwareType(), + "Return code", statusCode, + ) //update user password err := c.setUserPassword(cfg.Name, cfg.Password) @@ -570,11 +576,11 @@ func (c *C7000) User(users []*cfgresources.User) (err error) { } - log.WithFields(log.Fields{ - "IP": c.ip, - "Model": c.HardwareType(), - "user": cfg.Name, - }).Debug("User cfg applied.") + c.log.V(1).Info("User cfg applied.", + "IP", c.ip, + "Model", c.HardwareType(), + "user", cfg.Name, + ) } return err @@ -588,22 +594,22 @@ func (c *C7000) setUserPassword(user string, password string) (err error) { statusCode, _, err := c.postXML(payload) if err != nil { - log.WithFields(log.Fields{ - "step": "setUserPassword", - "user": user, - "IP": c.ip, - "Model": c.HardwareType(), - "return code": statusCode, - "Error": err, - }).Warn("Unable to set user password.") + c.log.V(1).Error(err, "unable to set user password.", + "step", "setUserPassword", + "user", user, + "IP", c.ip, + "Model", c.HardwareType(), + "return code", statusCode, + "Error", err.Error(), + ) return err } - log.WithFields(log.Fields{ - "IP": c.ip, - "Model": c.HardwareType(), - "user": user, - }).Debug("User password set.") + c.log.V(1).Info("User password set.", + "IP", c.ip, + "Model", c.HardwareType(), + "user", user, + ) return err } @@ -623,24 +629,24 @@ func (c *C7000) setUserACL(user string, role string) (err error) { statusCode, _, err := c.postXML(payload) if err != nil { - log.WithFields(log.Fields{ - "step": "setUserACL", - "user": user, - "ACL": role, - "IP": c.ip, - "Model": c.HardwareType(), - "return code": statusCode, - "Error": err, - }).Warn("Unable to set user ACL.") + c.log.V(1).Error(err, "unable to set user ACL.", + "step", "setUserACL", + "user", user, + "ACL", role, + "IP", c.ip, + "Model", c.HardwareType(), + "return code", statusCode, + "Error", err.Error(), + ) return err } - log.WithFields(log.Fields{ - "IP": c.ip, - "Model": c.HardwareType(), - "User": user, - "ACL": role, - }).Debug("User ACL set.") + c.log.V(1).Info("User ACL set.", + "IP", c.ip, + "Model", c.HardwareType(), + "User", user, + "ACL", role, + ) return err } @@ -686,22 +692,22 @@ func (c *C7000) applyAddUserBayAccess(user string) (err error) { statusCode, _, err := c.postXML(payload) if statusCode != 200 || err != nil { - log.WithFields(log.Fields{ - "step": "applyAddUserBayAccess", - "IP": c.ip, - "Model": c.HardwareType(), - "statusCode": statusCode, - "Error": err, - }).Warn("LDAP applyAddUserBayAccess apply request returned non 200.") + c.log.V(1).Error(err, "LDAP applyAddUserBayAccess apply request returned non 200.", + "step", "applyAddUserBayAccess", + "IP", c.ip, + "Model", c.HardwareType(), + "statusCode", statusCode, + "Error", err.Error(), + ) return err } - log.WithFields(log.Fields{ - "step": "applyAddUserBayAccess", - "IP": c.ip, - "Model": c.HardwareType(), - "user": user, - }).Debug("User account related interconnect and bay ACLs added.") + c.log.V(1).Info("User account related interconnect and bay ACLs added.", + "step", "applyAddUserBayAccess", + "IP", c.ip, + "Model", c.HardwareType(), + "user", user, + ) return err } @@ -723,26 +729,26 @@ func (c *C7000) applyAddUserBayAccess(user string) (err error) { func (c *C7000) Ntp(cfg *cfgresources.Ntp) (err error) { if cfg.Server1 == "" { - log.WithFields(log.Fields{ - "step": "applyNtpParams", - "Model": c.HardwareType(), - }).Warn("NTP resource expects parameter: server1.") + c.log.V(1).Info("NTP resource expects parameter: server1.", + "step", "applyNtpParams", + "Model", c.HardwareType(), + ) return } if cfg.Timezone == "" { - log.WithFields(log.Fields{ - "step": "applyNtpParams", - "Model": c.HardwareType(), - }).Warn("NTP resource expects parameter: timezone.") + c.log.V(1).Info("NTP resource expects parameter: timezone.", + "step", "applyNtpParams", + "Model", c.HardwareType(), + ) return } if cfg.Enable != true { - log.WithFields(log.Fields{ - "step": "applyNtpParams", - "Model": c.HardwareType(), - }).Debug("Ntp resource declared with enable: false.") + c.log.V(1).Info("Ntp resource declared with enable: false.", + "step", "applyNtpParams", + "Model", c.HardwareType(), + ) return } @@ -755,31 +761,31 @@ func (c *C7000) Ntp(cfg *cfgresources.Ntp) (err error) { //fmt.Printf("%s\n", output) statusCode, _, err := c.postXML(payload) if err != nil || statusCode != 200 { - log.WithFields(log.Fields{ - "step": "applyNtpParams", - "IP": c.ip, - "Model": c.HardwareType(), - "StatusCode": statusCode, - "Error": err, - }).Warn("NTP apply request returned non 200.") + c.log.V(1).Info("NTP apply request returned non 200.", + "step", "applyNtpParams", + "IP", c.ip, + "Model", c.HardwareType(), + "StatusCode", statusCode, + "Error", err.Error(), + ) return err } err = c.applyNtpTimezoneParam(cfg.Timezone) if err != nil { - log.WithFields(log.Fields{ - "step": "applyNtpParams", - "IP": c.ip, - "Model": c.HardwareType(), - "Error": err, - }).Warn("Unable to apply NTP timezone config.") + c.log.V(1).Info("Unable to apply NTP timezone config.", + "step", "applyNtpParams", + "IP", c.ip, + "Model", c.HardwareType(), + "Error", err.Error(), + ) return err } - log.WithFields(log.Fields{ - "IP": c.ip, - "Model": c.HardwareType(), - }).Debug("Date and time config applied.") + c.log.V(1).Info("Date and time config applied.", + "IP", c.ip, + "Model", c.HardwareType(), + ) return err } @@ -792,20 +798,20 @@ func (c *C7000) applyNtpTimezoneParam(timezone string) (err error) { statusCode, _, err := c.postXML(payload) if err != nil || statusCode != 200 { - log.WithFields(log.Fields{ - "step": "applyNtpTimezoneParam", - "IP": c.ip, - "Model": c.HardwareType(), - "Error": err, - "StatusCode": statusCode, - }).Warn("NTP applyNtpTimezoneParam request returned non 200.") + c.log.V(1).Info("NTP applyNtpTimezoneParam request returned non 200.", + "step", "applyNtpTimezoneParam", + "IP", c.ip, + "Model", c.HardwareType(), + "Error", err.Error(), + "StatusCode", statusCode, + ) return err } - log.WithFields(log.Fields{ - "IP": c.ip, - "Model": c.HardwareType(), - }).Debug("Timezone config applied.") + c.log.V(1).Info("Timezone config applied.", + "IP", c.ip, + "Model", c.HardwareType(), + ) return err } @@ -820,41 +826,41 @@ func (c *C7000) Syslog(cfg *cfgresources.Syslog) (err error) { var port int if cfg.Server == "" { - log.WithFields(log.Fields{ - "step": "applySyslogParams", - "IP": c.ip, - "Model": c.HardwareType(), - }).Warn("Syslog resource expects parameter: Server.") + c.log.V(1).Info("Syslog resource expects parameter: Server.", + "step", "applySyslogParams", + "IP", c.ip, + "Model", c.HardwareType(), + ) return } if cfg.Port == 0 { - log.WithFields(log.Fields{ - "step": "applySyslogParams", - "IP": c.ip, - "Model": c.HardwareType(), - }).Debug("Syslog resource port set to default: 514.") + c.log.V(1).Info("Syslog resource port set to default: 514.", + "step", "applySyslogParams", + "IP", c.ip, + "Model", c.HardwareType(), + ) port = 514 } else { port = cfg.Port } if cfg.Enable != true { - log.WithFields(log.Fields{ - "step": "applySyslogParams", - "IP": c.ip, - "Model": c.HardwareType(), - }).Debug("Syslog resource declared with enable: false.") + c.log.V(1).Info("Syslog resource declared with enable: false.", + "step", "applySyslogParams", + "IP", c.ip, + "Model", c.HardwareType(), + ) } c.applySyslogServer(cfg.Server) c.applySyslogPort(port) c.applySyslogEnabled(cfg.Enable) - log.WithFields(log.Fields{ - "IP": c.ip, - "Model": c.HardwareType(), - }).Debug("Syslog config applied.") + c.log.V(1).Info("Syslog config applied.", + "IP", c.ip, + "Model", c.HardwareType(), + ) return err } @@ -867,20 +873,20 @@ func (c *C7000) applySyslogServer(server string) { payload := SetRemoteSyslogServer{Server: server} statusCode, _, err := c.postXML(payload) if err != nil || statusCode != 200 { - log.WithFields(log.Fields{ - "step": "applySyslogServer", - "IP": c.ip, - "Model": c.HardwareType(), - "Error": err, - "StatusCode": statusCode, - }).Warn("Syslog set server request returned non 200.") + c.log.V(1).Error(err, "Syslog set server request returned non 200.", + "step", "applySyslogServer", + "IP", c.ip, + "Model", c.HardwareType(), + "Error", err.Error(), + "StatusCode", statusCode, + ) return } - log.WithFields(log.Fields{ - "IP": c.ip, - "Model": c.HardwareType(), - }).Debug("Syslog server set.") + c.log.V(1).Info("Syslog server set.", + "IP", c.ip, + "Model", c.HardwareType(), + ) return } @@ -892,20 +898,20 @@ func (c *C7000) applySyslogPort(port int) { payload := SetRemoteSyslogPort{Port: port} statusCode, _, err := c.postXML(payload) if err != nil || statusCode != 200 { - log.WithFields(log.Fields{ - "step": "applySyslogPort", - "IP": c.ip, - "Model": c.HardwareType(), - "Error": err, - "StatusCode": statusCode, - }).Warn("Syslog set port request returned non 200.") + c.log.V(1).Error(err, "Syslog set port request returned non 200.", + "step", "applySyslogPort", + "IP", c.ip, + "Model", c.HardwareType(), + "Error", err.Error(), + "StatusCode", statusCode, + ) return } - log.WithFields(log.Fields{ - "IP": c.ip, - "Model": c.HardwareType(), - }).Debug("Syslog port set.") + c.log.V(1).Info("Syslog port set.", + "IP", c.ip, + "Model", c.HardwareType(), + ) return } @@ -918,20 +924,20 @@ func (c *C7000) applySyslogEnabled(enabled bool) { payload := SetRemoteSyslogEnabled{Enabled: enabled} statusCode, _, err := c.postXML(payload) if err != nil || statusCode != 200 { - log.WithFields(log.Fields{ - "step": "SetRemoteSyslogEnabled", - "IP": c.ip, - "Model": c.HardwareType(), - "Error": err, - "StatusCode": statusCode, - }).Warn("Syslog enable request returned non 200.") + c.log.V(1).Error(err, "Syslog enable request returned non 200.", + "step", "SetRemoteSyslogEnabled", + "IP", c.ip, + "Model", c.HardwareType(), + "Error", err.Error(), + "StatusCode", statusCode, + ) return } - log.WithFields(log.Fields{ - "IP": c.ip, - "Model": c.HardwareType(), - }).Debug("Syslog enabled.") + c.log.V(1).Info("Syslog enabled.", + "IP", c.ip, + "Model", c.HardwareType(), + ) return } diff --git a/providers/hp/c7000/setupConnections.go b/providers/hp/c7000/setupConnections.go index d22e69ea..05b85b1f 100644 --- a/providers/hp/c7000/setupConnections.go +++ b/providers/hp/c7000/setupConnections.go @@ -12,7 +12,6 @@ import ( "github.com/bmc-toolbox/bmclib/errors" "github.com/bmc-toolbox/bmclib/internal/httpclient" multierror "github.com/hashicorp/go-multierror" - log "github.com/sirupsen/logrus" ) // Login initiates the connection to a chassis device @@ -51,13 +50,9 @@ func (c *C7000) httpLogin() (err error) { //req.Header.Add("Content-Type", "application/soap+xml; charset=utf-8") req.Header.Add("Content-Type", "text/plain;charset=UTF-8") - if log.GetLevel() == log.TraceLevel { - log.Println(fmt.Sprintf("https://%s/hpoa", c.ip)) - dump, err := httputil.DumpRequestOut(req, true) - if err == nil { - log.Printf("%s\n\n", dump) - } - } + + reqDump, _ := httputil.DumpRequestOut(req, true) + c.log.V(2).Info("requestTrace", "requestDump", string(reqDump), "url", fmt.Sprintf("https://%s/hpoa", c.ip)) resp, err := httpClient.Do(req) if err != nil || resp.StatusCode != 200 { @@ -65,12 +60,8 @@ func (c *C7000) httpLogin() (err error) { } defer resp.Body.Close() - if log.GetLevel() == log.TraceLevel { - dump, err := httputil.DumpResponse(resp, true) - if err == nil { - log.Printf("%s\n\n", dump) - } - } + respDump, _ := httputil.DumpResponse(resp, true) + c.log.V(2).Info("responseTrace", "responseDump", string(respDump)) responseBody, err := ioutil.ReadAll(resp.Body) if err != nil { diff --git a/providers/hp/c7000/xmlhelpers.go b/providers/hp/c7000/xmlhelpers.go index ccac4891..a18475ef 100644 --- a/providers/hp/c7000/xmlhelpers.go +++ b/providers/hp/c7000/xmlhelpers.go @@ -11,8 +11,6 @@ import ( "net/url" "strings" "time" - - log "github.com/sirupsen/logrus" ) // wraps the XML to be sent in the SOAP envelope @@ -83,13 +81,8 @@ func (c *C7000) postXML(data interface{}) (statusCode int, body []byte, err erro // req.Header.Add("Content-Type", "application/soap+xml; charset=utf-8") req.Header.Add("Content-Type", "text/plain;charset=UTF-8") - if log.GetLevel() == log.DebugLevel { - log.Println(fmt.Sprintf("https://%s/hpoa", c.ip)) - dump, err := httputil.DumpRequestOut(req, true) - if err == nil { - log.Printf("%s\n\n", dump) - } - } + reqDump, _ := httputil.DumpRequestOut(req, true) + c.log.V(1).Info("requestDebug", "requestDump", string(reqDump), "url", fmt.Sprintf("https://%s/hpoa", c.ip)) resp, err := c.httpClient.Do(req) if err != nil { @@ -97,12 +90,8 @@ func (c *C7000) postXML(data interface{}) (statusCode int, body []byte, err erro } defer resp.Body.Close() - if log.GetLevel() == log.DebugLevel { - dump, err := httputil.DumpResponse(resp, true) - if err == nil { - log.Printf("%s\n\n", dump) - } - } + respDump, _ := httputil.DumpResponse(resp, true) + c.log.V(1).Info("responseTrace", "responseDump", string(respDump)) body, err = ioutil.ReadAll(resp.Body) if err != nil { diff --git a/providers/hp/ilo/configure.go b/providers/hp/ilo/configure.go index 3044976e..56b3200a 100644 --- a/providers/hp/ilo/configure.go +++ b/providers/hp/ilo/configure.go @@ -8,7 +8,6 @@ import ( "github.com/bmc-toolbox/bmclib/cfgresources" "github.com/bmc-toolbox/bmclib/devices" "github.com/bmc-toolbox/bmclib/internal/helper" - log "github.com/sirupsen/logrus" ) // This ensures the compiler errors if this type is missing @@ -38,11 +37,11 @@ func (i *Ilo) ApplyCfg(config *cfgresources.ResourcesConfig) (err error) { //check sessionKey is available if i.sessionKey == "" { msg := "Expected sessionKey not found, unable to configure BMC." - log.WithFields(log.Fields{ - "step": "Login()", - "IP": i.ip, - "Model": i.HardwareType(), - }).Warn(msg) + i.log.V(1).Info(msg, + "IP", i.ip, + "Model", i.HardwareType(), + "step", "Login()", + ) return errors.New(msg) } @@ -95,12 +94,12 @@ func (i *Ilo) User(users []*cfgresources.User) (err error) { existingUsers, err := i.queryUsers() if err != nil { msg := "Unable to query existing users" - log.WithFields(log.Fields{ - "step": "applyUserParams", - "IP": i.ip, - "Model": i.HardwareType(), - "Error": err, - }).Warn(msg) + i.log.V(1).Info(msg, + "IP", i.ip, + "Model", i.HardwareType(), + "step", "applyUserParams", + "Error", err.Error(), + ) return errors.New(msg) } @@ -110,27 +109,19 @@ func (i *Ilo) User(users []*cfgresources.User) (err error) { if user.Name == "" { msg := "User resource expects parameter: Name." - log.WithFields(log.Fields{ - "step": "applyUserParams", - }).Warn(msg) + i.log.V(1).Info(msg, "step", "applyUserParams") return errors.New(msg) } if user.Password == "" { msg := "User resource expects parameter: Password." - log.WithFields(log.Fields{ - "step": "applyUserParams", - "Username": user.Name, - }).Warn(msg) + i.log.V(1).Info(msg, "step", "applyUserParams", "Username", user.Name) return errors.New(msg) } if !i.isRoleValid(user.Role) { msg := "User resource Role must be declared and a must be a valid role: 'admin' OR 'user'." - log.WithFields(log.Fields{ - "step": "applyUserParams", - "Username": user.Name, - }).Warn(msg) + i.log.V(1).Info(msg, "step", "applyUserParams", "Username", user.Name) return errors.New(msg) } @@ -176,48 +167,52 @@ func (i *Ilo) User(users []*cfgresources.User) (err error) { if user.Enable == false && uexists { userinfo.Method = "del_user" userinfo.UserID = userinfo.ID - log.WithFields(log.Fields{ - "IP": i.ip, - "Model": i.HardwareType(), - "User": user.Name, - }).Debug("User disabled in config, will be removed.") + msg := "User disabled in config, will be removed." + i.log.V(1).Info(msg, + "IP", i.ip, + "Model", i.HardwareType(), + "User", user.Name, + ) postPayload = true } if postPayload { payload, err := json.Marshal(userinfo) if err != nil { - log.WithFields(log.Fields{ - "IP": i.ip, - "Model": i.HardwareType(), - "step": helper.WhosCalling(), - "User": user.Name, - "Error": err, - }).Warn("Unable to marshal userInfo payload to set User config.") + msg := "Unable to marshal userInfo payload to set User config." + i.log.V(1).Info(msg, + "IP", i.ip, + "Model", i.HardwareType(), + "step", helper.WhosCalling(), + "User", user.Name, + "Error", err.Error(), + ) continue } endpoint := "json/user_info" statusCode, response, err := i.post(endpoint, payload) if err != nil || statusCode != 200 { - log.WithFields(log.Fields{ - "IP": i.ip, - "Model": i.HardwareType(), - "endpoint": endpoint, - "step": helper.WhosCalling(), - "User": user.Name, - "StatusCode": statusCode, - "response": string(response), - "Error": err, - }).Warn("POST request to set User config returned error.") + msg := "POST request to set User config returned error." + i.log.V(1).Info(msg, + "IP", i.ip, + "Model", i.HardwareType(), + "endpoint", endpoint, + "step", helper.WhosCalling(), + "User", user.Name, + "StatusCode", statusCode, + "response", string(response), + "Error", err.Error(), + ) + continue } - log.WithFields(log.Fields{ - "IP": i.ip, - "Model": i.HardwareType(), - "User": user.Name, - }).Debug("User parameters applied.") + i.log.V(1).Info("User parameters applied.", + "IP", i.ip, + "Model", i.HardwareType(), + "User", user.Name, + ) } } @@ -234,16 +229,12 @@ func (i *Ilo) Syslog(cfg *cfgresources.Syslog) (err error) { if cfg.Server == "" { msg := "Syslog resource expects parameter: Server." - log.WithFields(log.Fields{ - "step": helper.WhosCalling(), - }).Warn(msg) + i.log.V(1).Info(msg, "step", helper.WhosCalling()) return errors.New(msg) } if cfg.Port == 0 { - log.WithFields(log.Fields{ - "step": helper.WhosCalling(), - }).Debug("Syslog resource port set to default: 514.") + i.log.V(1).Info("Syslog resource port set to default: 514.", "step", helper.WhosCalling()) port = 514 } else { port = cfg.Port @@ -251,9 +242,7 @@ func (i *Ilo) Syslog(cfg *cfgresources.Syslog) (err error) { if cfg.Enable != true { enable = 0 - log.WithFields(log.Fields{ - "step": helper.WhosCalling(), - }).Debug("Syslog resource declared with disable.") + i.log.V(1).Info("Syslog resource declared with disable.", "step", helper.WhosCalling()) } remoteSyslog := RemoteSyslog{ @@ -267,12 +256,12 @@ func (i *Ilo) Syslog(cfg *cfgresources.Syslog) (err error) { payload, err := json.Marshal(remoteSyslog) if err != nil { msg := "Unable to marshal RemoteSyslog payload to set Syslog config." - log.WithFields(log.Fields{ - "IP": i.ip, - "Model": i.HardwareType(), - "step": helper.WhosCalling(), - "Error": err, - }).Warn(msg) + i.log.V(1).Info(msg, + "IP", i.ip, + "Model", i.HardwareType(), + "step", helper.WhosCalling(), + "Error", err.Error(), + ) return errors.New(msg) } @@ -280,22 +269,19 @@ func (i *Ilo) Syslog(cfg *cfgresources.Syslog) (err error) { statusCode, response, err := i.post(endpoint, payload) if err != nil || statusCode != 200 { msg := "POST request to set User config returned error." - log.WithFields(log.Fields{ - "IP": i.ip, - "Model": i.HardwareType(), - "endpoint": endpoint, - "step": helper.WhosCalling(), - "StatusCode": statusCode, - "response": string(response), - "Error": err, - }).Warn(msg) + i.log.V(1).Info(msg, + "IP", i.ip, + "Model", i.HardwareType(), + "endpoint", endpoint, + "step", helper.WhosCalling(), + "StatusCode", statusCode, + "response", string(response), + "Error", err.Error(), + ) return errors.New(msg) } - log.WithFields(log.Fields{ - "IP": i.ip, - "Model": i.HardwareType(), - }).Debug("Syslog parameters applied.") + i.log.V(1).Info("Syslog parameters applied.", "IP", i.ip, "Model", i.HardwareType()) return err } @@ -306,9 +292,7 @@ func (i *Ilo) SetLicense(cfg *cfgresources.License) (err error) { if cfg.Key == "" { msg := "License resource expects parameter: Key." - log.WithFields(log.Fields{ - "step": helper.WhosCalling(), - }).Warn(msg) + i.log.V(1).Info(msg, "step", helper.WhosCalling()) return errors.New(msg) } @@ -321,12 +305,12 @@ func (i *Ilo) SetLicense(cfg *cfgresources.License) (err error) { payload, err := json.Marshal(license) if err != nil { msg := "Unable to marshal License payload to activate License." - log.WithFields(log.Fields{ - "IP": i.ip, - "Model": i.HardwareType(), - "step": helper.WhosCalling(), - "Error": err, - }).Warn(msg) + i.log.V(1).Info(msg, + "IP", i.ip, + "Model", i.HardwareType(), + "step", helper.WhosCalling(), + "Error", err.Error(), + ) return errors.New(msg) } @@ -334,22 +318,19 @@ func (i *Ilo) SetLicense(cfg *cfgresources.License) (err error) { statusCode, response, err := i.post(endpoint, payload) if err != nil || statusCode != 200 { msg := "POST request to set User config returned error." - log.WithFields(log.Fields{ - "IP": i.ip, - "Model": i.HardwareType(), - "endpoint": endpoint, - "step": helper.WhosCalling(), - "StatusCode": statusCode, - "response": string(response), - "Error": err, - }).Warn(msg) + i.log.V(1).Info(msg, + "IP", i.ip, + "Model", i.HardwareType(), + "endpoint", endpoint, + "step", helper.WhosCalling(), + "StatusCode", statusCode, + "response", string(response), + "Error", err.Error(), + ) return errors.New(msg) } - log.WithFields(log.Fields{ - "IP": i.ip, - "Model": i.HardwareType(), - }).Debug("License activated.") + i.log.V(1).Info("License activated.", "IP", i.ip, "Model", i.HardwareType()) return err } @@ -361,17 +342,13 @@ func (i *Ilo) Ntp(cfg *cfgresources.Ntp) (err error) { enable := 1 if cfg.Server1 == "" { msg := "NTP resource expects parameter: server1." - log.WithFields(log.Fields{ - "step": helper.WhosCalling(), - }).Warn(msg) + i.log.V(1).Info(msg, "step", helper.WhosCalling()) return errors.New(msg) } if cfg.Timezone == "" { msg := "NTP resource expects parameter: timezone." - log.WithFields(log.Fields{ - "step": helper.WhosCalling(), - }).Warn(msg) + i.log.V(1).Info(msg, "step", helper.WhosCalling()) return errors.New(msg) } @@ -388,29 +365,24 @@ func (i *Ilo) Ntp(cfg *cfgresources.Ntp) (err error) { _, validTimezone := timezones[cfg.Timezone] if !validTimezone { msg := "NTP resource a valid timezone parameter, for valid timezones see hp/ilo/model.go" - log.WithFields(log.Fields{ - "step": helper.WhosCalling(), - "Unknown Timezone": cfg.Timezone, - }).Warn(msg) + i.log.V(1).Info(msg, "step", helper.WhosCalling(), "UnknownTimezone", cfg.Timezone) return errors.New(msg) } if cfg.Enable != true { enable = 0 - log.WithFields(log.Fields{ - "step": helper.WhosCalling(), - }).Debug("NTP resource declared with disable.") + i.log.V(1).Info("NTP resource declared with disable.", "step", helper.WhosCalling()) } existingConfig, err := i.queryNetworkSntp() if err != nil { msg := "Unable to query existing config" - log.WithFields(log.Fields{ - "step": helper.WhosCalling(), - "IP": i.ip, - "Model": i.HardwareType(), - "Error": err, - }).Warn(msg) + i.log.V(1).Info(msg, + "IP", i.ip, + "Model", i.HardwareType(), + "step", helper.WhosCalling(), + "Error", err.Error(), + ) return errors.New(msg) } @@ -438,12 +410,12 @@ func (i *Ilo) Ntp(cfg *cfgresources.Ntp) (err error) { payload, err := json.Marshal(networkSntp) if err != nil { msg := "Unable to marshal NetworkSntp payload to set NTP config." - log.WithFields(log.Fields{ - "IP": i.ip, - "Model": i.HardwareType(), - "step": helper.WhosCalling(), - "Error": err, - }).Warn(msg) + i.log.V(1).Info(msg, + "IP", i.ip, + "Model", i.HardwareType(), + "step", helper.WhosCalling(), + "Error", err.Error(), + ) return errors.New(msg) } @@ -451,22 +423,19 @@ func (i *Ilo) Ntp(cfg *cfgresources.Ntp) (err error) { statusCode, response, err := i.post(endpoint, payload) if err != nil || statusCode != 200 { msg := "POST request to set NTP config returned error." - log.WithFields(log.Fields{ - "IP": i.ip, - "Model": i.HardwareType(), - "endpoint": endpoint, - "step": helper.WhosCalling(), - "StatusCode": statusCode, - "response": string(response), - "Error": err, - }).Warn(msg) + i.log.V(1).Info(msg, + "IP", i.ip, + "Model", i.HardwareType(), + "endpoint", endpoint, + "step", helper.WhosCalling(), + "StatusCode", statusCode, + "response", string(response), + "Error", err.Error(), + ) return errors.New(msg) } - log.WithFields(log.Fields{ - "IP": i.ip, - "Model": i.HardwareType(), - }).Debug("NTP parameters applied.") + i.log.V(1).Info("NTP parameters applied.", "IP", i.ip, "Model", i.HardwareType()) return err } @@ -479,12 +448,12 @@ func (i *Ilo) LdapGroup(cfg []*cfgresources.LdapGroup, cfgLdap *cfgresources.Lda directoryGroups, err := i.queryDirectoryGroups() if err != nil { msg := "Unable to query existing Ldap groups" - log.WithFields(log.Fields{ - "IP": i.ip, - "Model": i.HardwareType(), - "Step": helper.WhosCalling(), - "Error": err, - }).Warn(msg) + i.log.V(1).Info(msg, + "IP", i.ip, + "Model", i.HardwareType(), + "step", helper.WhosCalling(), + "Error", err.Error(), + ) return errors.New(msg) } @@ -493,21 +462,21 @@ func (i *Ilo) LdapGroup(cfg []*cfgresources.LdapGroup, cfgLdap *cfgresources.Lda var postPayload bool if group.Group == "" { msg := "Ldap resource parameter Group required but not declared." - log.WithFields(log.Fields{ - "Model": i.HardwareType(), - "step": helper.WhosCalling, - "Ldap role": group.Role, - }).Warn(msg) + i.log.V(1).Info(msg, + "Model", i.HardwareType(), + "step", helper.WhosCalling(), + "Ldap role", group.Role, + ) return errors.New(msg) } if !i.isRoleValid(group.Role) { msg := "Ldap resource Role must be a valid role: admin OR user." - log.WithFields(log.Fields{ - "Model": i.HardwareType(), - "step": helper.WhosCalling(), - "Ldap role": group.Role, - }).Warn(msg) + i.log.V(1).Info(msg, + "Model", i.HardwareType(), + "step", helper.WhosCalling(), + "Ldap role", group.Role, + ) return errors.New(msg) } @@ -547,48 +516,48 @@ func (i *Ilo) LdapGroup(cfg []*cfgresources.LdapGroup, cfgLdap *cfgresources.Lda //if the group is disabled remove it if group.Enable == false && gexists { directoryGroup.Method = "del_group" - log.WithFields(log.Fields{ - "IP": i.ip, - "Model": i.HardwareType(), - "User": group.Group, - }).Debug("Ldap role group disabled in config, will be removed.") + i.log.V(1).Info("Ldap role group disabled in config, will be removed.", + "IP", i.ip, + "Model", i.HardwareType(), + "User", group.Group, + ) postPayload = true } if postPayload { payload, err := json.Marshal(directoryGroup) if err != nil { - log.WithFields(log.Fields{ - "IP": i.ip, - "Model": i.HardwareType(), - "Step": helper.WhosCalling(), - "Group": group.Group, - "Error": err, - }).Warn("Unable to marshal directoryGroup payload to set LdapGroup config.") + i.log.V(1).Info("Unable to marshal directoryGroup payload to set LdapGroup config.", + "IP", i.ip, + "Model", i.HardwareType(), + "step", helper.WhosCalling(), + "Group", group.Group, + "Error", err.Error(), + ) continue } endpoint := "json/directory_groups" statusCode, response, err := i.post(endpoint, payload) if err != nil || statusCode != 200 { - log.WithFields(log.Fields{ - "IP": i.ip, - "Model": i.HardwareType(), - "endpoint": endpoint, - "step": helper.WhosCalling(), - "Group": group.Group, - "StatusCode": statusCode, - "response": string(response), - "Error": err, - }).Warn("POST request to set User config returned error.") + i.log.V(1).Info("POST request to set User config returned error.", + "IP", i.ip, + "Model", i.HardwareType(), + "endpoint", endpoint, + "step", helper.WhosCalling(), + "Group", group.Group, + "StatusCode", statusCode, + "response", string(response), + "Error", err.Error(), + ) continue } - log.WithFields(log.Fields{ - "IP": i.ip, - "Model": i.HardwareType(), - "User": group.Group, - }).Debug("LdapGroup parameters applied.") + i.log.V(1).Info("LdapGroup parameters applied.", + "IP", i.ip, + "Model", i.HardwareType(), + "User", group.Group, + ) } @@ -603,28 +572,28 @@ func (i *Ilo) Ldap(cfg *cfgresources.Ldap) (err error) { if cfg.Server == "" { msg := "Ldap resource parameter Server required but not declared." - log.WithFields(log.Fields{ - "Model": i.HardwareType(), - "step": helper.WhosCalling, - }).Warn(msg) + i.log.V(1).Info(msg, + "Model", i.HardwareType(), + "step", helper.WhosCalling(), + ) return errors.New(msg) } if cfg.Port == 0 { msg := "Ldap resource parameter Port required but not declared." - log.WithFields(log.Fields{ - "Model": i.HardwareType(), - "step": helper.WhosCalling, - }).Warn(msg) + i.log.V(1).Info(msg, + "Model", i.HardwareType(), + "step", helper.WhosCalling(), + ) return errors.New(msg) } if cfg.BaseDn == "" { msg := "Ldap resource parameter BaseDn required but not declared." - log.WithFields(log.Fields{ - "Model": i.HardwareType(), - "step": helper.WhosCalling, - }).Warn(msg) + i.log.V(1).Info(msg, + "Model", i.HardwareType(), + "step", helper.WhosCalling(), + ) return errors.New(msg) } @@ -650,12 +619,12 @@ func (i *Ilo) Ldap(cfg *cfgresources.Ldap) (err error) { payload, err := json.Marshal(directory) if err != nil { - log.WithFields(log.Fields{ - "IP": i.ip, - "Model": i.HardwareType(), - "Step": helper.WhosCalling(), - "Error": err, - }).Warn("Unable to marshal directory payload to set Ldap config.") + i.log.V(1).Info("Unable to marshal directory payload to set Ldap config.", + "IP", i.ip, + "Model", i.HardwareType(), + "step", helper.WhosCalling(), + "Error", err.Error(), + ) return err } @@ -663,22 +632,19 @@ func (i *Ilo) Ldap(cfg *cfgresources.Ldap) (err error) { statusCode, response, err := i.post(endpoint, payload) if err != nil || statusCode != 200 { msg := "POST request to set Ldap config returned error." - log.WithFields(log.Fields{ - "IP": i.ip, - "Model": i.HardwareType(), - "endpoint": endpoint, - "step": helper.WhosCalling(), - "StatusCode": statusCode, - "response": string(response), - "Error": err, - }).Warn(msg) + i.log.V(1).Info(msg, + "IP", i.ip, + "Model", i.HardwareType(), + "endpoint", endpoint, + "step", helper.WhosCalling(), + "StatusCode", statusCode, + "response", string(response), + "Error", err.Error(), + ) return err } - log.WithFields(log.Fields{ - "IP": i.ip, - "Model": i.HardwareType(), - }).Debug("Ldap parameters applied.") + i.log.V(1).Info("Ldap parameters applied.", "IP", i.ip, "Model", i.HardwareType()) return err @@ -813,6 +779,7 @@ func (i *Ilo) Network(cfg *cfgresources.Network) (reset bool, err error) { return reset, nil } +// Power settings func (i *Ilo) Power(cfg *cfgresources.Power) error { if cfg.HPE == nil { @@ -839,21 +806,21 @@ func (i *Ilo) Power(cfg *cfgresources.Power) error { } if !changeRequired { - log.WithFields(log.Fields{ - "IP": i.ip, - "current mode": config.PowerMode, - "expected mode": configMode, - "Model": i.HardwareType(), - }).Trace("Power regulator config - no change required.") + i.log.V(2).Info("Power regulator config - no change required.", + "IP", i.ip, + "Model", i.HardwareType(), + "current mode", config.PowerMode, + "expected mode", configMode, + ) return nil } - log.WithFields(log.Fields{ - "IP": i.ip, - "current mode": config.PowerMode, - "to apply mode": configMode, - "Model": i.HardwareType(), - }).Trace("Power regulator change to be applied.") + i.log.V(2).Info("Power regulator change to be applied.", + "IP", i.ip, + "Model", i.HardwareType(), + "current mode", config.PowerMode, + "expected mode", configMode, + ) config.SessionKey = i.sessionKey config.Method = "set" @@ -870,10 +837,10 @@ func (i *Ilo) Power(cfg *cfgresources.Power) error { return fmt.Errorf("Error/non 200 response calling power_regulator, status: %d, error: %s", statusCode, err) } - log.WithFields(log.Fields{ - "IP": i.ip, - "Model": i.HardwareType(), - }).Debug("Power regulator config applied.") + i.log.V(1).Info("Power regulator config applied.", + "IP", i.ip, + "Model", i.HardwareType(), + ) return nil } diff --git a/providers/hp/ilo/ilo.go b/providers/hp/ilo/ilo.go index e4bcf1e2..6a28458e 100644 --- a/providers/hp/ilo/ilo.go +++ b/providers/hp/ilo/ilo.go @@ -2,6 +2,7 @@ package ilo import ( "bytes" + "context" "encoding/json" "encoding/xml" "fmt" @@ -16,14 +17,11 @@ import ( "github.com/bmc-toolbox/bmclib/internal/httpclient" "github.com/bmc-toolbox/bmclib/internal/sshclient" "github.com/bmc-toolbox/bmclib/providers/hp" - - // this make possible to setup logging and properties at any stage - _ "github.com/bmc-toolbox/bmclib/logging" - log "github.com/sirupsen/logrus" + "github.com/go-logr/logr" ) const ( - // HardwareType defines the bmc model that is supported by this package + // BmcType defines the bmc model that is supported by this package BmcType = "ilo" // Ilo2 is the constant for iLO2 @@ -46,10 +44,12 @@ type Ilo struct { sshClient *sshclient.SSHClient loginURL *url.URL rimpBlade *hp.RimpBlade + ctx context.Context + log logr.Logger } // New returns a new Ilo ready to be used -func New(host string, username string, password string) (*Ilo, error) { +func New(ctx context.Context, host string, username string, password string, log logr.Logger) (*Ilo, error) { loginURL, err := url.Parse(fmt.Sprintf("https://%s/json/login_session", host)) if err != nil { return nil, err @@ -90,6 +90,8 @@ func New(host string, username string, password string) (*Ilo, error) { loginURL: loginURL, rimpBlade: rimpBlade, sshClient: sshClient, + ctx: ctx, + log: log, } return ilo, nil } @@ -105,7 +107,7 @@ func (i *Ilo) CheckCredentials() (err error) { // get calls a given json endpoint of the iLO and returns the data func (i *Ilo) get(endpoint string) (payload []byte, err error) { - log.WithFields(log.Fields{"step": "bmc connection", "vendor": hp.VendorID, "ip": i.ip, "endpoint": endpoint}).Debug("retrieving data from bmc") + i.log.V(1).Info("retrieving data from bmc", "step", "bmc connection", "vendor", hp.VendorID, "ip", i.ip, "endpoint", endpoint) bmcURL := fmt.Sprintf("https://%s", i.ip) req, err := http.NewRequest("GET", fmt.Sprintf("%s/%s", bmcURL, endpoint), nil) @@ -123,30 +125,17 @@ func (i *Ilo) get(endpoint string) (payload []byte, err error) { req.AddCookie(cookie) } } - if log.GetLevel() == log.TraceLevel { - dump, err := httputil.DumpRequestOut(req, true) - if err == nil { - log.Println(fmt.Sprintf("[Request] %s/%s", bmcURL, endpoint)) - log.Println(">>>>>>>>>>>>>>>") - log.Printf("%s\n\n", dump) - log.Println(">>>>>>>>>>>>>>>") - } - } + + reqDump, _ := httputil.DumpRequestOut(req, true) + i.log.V(2).Info("requestTrace", "requestDump", string(reqDump), "url", fmt.Sprintf("%s/%s", bmcURL, endpoint)) resp, err := i.httpClient.Do(req) if err != nil { return payload, err } defer resp.Body.Close() - if log.GetLevel() == log.TraceLevel { - dump, err := httputil.DumpResponse(resp, true) - if err == nil { - log.Println("[Response]") - log.Println("<<<<<<<<<<<<<<") - log.Printf("%s\n\n", dump) - log.Println("<<<<<<<<<<<<<<") - } - } + respDump, _ := httputil.DumpResponse(resp, true) + i.log.V(2).Info("responseTrace", "responseDump", string(respDump)) payload, err = ioutil.ReadAll(resp.Body) if err != nil { @@ -180,30 +169,16 @@ func (i *Ilo) post(endpoint string, data []byte) (statusCode int, body []byte, e } } - if log.GetLevel() == log.TraceLevel { - dump, err := httputil.DumpRequestOut(req, true) - if err == nil { - log.Println(fmt.Sprintf("[Request] %s/%s", i.ip, endpoint)) - log.Println(">>>>>>>>>>>>>>>") - log.Printf("%s\n\n", dump) - log.Println(">>>>>>>>>>>>>>>") - } - } + reqDump, _ := httputil.DumpRequestOut(req, true) + i.log.V(2).Info("requestTrace", "requestDump", string(reqDump), "url", fmt.Sprintf("%s/%s", i.ip, endpoint)) resp, err := i.httpClient.Do(req) if err != nil { return 0, []byte{}, err } defer resp.Body.Close() - if log.GetLevel() == log.TraceLevel { - dump, err := httputil.DumpResponse(resp, true) - if err == nil { - log.Println("[Response]") - log.Println("<<<<<<<<<<<<<<") - log.Printf("%s\n\n", dump) - log.Println("<<<<<<<<<<<<<<") - } - } + respDump, _ := httputil.DumpResponse(resp, true) + i.log.V(2).Info("responseTrace", "responseDump", string(respDump)) body, err = ioutil.ReadAll(resp.Body) if err != nil { diff --git a/providers/hp/ilo/ilo_test.go b/providers/hp/ilo/ilo_test.go index 0bbe38c8..9c9749ff 100644 --- a/providers/hp/ilo/ilo_test.go +++ b/providers/hp/ilo/ilo_test.go @@ -1,12 +1,15 @@ package ilo import ( + "context" "net/http" "net/http/httptest" "strings" "testing" "github.com/bmc-toolbox/bmclib/devices" + "github.com/bombsimon/logrusr" + "github.com/sirupsen/logrus" "github.com/spf13/viper" ) @@ -144,8 +147,13 @@ var ( } ) +func init() { + if viper.GetBool("debug") != true { + viper.SetDefault("debug", true) + } +} + func setup() (bmc *Ilo, err error) { - viper.SetDefault("debug", true) mux = http.NewServeMux() server = httptest.NewTLSServer(mux) ip := strings.TrimPrefix(server.URL, "https://") @@ -161,7 +169,8 @@ func setup() (bmc *Ilo, err error) { }) } - bmc, err = New(ip, username, password) + testLog := logrus.New() + bmc, err = New(context.TODO(), ip, username, password, logrusr.NewLogger(testLog)) if err != nil { return bmc, err } diff --git a/providers/hp/ilo/query.go b/providers/hp/ilo/query.go index d197bd56..62586a67 100644 --- a/providers/hp/ilo/query.go +++ b/providers/hp/ilo/query.go @@ -9,8 +9,6 @@ import ( "github.com/bmc-toolbox/bmclib/errors" "github.com/bmc-toolbox/bmclib/internal/helper" - - log "github.com/sirupsen/logrus" ) // CurrentHTTPSCert returns the current x509 certficates configured on the BMC @@ -63,13 +61,14 @@ func (i *Ilo) queryDirectoryGroups() (directoryGroups []DirectoryGroups, err err payload, err := i.get(endpoint) if err != nil { - log.WithFields(log.Fields{ - "IP": i.ip, - "Model": i.HardwareType(), - "endpoint": endpoint, - "step": helper.WhosCalling(), - "Error": err, - }).Warn("GET request failed.") + msg := "GET request failed." + i.log.V(1).Info(msg, + "IP", i.ip, + "Model", i.HardwareType(), + "endpoint", endpoint, + "step", helper.WhosCalling(), + "Error", err.Error(), + ) return directoryGroups, err } @@ -77,12 +76,13 @@ func (i *Ilo) queryDirectoryGroups() (directoryGroups []DirectoryGroups, err err //fmt.Printf("--> %+v\n", userinfo["users"]) err = json.Unmarshal(payload, &directoryGroupAccts) if err != nil { - log.WithFields(log.Fields{ - "IP": i.ip, - "step": helper.WhosCalling(), - "Model": i.HardwareType(), - "Error": err, - }).Warn("Unable to unmarshal payload.") + msg := "Unable to unmarshal payload." + i.log.V(1).Info(msg, + "IP", i.ip, + "Model", i.HardwareType(), + "step", helper.WhosCalling(), + "Error", err.Error(), + ) return directoryGroups, err } @@ -95,13 +95,14 @@ func (i *Ilo) queryUsers() (usersInfo []UserInfo, err error) { payload, err := i.get(endpoint) if err != nil { - log.WithFields(log.Fields{ - "IP": i.ip, - "Model": i.HardwareType(), - "endpoint": endpoint, - "step": helper.WhosCalling(), - "Error": err, - }).Warn("GET request failed.") + msg := "GET request failed." + i.log.V(1).Info(msg, + "IP", i.ip, + "Model", i.HardwareType(), + "endpoint", endpoint, + "step", helper.WhosCalling(), + "Error", err.Error(), + ) return usersInfo, err } @@ -109,13 +110,14 @@ func (i *Ilo) queryUsers() (usersInfo []UserInfo, err error) { //fmt.Printf("--> %+v\n", userinfo["users"]) err = json.Unmarshal(payload, &users) if err != nil { - log.WithFields(log.Fields{ - "step": "queryUserInfo", - "resource": "User", - "IP": i.ip, - "Model": i.HardwareType(), - "Error": err, - }).Warn("Unable to unmarshal payload.") + msg := "Unable to unmarshal payload." + i.log.V(1).Info(msg, + "IP", i.ip, + "Model", i.HardwareType(), + "resource", "User", + "step", "queryUserInfo", + "Error", err.Error(), + ) return usersInfo, err } @@ -128,24 +130,26 @@ func (i *Ilo) queryNetworkSntp() (networkSntp NetworkSntp, err error) { payload, err := i.get(endpoint) if err != nil { - log.WithFields(log.Fields{ - "IP": i.ip, - "Model": i.HardwareType(), - "endpoint": endpoint, - "step": helper.WhosCalling(), - "Error": err, - }).Warn("GET request failed.") + msg := "GET request failed." + i.log.V(1).Info(msg, + "IP", i.ip, + "Model", i.HardwareType(), + "endpoint", endpoint, + "step", helper.WhosCalling(), + "Error", err.Error(), + ) return networkSntp, err } err = json.Unmarshal(payload, &networkSntp) if err != nil { - log.WithFields(log.Fields{ - "IP": i.ip, - "step": helper.WhosCalling(), - "Model": i.HardwareType(), - "Error": err, - }).Warn("Unable to unmarshal payload.") + msg := "Unable to unmarshal payload." + i.log.V(1).Info(msg, + "IP", i.ip, + "Model", i.HardwareType(), + "step", helper.WhosCalling(), + "Error", err.Error(), + ) return networkSntp, err } @@ -160,24 +164,26 @@ func (i *Ilo) queryAccessSettings() (AccessSettings, error) { payload, err := i.get(endpoint) if err != nil { - log.WithFields(log.Fields{ - "IP": i.ip, - "Model": i.HardwareType(), - "endpoint": endpoint, - "step": helper.WhosCalling(), - "Error": err, - }).Warn("GET request failed.") + msg := "GET request failed." + i.log.V(1).Info(msg, + "IP", i.ip, + "Model", i.HardwareType(), + "endpoint", endpoint, + "step", helper.WhosCalling(), + "Error", err.Error(), + ) return accessSettings, err } err = json.Unmarshal(payload, &accessSettings) if err != nil { - log.WithFields(log.Fields{ - "IP": i.ip, - "step": helper.WhosCalling(), - "Model": i.HardwareType(), - "Error": err, - }).Warn("Unable to unmarshal payload.") + msg := "Unable to unmarshal payload." + i.log.V(1).Info(msg, + "IP", i.ip, + "Model", i.HardwareType(), + "step", helper.WhosCalling(), + "Error", err.Error(), + ) return accessSettings, err } @@ -192,24 +198,26 @@ func (i *Ilo) queryNetworkIPv4() (NetworkIPv4, error) { payload, err := i.get(endpoint) if err != nil { - log.WithFields(log.Fields{ - "IP": i.ip, - "Model": i.HardwareType(), - "endpoint": endpoint, - "step": helper.WhosCalling(), - "Error": err, - }).Warn("GET request failed.") + msg := "GET request failed." + i.log.V(1).Info(msg, + "IP", i.ip, + "Model", i.HardwareType(), + "endpoint", endpoint, + "step", helper.WhosCalling(), + "Error", err.Error(), + ) return networkIPv4, err } err = json.Unmarshal(payload, &networkIPv4) if err != nil { - log.WithFields(log.Fields{ - "IP": i.ip, - "step": helper.WhosCalling(), - "Model": i.HardwareType(), - "Error": err, - }).Warn("Unable to unmarshal payload.") + msg := "Unable to unmarshal payload." + i.log.V(1).Info(msg, + "IP", i.ip, + "Model", i.HardwareType(), + "step", helper.WhosCalling(), + "Error", err.Error(), + ) return networkIPv4, err } @@ -224,24 +232,26 @@ func (i *Ilo) queryPowerRegulator() (PowerRegulator, error) { payload, err := i.get(endpoint) if err != nil { - log.WithFields(log.Fields{ - "IP": i.ip, - "Model": i.HardwareType(), - "endpoint": endpoint, - "step": helper.WhosCalling(), - "Error": err, - }).Warn("GET request failed.") + msg := "GET request failed." + i.log.V(1).Info(msg, + "IP", i.ip, + "Model", i.HardwareType(), + "endpoint", endpoint, + "step", helper.WhosCalling(), + "Error", err.Error(), + ) return PowerRegulator{}, err } err = json.Unmarshal(payload, &powerRegulator) if err != nil { - log.WithFields(log.Fields{ - "IP": i.ip, - "step": helper.WhosCalling(), - "Model": i.HardwareType(), - "Error": err, - }).Warn("Unable to unmarshal payload.") + msg := "Unable to unmarshal payload." + i.log.V(1).Info(msg, + "IP", i.ip, + "Model", i.HardwareType(), + "step", helper.WhosCalling(), + "Error", err.Error(), + ) return PowerRegulator{}, err } diff --git a/providers/hp/ilo/setupConnection.go b/providers/hp/ilo/setupConnection.go index c300ae7d..c8291a7a 100644 --- a/providers/hp/ilo/setupConnection.go +++ b/providers/hp/ilo/setupConnection.go @@ -15,7 +15,6 @@ import ( "github.com/bmc-toolbox/bmclib/providers/hp" multierror "github.com/hashicorp/go-multierror" - log "github.com/sirupsen/logrus" ) // Login initiates the connection to a bmc device @@ -29,7 +28,7 @@ func (i *Ilo) httpLogin() (err error) { return err } - log.WithFields(log.Fields{"step": "bmc connection", "vendor": hp.VendorID, "ip": i.ip}).Debug("connecting to bmc") + i.log.V(1).Info("connecting to bmc", "step", "bmc connection", "vendor", hp.VendorID, "ip", i.ip) data := fmt.Sprintf("{\"method\":\"login\", \"user_login\":\"%s\", \"password\":\"%s\" }", i.username, i.password) @@ -39,6 +38,9 @@ func (i *Ilo) httpLogin() (err error) { } req.Header.Set("Content-Type", "application/json") + reqDump, _ := httputil.DumpRequestOut(req, true) + i.log.V(2).Info("requestTrace", "requestDump", string(reqDump), "url", i.loginURL.String()) + resp, err := httpClient.Do(req) if err != nil { return err @@ -55,22 +57,8 @@ func (i *Ilo) httpLogin() (err error) { } } - if log.GetLevel() == log.TraceLevel { - dump, err := httputil.DumpRequestOut(req, true) - if err == nil { - log.Println(fmt.Sprintf("[Request] %s", i.loginURL.String())) - log.Println(">>>>>>>>>>>>>>>") - log.Printf("%s\n\n", dump) - log.Println(">>>>>>>>>>>>>>>") - } - } - if i.sessionKey == "" { - log.WithFields(log.Fields{ - "step": "Login()", - "IP": i.ip, - "Model": i.HardwareType(), - }).Warn("Expected sessionKey cookie value not found.") + i.log.V(1).Info("Expected sessionKey cookie value not found.", "step", "Login()", "IP", i.ip, "Model", i.HardwareType()) } if resp.StatusCode == 404 { @@ -82,15 +70,8 @@ func (i *Ilo) httpLogin() (err error) { return err } defer resp.Body.Close() - if log.GetLevel() == log.TraceLevel { - dump, err := httputil.DumpResponse(resp, true) - if err == nil { - log.Println("[Response]") - log.Println("<<<<<<<<<<<<<<") - log.Printf("%s\n\n", dump) - log.Println("<<<<<<<<<<<<<<") - } - } + respDump, _ := httputil.DumpResponse(resp, true) + i.log.V(2).Info("responseTrace", "responseDump", string(respDump)) if strings.Contains(string(payload), "Invalid login attempt") { return errors.ErrLoginFailed @@ -106,7 +87,7 @@ func (i *Ilo) Close() error { var multiErr error if i.httpClient != nil { - log.WithFields(log.Fields{"step": "bmc connection", "vendor": hp.VendorID, "ip": i.ip}).Debug("logout from bmc http") + i.log.V(1).Info("logout from bmc http", "step", "bmc connection", "vendor", hp.VendorID, "ip", i.ip) data := []byte(fmt.Sprintf(`{"method":"logout", "session_key": "%s"}`, i.sessionKey)) @@ -116,15 +97,8 @@ func (i *Ilo) Close() error { } else { req.Header.Set("Content-Type", "application/json") - if log.GetLevel() == log.TraceLevel { - dump, err := httputil.DumpRequestOut(req, true) - if err == nil { - log.Println(fmt.Sprintf("[Request] %s", i.loginURL.String())) - log.Println(">>>>>>>>>>>>>>>") - log.Printf("%s\n\n", dump) - log.Println(">>>>>>>>>>>>>>>") - } - } + reqDump, _ := httputil.DumpRequestOut(req, true) + i.log.V(2).Info("requestTrace", "requestDump", string(reqDump), "url", i.loginURL.String()) resp, err := i.httpClient.Do(req) if err != nil { @@ -133,15 +107,8 @@ func (i *Ilo) Close() error { defer resp.Body.Close() defer io.Copy(ioutil.Discard, resp.Body) - if log.GetLevel() == log.TraceLevel { - dump, err := httputil.DumpResponse(resp, true) - if err == nil { - log.Println("[Response]") - log.Println("<<<<<<<<<<<<<<") - log.Printf("%s\n\n", dump) - log.Println("<<<<<<<<<<<<<<") - } - } + respDump, _ := httputil.DumpResponse(resp, true) + i.log.V(2).Info("responseTrace", "responseDump", string(respDump)) } } diff --git a/providers/supermicro/supermicrox/configure.go b/providers/supermicro/supermicrox/configure.go index 0864b220..7502e572 100644 --- a/providers/supermicro/supermicrox/configure.go +++ b/providers/supermicro/supermicrox/configure.go @@ -11,8 +11,6 @@ import ( "strings" "time" - log "github.com/sirupsen/logrus" - "github.com/bmc-toolbox/bmclib/cfgresources" "github.com/bmc-toolbox/bmclib/devices" "github.com/bmc-toolbox/bmclib/internal/helper" @@ -108,12 +106,7 @@ func (s *SupermicroX) User(users []*cfgresources.User) (err error) { currentUsers, err := s.queryUserAccounts() if err != nil { msg := "Unable to query current user accounts." - log.WithFields(log.Fields{ - "IP": s.ip, - "Model": s.HardwareType(), - "Step": helper.WhosCalling(), - "Error": err, - }).Warn(msg) + s.log.V(1).Info(msg, "ip", s.ip, "model", s.HardwareType(), "step", helper.WhosCalling(), "error", err.Error()) return errors.New(msg) } @@ -122,27 +115,19 @@ func (s *SupermicroX) User(users []*cfgresources.User) (err error) { if user.Name == "" { msg := "User resource expects parameter: Name." - log.WithFields(log.Fields{ - "step": "applyUserParams", - }).Warn(msg) + s.log.V(1).Info(msg, "step", "applyUserParams") return errors.New(msg) } if user.Password == "" { msg := "User resource expects parameter: Password." - log.WithFields(log.Fields{ - "step": "applyUserParams", - "Username": user.Name, - }).Warn(msg) + s.log.V(1).Info(msg, "step", "applyUserParams", "username", user.Name) return errors.New(msg) } if !s.isRoleValid(user.Role) { msg := "User resource Role must be declared and a must be a valid role: 'admin' OR 'user'." - log.WithFields(log.Fields{ - "step": "applyUserParams", - "Username": user.Name, - }).Warn(msg) + s.log.V(1).Info(msg, "step", "applyUserParams", "username", user.Name) return errors.New(msg) } @@ -178,22 +163,17 @@ func (s *SupermicroX) User(users []*cfgresources.User) (err error) { statusCode, err := s.post(endpoint, &form, []byte{}, "") if err != nil || statusCode != 200 { msg := "POST request to set User config returned error." - log.WithFields(log.Fields{ - "IP": s.ip, - "Model": s.HardwareType(), - "Endpoint": endpoint, - "StatusCode": statusCode, - "Step": helper.WhosCalling(), - "Error": err, - }).Warn(msg) + s.log.V(1).Info(msg, + "ip", s.ip, + "model", s.HardwareType(), + "endpoint", endpoint, + "statusCode", statusCode, + "step", helper.WhosCalling(), + "error", err.Error()) return errors.New(msg) } - log.WithFields(log.Fields{ - "IP": s.ip, - "Model": s.HardwareType(), - "User": user.Name, - }).Debug("User parameters applied.") + s.log.V(1).Info("User parameters applied.", "ip", s.ip, "model", s.HardwareType(), "user", user.Name) userID++ } @@ -235,21 +215,17 @@ func (s *SupermicroX) Network(cfg *cfgresources.Network) (reset bool, err error) statusCode, err := s.post(endpoint, &form, []byte{}, "") if err != nil || statusCode != 200 { msg := "POST request to set Port config returned error." - log.WithFields(log.Fields{ - "IP": s.ip, - "Model": s.HardwareType(), - "Endpoint": endpoint, - "StatusCode": statusCode, - "Step": helper.WhosCalling(), - "Error": err, - }).Warn(msg) + s.log.V(1).Info(msg, + "ip", s.ip, + "model", s.HardwareType(), + "endpoint", endpoint, + "statusCode", statusCode, + "step", helper.WhosCalling(), + "error", err.Error()) return reset, errors.New(msg) } - log.WithFields(log.Fields{ - "IP": s.ip, - "Model": s.HardwareType(), - }).Debug("Network config parameters applied.") + s.log.V(1).Info("Network config parameters applied.", "ip", s.ip, "model", s.HardwareType()) return reset, err } @@ -259,39 +235,35 @@ func (s *SupermicroX) Ntp(cfg *cfgresources.Ntp) (err error) { var enable string if cfg.Server1 == "" { - log.WithFields(log.Fields{ - "step": "applyNtpParams", - "Model": s.HardwareType(), - }).Warn("NTP resource expects parameter: server1.") + s.log.V(1).Info("NTP resource expects parameter: server1.", + "step", "applyNtpParams", + "model", s.HardwareType()) return } if cfg.Timezone == "" { - log.WithFields(log.Fields{ - "step": "applyNtpParams", - "Model": s.HardwareType(), - }).Warn("NTP resource expects parameter: timezone.") + s.log.V(1).Info("NTP resource expects parameter: timezone.", + "step", "applyNtpParams", + "model", s.HardwareType()) return } tzLocation, err := time.LoadLocation(cfg.Timezone) if err != nil { - log.WithFields(log.Fields{ - "step": "applyNtpParams", - "Model": s.HardwareType(), - "Declared timezone": cfg.Timezone, - "Error": err, - }).Warn("NTP resource declared parameter timezone invalid.") + s.log.V(1).Info("NTP resource declared parameter timezone invalid.", + "step", "applyNtpParams", + "model", s.HardwareType(), + "declaredTtimezone", cfg.Timezone, + "error", err.Error()) return } tzUtcOffset := timezoneToUtcOffset(tzLocation) if cfg.Enable != true { - log.WithFields(log.Fields{ - "step": "applyNtpParams", - "Model": s.HardwareType(), - }).Debug("Ntp resource declared with enable: false.") + s.log.V(1).Info("Ntp resource declared with enable: false.", + "step", "applyNtpParams", + "model", s.HardwareType()) return } @@ -329,22 +301,19 @@ func (s *SupermicroX) Ntp(cfg *cfgresources.Ntp) (err error) { statusCode, err := s.post(endpoint, &form, []byte{}, "") if err != nil || statusCode != 200 { msg := "POST request to set Syslog config returned error." - log.WithFields(log.Fields{ - "IP": s.ip, - "Model": s.HardwareType(), - "Endpoint": endpoint, - "StatusCode": statusCode, - "Step": helper.WhosCalling(), - "Error": err, - }).Warn(msg) + s.log.V(1).Info(msg, + "ip", s.ip, + "model", s.HardwareType(), + "endpoint", endpoint, + "statusCode", statusCode, + "step", helper.WhosCalling(), + "error", err.Error()) return errors.New(msg) } - // - log.WithFields(log.Fields{ - "IP": s.ip, - "Model": s.HardwareType(), - }).Debug("NTP config parameters applied.") + s.log.V(1).Info("NTP config parameters applied.", + "ip", s.ip, + "model", s.HardwareType()) return err } @@ -366,28 +335,23 @@ func (s *SupermicroX) LdapGroup(cfgGroup []*cfgresources.LdapGroup, cfgLdap *cfg if cfgLdap.Server == "" { msg := "Ldap resource parameter Server required but not declared." - log.WithFields(log.Fields{ - "step": helper.WhosCalling(), - "Model": s.HardwareType(), - }).Warn(msg) + s.log.V(1).Info(msg, "step", helper.WhosCalling(), "model", s.HardwareType()) return errors.New(msg) } //first some preliminary checks if cfgLdap.Port == 0 { msg := "Ldap resource parameter Port required but not declared" - log.WithFields(log.Fields{ - "step": helper.WhosCalling(), - "Model": s.HardwareType(), - }).Warn(msg) + s.log.V(1).Info(msg, + "step", helper.WhosCalling(), + "model", s.HardwareType()) return errors.New(msg) } if cfgLdap.Enable != true { - log.WithFields(log.Fields{ - "step": helper.WhosCalling(), - "Model": s.HardwareType(), - }).Debug("Ldap resource declared with enable: false.") + s.log.V(1).Info("Ldap resource declared with enable: false.", + "step", helper.WhosCalling(), + "model", s.HardwareType()) return } @@ -395,20 +359,14 @@ func (s *SupermicroX) LdapGroup(cfgGroup []*cfgresources.LdapGroup, cfgLdap *cfg if cfgLdap.BaseDn == "" { msg := "Ldap resource parameter BaseDn required but not declared." - log.WithFields(log.Fields{ - "step": helper.WhosCalling(), - "Model": s.HardwareType(), - }).Warn(msg) + s.log.V(1).Info(msg, "step", helper.WhosCalling(), "model", s.HardwareType()) return errors.New(msg) } serverIP, err := net.LookupIP(cfgLdap.Server) if err != nil || serverIP == nil { msg := "Unable to lookup the IP for ldap server hostname." - log.WithFields(log.Fields{ - "step": helper.WhosCalling(), - "Model": s.HardwareType(), - }).Warn(msg) + s.log.V(1).Info(msg, "step", helper.WhosCalling(), "model", s.HardwareType()) return errors.New(msg) } @@ -422,10 +380,7 @@ func (s *SupermicroX) LdapGroup(cfgGroup []*cfgresources.LdapGroup, cfgLdap *cfg if group.Role == "" { msg := "Ldap resource parameter Role required but not declared." - log.WithFields(log.Fields{ - "Role": group.Role, - "step": helper.WhosCalling(), - }).Warn(msg) + s.log.V(1).Info(msg, "step", helper.WhosCalling(), "role", group.Role) continue } @@ -435,29 +390,22 @@ func (s *SupermicroX) LdapGroup(cfgGroup []*cfgresources.LdapGroup, cfgLdap *cfg if group.Group == "" { msg := "Ldap resource parameter Group required but not declared." - log.WithFields(log.Fields{ - "Role": group.Role, - "step": helper.WhosCalling(), - }).Warn(msg) + s.log.V(1).Info(msg, "step", helper.WhosCalling(), "role", group.Role) return errors.New(msg) } if group.GroupBaseDn == "" { msg := "Ldap resource parameter GroupBaseDn required but not declared." - log.WithFields(log.Fields{ - "Role": group.Role, - "Group": group.Group, - "step": helper.WhosCalling(), - }).Warn(msg) + s.log.V(1).Info(msg, + "step", helper.WhosCalling(), + "group", group.Group, + "role", group.Role) return errors.New(msg) } if !s.isRoleValid(group.Role) { msg := "Ldap resource Role must be a valid role: admin OR user." - log.WithFields(log.Fields{ - "Role": group.Role, - "step": "applyLdapParams", - }).Warn(msg) + s.log.V(1).Info(msg, "step", helper.WhosCalling(), "role", group.Role) return errors.New(msg) } @@ -477,22 +425,18 @@ func (s *SupermicroX) LdapGroup(cfgGroup []*cfgresources.LdapGroup, cfgLdap *cfg statusCode, err := s.post(endpoint, &form, []byte{}, "") if err != nil || statusCode != 200 { msg := "POST request to set Ldap config returned error." - log.WithFields(log.Fields{ - "IP": s.ip, - "Model": s.HardwareType(), - "Endpoint": endpoint, - "StatusCode": statusCode, - "Step": helper.WhosCalling(), - "Error": err, - }).Warn(msg) + s.log.V(1).Info(msg, + "step", helper.WhosCalling(), + "ip", s.ip, + "model", s.HardwareType(), + "endpoint", endpoint, + "statusCode", statusCode, + "error", err.Error()) return errors.New(msg) } } - log.WithFields(log.Fields{ - "IP": s.ip, - "Model": s.HardwareType(), - }).Debug("Ldap config parameters applied.") + s.log.V(1).Info("Ldap config parameters applied.", "ip", s.ip, "model", s.HardwareType()) return err } @@ -505,37 +449,27 @@ func (s *SupermicroX) Syslog(cfg *cfgresources.Syslog) (err error) { if cfg.Server == "" { msg := "Syslog resource expects parameter: Server." - log.WithFields(log.Fields{ - "step": helper.WhosCalling(), - "Model": s.HardwareType(), - }).Warn(msg) + s.log.V(1).Info(msg, "step", helper.WhosCalling(), "model", s.HardwareType()) return errors.New(msg) } if cfg.Port == 0 { - log.WithFields(log.Fields{ - "step": helper.WhosCalling(), - "Model": s.HardwareType(), - }).Debug("Syslog resource port set to default: 514.") + msg := "Syslog resource port set to default: 514." + s.log.V(1).Info(msg, "step", helper.WhosCalling(), "model", s.HardwareType()) port = 514 } else { port = cfg.Port } if cfg.Enable != true { - log.WithFields(log.Fields{ - "step": helper.WhosCalling(), - "Model": s.HardwareType(), - }).Debug("Syslog resource declared with disable.") + msg := "Syslog resource declared with disable." + s.log.V(1).Info(msg, "step", helper.WhosCalling(), "model", s.HardwareType()) } serverIP, err := net.LookupIP(cfg.Server) if err != nil || serverIP == nil { msg := "Unable to lookup IP for syslog server hostname, yes supermicros requires the Syslog server IP :|." - log.WithFields(log.Fields{ - "step": helper.WhosCalling(), - "Model": s.HardwareType(), - }).Warn(msg) + s.log.V(1).Info(msg, "step", helper.WhosCalling(), "model", s.HardwareType()) return errors.New(msg) } @@ -553,14 +487,13 @@ func (s *SupermicroX) Syslog(cfg *cfgresources.Syslog) (err error) { statusCode, err := s.post(endpoint, &form, []byte{}, "") if err != nil || statusCode != 200 { msg := "POST request to set Syslog config returned error." - log.WithFields(log.Fields{ - "IP": s.ip, - "Model": s.HardwareType(), - "Endpoint": endpoint, - "StatusCode": statusCode, - "step": helper.WhosCalling(), - "Error": err, - }).Warn(msg) + s.log.V(1).Info(msg, + "step", helper.WhosCalling(), + "ip", s.ip, + "model", s.HardwareType(), + "endpoint", endpoint, + "statusCode", statusCode, + "error", err.Error()) return errors.New(msg) } @@ -573,21 +506,17 @@ func (s *SupermicroX) Syslog(cfg *cfgresources.Syslog) (err error) { statusCode, err = s.post(endpoint, &form, []byte{}, "") if err != nil || statusCode != 200 { msg := "POST request to enable maintenance alerts returned error." - log.WithFields(log.Fields{ - "IP": s.ip, - "Model": s.HardwareType(), - "Endpoint": endpoint, - "StatusCode": statusCode, - "step": helper.WhosCalling(), - "Error": err, - }).Warn(msg) + s.log.V(1).Info(msg, + "step", helper.WhosCalling(), + "ip", s.ip, + "model", s.HardwareType(), + "endpoint", endpoint, + "statusCode", statusCode, + "error", err.Error()) return errors.New(msg) } - log.WithFields(log.Fields{ - "IP": s.ip, - "Model": s.HardwareType(), - }).Debug("Syslog config parameters applied.") + s.log.V(1).Info("Syslog config parameters applied.", "ip", s.ip, "model", s.HardwareType()) return err } @@ -639,14 +568,14 @@ func (s *SupermicroX) UploadHTTPSCert(cert []byte, certFileName string, key []by // 1. upload status, err := s.post(endpoint, &url.Values{}, form.Bytes(), w.FormDataContentType()) if err != nil || status != 200 { - log.WithFields(log.Fields{ - "IP": s.ip, - "Model": s.HardwareType(), - "Endpoint": endpoint, - "StatusCode": status, - "Step": helper.WhosCalling(), - "Error": err, - }).Warn("Cert form upload POST request failed, expected 200.") + msg := "Cert form upload POST request failed, expected 200." + s.log.V(1).Info(msg, + "step", helper.WhosCalling(), + "ip", s.ip, + "model", s.HardwareType(), + "endpoint", endpoint, + "statusCode", status, + "error", err.Error()) return false, err } @@ -681,14 +610,14 @@ func (s *SupermicroX) validateSSL() error { var endpoint = "ipmi.cgi" status, err := s.post(endpoint, &v, []byte{}, "") if err != nil || status != 200 { - log.WithFields(log.Fields{ - "IP": s.ip, - "Model": s.HardwareType(), - "Endpoint": endpoint, - "StatusCode": status, - "Step": helper.WhosCalling(), - "Error": err, - }).Warn("Cert validate POST request failed, expected 200.") + msg := "Cert validate POST request failed, expected 200." + s.log.V(1).Info(msg, + "step", helper.WhosCalling(), + "ip", s.ip, + "model", s.HardwareType(), + "endpoint", endpoint, + "statusCode", status, + "error", err.Error()) return err } @@ -706,14 +635,14 @@ func (s *SupermicroX) statusSSL() error { var endpoint = "ipmi.cgi" status, err := s.post(endpoint, &v, []byte{}, "") if err != nil || status != 200 { - log.WithFields(log.Fields{ - "IP": s.ip, - "Model": s.HardwareType(), - "Endpoint": endpoint, - "StatusCode": status, - "Step": helper.WhosCalling(), - "Error": err, - }).Warn("Cert status POST request failed, expected 200.") + msg := "Cert status POST request failed, expected 200." + s.log.V(1).Info(msg, + "step", helper.WhosCalling(), + "ip", s.ip, + "model", s.HardwareType(), + "endpoint", endpoint, + "statusCode", status, + "error", err.Error()) return err } diff --git a/providers/supermicro/supermicrox/setupConnection.go b/providers/supermicro/supermicrox/setupConnection.go index 4e960de7..b842fe51 100644 --- a/providers/supermicro/supermicrox/setupConnection.go +++ b/providers/supermicro/supermicrox/setupConnection.go @@ -13,7 +13,6 @@ import ( "github.com/bmc-toolbox/bmclib/errors" "github.com/bmc-toolbox/bmclib/internal/httpclient" "github.com/bmc-toolbox/bmclib/providers/supermicro" - log "github.com/sirupsen/logrus" ) // httpLogin initiates the connection to an SupermicroX device @@ -27,7 +26,7 @@ func (s *SupermicroX) httpLogin() (err error) { return err } - log.WithFields(log.Fields{"step": "bmc connection", "vendor": supermicro.VendorID, "ip": s.ip}).Debug("connecting to bmc") + s.log.V(1).Info("connecting to bmc", "step", "bmc connection", "vendor", supermicro.VendorID, "ip", s.ip) data := fmt.Sprintf("name=%s&pwd=%s", s.username, s.password) req, err := http.NewRequest("POST", fmt.Sprintf("https://%s/cgi/login.cgi", s.ip), bytes.NewBufferString(data)) @@ -64,7 +63,7 @@ func (s *SupermicroX) httpLogin() (err error) { func (s *SupermicroX) Close() (err error) { if s.httpClient != nil { bmcURL := fmt.Sprintf("https://%s/cgi/logout.cgi", s.ip) - log.WithFields(log.Fields{"step": "bmc connection", "vendor": supermicro.VendorID, "ip": s.ip}).Debug("logout from bmc") + s.log.V(1).Info("logout from bmc", "step", "bmc connection", "vendor", supermicro.VendorID, "ip", s.ip) req, err := http.NewRequest("POST", bmcURL, nil) if err != nil { @@ -80,16 +79,8 @@ func (s *SupermicroX) Close() (err error) { req.AddCookie(cookie) } } - if log.GetLevel() == log.TraceLevel { - log.Println(fmt.Sprintf("https://%s/cgi/%s", bmcURL, s.ip)) - dump, err := httputil.DumpRequestOut(req, true) - if err == nil { - log.Println("[Request]") - log.Println(">>>>>>>>>>>>>>>") - log.Printf("%s\n\n", dump) - log.Println(">>>>>>>>>>>>>>>") - } - } + reqDump, _ := httputil.DumpRequestOut(req, true) + s.log.V(2).Info("request", "url", fmt.Sprintf("https://%s/cgi/%s", bmcURL, s.ip), "requestDump", reqDump) resp, err := s.httpClient.Do(req) if err != nil { @@ -99,17 +90,6 @@ func (s *SupermicroX) Close() (err error) { defer resp.Body.Close() defer io.Copy(ioutil.Discard, resp.Body) - if log.GetLevel() == log.TraceLevel { - log.Println(fmt.Sprintf("https://%s/cgi/%s", bmcURL, s.ip)) - dump, err := httputil.DumpRequestOut(req, true) - if err == nil { - log.Println("[Request]") - log.Println(">>>>>>>>>>>>>>>") - log.Printf("%s\n\n", dump) - log.Println(">>>>>>>>>>>>>>>") - } - } - return err } return err diff --git a/providers/supermicro/supermicrox/supermicrox.go b/providers/supermicro/supermicrox/supermicrox.go index a99dc648..003748b1 100644 --- a/providers/supermicro/supermicrox/supermicrox.go +++ b/providers/supermicro/supermicrox/supermicrox.go @@ -2,6 +2,7 @@ package supermicrox import ( "bytes" + "context" "encoding/xml" "fmt" "io/ioutil" @@ -14,16 +15,13 @@ import ( "github.com/bmc-toolbox/bmclib/devices" "github.com/bmc-toolbox/bmclib/errors" "github.com/bmc-toolbox/bmclib/internal/httpclient" + "github.com/go-logr/logr" "github.com/bmc-toolbox/bmclib/providers/supermicro" - - // this make possible to setup logging and properties at any stage - _ "github.com/bmc-toolbox/bmclib/logging" - log "github.com/sirupsen/logrus" ) const ( - // HardwareType defines the bmc model that is supported by this package + // BmcType defines the bmc model that is supported by this package BmcType = "supermicrox" // X10 is the constant for x10 servers @@ -38,11 +36,18 @@ type SupermicroX struct { username string password string httpClient *http.Client + ctx context.Context + log logr.Logger } // New returns a new SupermicroX instance ready to be used -func New(ip string, username string, password string) (sm *SupermicroX, err error) { - return &SupermicroX{ip: ip, username: username, password: password}, err +func New(ctx context.Context, ip string, username string, password string, log logr.Logger) (sm *SupermicroX, err error) { + return &SupermicroX{ + ip: ip, + username: username, + password: password, + ctx: ctx, + log: log}, err } // CheckCredentials verify whether the credentials are valid or not @@ -74,15 +79,8 @@ func (s *SupermicroX) get(endpoint string) (payload []byte, err error) { } } - if log.GetLevel() == log.TraceLevel { - dump, err := httputil.DumpRequestOut(req, true) - if err == nil { - log.Println(fmt.Sprintf("[Request] https://%s/%s", bmcURL, endpoint)) - log.Println(">>>>>>>>>>>>>>>") - log.Printf("%s\n\n", dump) - log.Println(">>>>>>>>>>>>>>>") - } - } + reqDump, _ := httputil.DumpRequestOut(req, true) + s.log.V(2).Info("", "request", fmt.Sprintf("https://%s/%s", bmcURL, endpoint), "requestDump", string(reqDump)) resp, err := s.httpClient.Do(req) if err != nil { @@ -90,15 +88,8 @@ func (s *SupermicroX) get(endpoint string) (payload []byte, err error) { } defer resp.Body.Close() - if log.GetLevel() == log.TraceLevel { - dump, err := httputil.DumpResponse(resp, true) - if err == nil { - log.Println("[Response]") - log.Println("<<<<<<<<<<<<<<") - log.Printf("%s\n\n", dump) - log.Println("<<<<<<<<<<<<<<") - } - } + respDump, _ := httputil.DumpResponse(resp, true) + s.log.V(2).Info("", "responseDump", string(respDump)) payload, err = ioutil.ReadAll(resp.Body) if err != nil { @@ -152,16 +143,8 @@ func (s *SupermicroX) post(endpoint string, urlValues *url.Values, form []byte, } } - if log.GetLevel() == log.TraceLevel { - fmt.Println(fmt.Sprintf("https://%s/cgi/%s", s.ip, endpoint)) - dump, err := httputil.DumpRequestOut(req, true) - if err == nil { - log.Println("[Request]") - log.Println(">>>>>>>>>>>>>>>") - log.Printf("%s\n\n", dump) - log.Println(">>>>>>>>>>>>>>>") - } - } + reqDump, _ := httputil.DumpRequestOut(req, true) + s.log.V(2).Info("", "url", fmt.Sprintf("https://%s/cgi/%s", s.ip, endpoint), "requestDump", string(reqDump)) resp, err := s.httpClient.Do(req) if err != nil { @@ -169,23 +152,14 @@ func (s *SupermicroX) post(endpoint string, urlValues *url.Values, form []byte, } defer resp.Body.Close() - if log.GetLevel() == log.TraceLevel { - dump, err := httputil.DumpResponse(resp, true) - if err == nil { - log.Println("[Response]") - log.Println("<<<<<<<<<<<<<<") - log.Printf("%s\n\n", dump) - log.Println("<<<<<<<<<<<<<<") - } - } + respDump, _ := httputil.DumpResponse(resp, true) + s.log.V(2).Info("", "responseDump", string(respDump)) statusCode = resp.StatusCode _, err = ioutil.ReadAll(resp.Body) if err != nil { return statusCode, err } - //fmt.Printf("-->> %d\n", resp.StatusCode) - //fmt.Printf("%s\n", body) return statusCode, err } @@ -196,7 +170,7 @@ func (s *SupermicroX) query(requestType string) (ipmi *supermicro.IPMI, err erro } bmcURL := fmt.Sprintf("https://%s/cgi/ipmi.cgi", s.ip) - log.WithFields(log.Fields{"step": "bmc connection", "vendor": supermicro.VendorID, "ip": s.ip}).Debug("retrieving data from bmc") + s.log.V(1).Info("retrieving data from bmc", "step", "bmc connection", "vendor", string(supermicro.VendorID), "ip", s.ip) req, err := http.NewRequest("POST", bmcURL, bytes.NewBufferString(requestType)) if err != nil { @@ -212,16 +186,8 @@ func (s *SupermicroX) query(requestType string) (ipmi *supermicro.IPMI, err erro req.AddCookie(cookie) } } - if log.GetLevel() == log.TraceLevel { - log.Println(fmt.Sprintf("https://%s/cgi/%s", bmcURL, s.ip)) - dump, err := httputil.DumpRequestOut(req, true) - if err == nil { - log.Println("[Request]") - log.Println(">>>>>>>>>>>>>>>") - log.Printf("%s\n\n", dump) - log.Println(">>>>>>>>>>>>>>>") - } - } + reqDump, _ := httputil.DumpRequestOut(req, true) + s.log.V(2).Info("trace", "url", fmt.Sprintf("https://%s/cgi/%s", bmcURL, s.ip), "requestDump", string(reqDump)) resp, err := s.httpClient.Do(req) if err != nil { @@ -234,16 +200,8 @@ func (s *SupermicroX) query(requestType string) (ipmi *supermicro.IPMI, err erro return ipmi, err } - if log.GetLevel() == log.TraceLevel { - log.Println(fmt.Sprintf("https://%s/cgi/%s", bmcURL, s.ip)) - dump, err := httputil.DumpRequestOut(req, true) - if err == nil { - log.Println("[Request]") - log.Println(">>>>>>>>>>>>>>>") - log.Printf("%s\n\n", dump) - log.Println(">>>>>>>>>>>>>>>") - } - } + respDump, _ := httputil.DumpResponse(resp, true) + s.log.V(2).Info("", "responseDump", string(respDump)) ipmi = &supermicro.IPMI{} err = xml.Unmarshal(payload, ipmi) diff --git a/providers/supermicro/supermicrox/supermicrox_test.go b/providers/supermicro/supermicrox/supermicrox_test.go index 5acc0a5e..75b4b260 100644 --- a/providers/supermicro/supermicrox/supermicrox_test.go +++ b/providers/supermicro/supermicrox/supermicrox_test.go @@ -1,6 +1,7 @@ package supermicrox import ( + "context" "io/ioutil" "net/http" "net/http/httptest" @@ -8,6 +9,8 @@ import ( "testing" "github.com/bmc-toolbox/bmclib/devices" + "github.com/bombsimon/logrusr" + "github.com/sirupsen/logrus" "github.com/spf13/viper" ) @@ -104,8 +107,13 @@ var ( } ) +func init() { + if viper.GetBool("debug") != true { + viper.SetDefault("debug", true) + } +} + func setup() (r *SupermicroX, err error) { - viper.SetDefault("debug", false) mux = http.NewServeMux() server = httptest.NewTLSServer(mux) ip := strings.TrimPrefix(server.URL, "https://") @@ -125,7 +133,8 @@ func setup() (r *SupermicroX, err error) { w.Write([]byte("../cgi/url_redirect.cgi?url_name=mainmenu")) }) - r, err = New(ip, username, password) + testLog := logrus.New() + r, err = New(context.TODO(), ip, username, password, logrusr.NewLogger(testLog)) if err != nil { return r, err }