From fa052b8d784abae422491be18f710d7154ce0a29 Mon Sep 17 00:00:00 2001 From: Sean McGinnis Date: Sat, 20 Mar 2021 07:45:41 -0500 Subject: [PATCH] Add golangci-lint linting This adds linting of the code using golangci-lint as well as a GitHub Action job to help enforce it. Signed-off-by: Sean McGinnis --- .github/workflows/check.yml | 19 ++- .golangci.yaml | 118 ++++++++++++++++++ Makefile | 5 +- client.go | 65 +++++----- client_test.go | 51 +++----- common/testclient.go | 80 +++--------- common/types.go | 8 +- examples/{change_login.go => change_login.md} | 6 + .../{query_chassis.go => query_chassis.md} | 6 + .../{query_sessions.go => query_sessions.md} | 7 ++ examples/{reboot.go => reboot.md} | 9 ++ redfish/accountservice.go | 16 +-- redfish/assembly.go | 6 +- redfish/assembly_test.go | 6 +- redfish/bios.go | 8 +- redfish/chassis.go | 6 +- redfish/chassis_test.go | 5 +- redfish/compositionservice.go | 6 +- redfish/computersystem.go | 11 +- redfish/computersystem_test.go | 6 +- redfish/drive.go | 8 +- redfish/drive_test.go | 4 +- redfish/endpoint.go | 6 +- redfish/ethernetinterface.go | 6 +- redfish/eventdestination.go | 20 +-- redfish/eventservice.go | 12 +- redfish/eventservice_test.go | 9 +- redfish/hostinterface.go | 6 +- redfish/hostinterface_test.go | 2 +- redfish/ipaddresses.go | 2 +- redfish/logservice.go | 8 +- redfish/logservice_test.go | 2 +- redfish/manager.go | 8 +- redfish/manager_test.go | 7 +- redfish/manageraccount.go | 7 +- redfish/memory.go | 6 +- redfish/memory_test.go | 4 +- redfish/messageregistry.go | 15 +-- redfish/messageregistry_test.go | 4 +- redfish/networkadapter.go | 2 +- redfish/networkdevicefunction.go | 8 +- redfish/networkdevicefunction_test.go | 2 +- redfish/networkport.go | 8 +- redfish/pciedevice.go | 8 +- redfish/pciedevice_test.go | 4 +- redfish/power.go | 10 +- redfish/processor.go | 16 +-- redfish/redundancy.go | 6 +- redfish/redundancy_test.go | 2 +- redfish/role.go | 6 +- redfish/secureboot.go | 6 +- redfish/secureboot_test.go | 2 +- redfish/session.go | 6 +- redfish/storage.go | 9 +- redfish/storage_test.go | 2 +- redfish/updateservice_test.go | 4 +- redfish/virtualmedia.go | 12 +- redfish/vlannetworkinterface.go | 6 +- redfish/vlannetworkinterface_test.go | 2 +- redfish/volume.go | 4 +- serviceroot.go | 6 +- swordfish/dataprotectionloscapabilities.go | 6 +- swordfish/datasecurityloscapabilities.go | 2 +- swordfish/datastorageloscapabilities.go | 6 +- swordfish/endpointgroup.go | 6 +- swordfish/endpointgroup_test.go | 2 +- swordfish/fileshare.go | 6 +- swordfish/filesystem.go | 10 +- swordfish/ioconnectivityloscapabilities.go | 6 +- swordfish/ioperformanceloscapabilities.go | 6 +- .../ioperformanceloscapabilities_test.go | 2 +- swordfish/spareresourceset.go | 6 +- swordfish/spareresourceset_test.go | 2 +- swordfish/storagegroup.go | 12 +- swordfish/storagepool.go | 8 +- swordfish/storagepool_test.go | 2 +- swordfish/storageservice.go | 2 - swordfish/volume.go | 35 +++--- 78 files changed, 485 insertions(+), 345 deletions(-) create mode 100644 .golangci.yaml rename examples/{change_login.go => change_login.md} (91%) rename examples/{query_chassis.go => query_chassis.md} (88%) rename examples/{query_sessions.go => query_sessions.md} (86%) rename examples/{reboot.go => reboot.md} (90%) diff --git a/.github/workflows/check.yml b/.github/workflows/check.yml index a6f24fdf..e637d24b 100644 --- a/.github/workflows/check.yml +++ b/.github/workflows/check.yml @@ -8,6 +8,7 @@ on: - main jobs: build: + name: Build runs-on: ubuntu-latest steps: @@ -30,12 +31,18 @@ jobs: - name: Run build run: go build . - # Vet and lint - - name: Run vet & lint - run: | - go vet . - golint . - # Run unit tests - name: Run tests run: make test + + lint: + name: Lint + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + + - name: Run golangci-lint + uses: golangci/golangci-lint-action@v2 + with: + version: v1.38.0 + args: --timeout=5m -v diff --git a/.golangci.yaml b/.golangci.yaml new file mode 100644 index 00000000..44a12962 --- /dev/null +++ b/.golangci.yaml @@ -0,0 +1,118 @@ +linters-settings: + dupl: + threshold: 100 + funlen: + lines: 100 + statements: 50 + goheader: + values: + const: + - LICENSE: BSD-3-Clause + template: |- + SPDX-License-Identifier: {{ LICENSE }} + goconst: + min-len: 2 + min-occurrences: 5 + gocritic: + enabled-tags: + - diagnostic + - experimental + - opinionated + - performance + - style + disabled-checks: + - deprecatedComment + - dupImport # https://github.com/go-critic/go-critic/issues/845 + - ifElseChain + - octalLiteral + - whyNoLint + - wrapperFunc + gocyclo: + min-complexity: 25 + goimports: + local-prefixes: github.com/stmcginnis + golint: + min-confidence: 0 + gomnd: + settings: + mnd: + checks: argument,case,condition,return + govet: + check-shadowing: true + misspell: + locale: US + nolintlint: + allow-leading-space: true # don't require machine-readable nolint directives (i.e. with no leading space) + allow-unused: false # report any unused nolint directives + require-explanation: false # don't require an explanation for nolint directives + require-specific: false # don't require nolint directives to be specific about which linter is being skipped + +linters: + disable-all: true + enable: + - bodyclose + - deadcode + - depguard + - dogsled + - dupl + - errcheck + - funlen + - goconst + - gocritic + - gocyclo + - goheader + - goimports + - golint + - gomnd + - goprintffuncname + - gosec + - gosimple + - govet + - ineffassign + - misspell + - nakedret + - noctx + - nolintlint + - rowserrcheck + - staticcheck + - structcheck + - stylecheck + - typecheck + - unconvert + - unparam + - unused + - varcheck + - whitespace + + # don't enable: + # - asciicheck + # - exhaustive + # - gochecknoinits + # - gochecknoglobals + # - gocognit + # - godot + # - godox + # - goerr113 + # - interfacer + # - lll + # - nestif + # - prealloc + # - testpackage + # - revive + # - scopelint + # - wsl + +issues: + exclude: + - 'declaration of "(err|ctx)" shadows declaration at' + - 'G402: TLS InsecureSkipVerify may be true' + - '`(F|f)ibre` is a misspelling' + - '`(C|c)ancell.*` is a misspelling' +run: + skip-dirs: + - examples + +# golangci.com configuration +# https://github.com/golangci/golangci/wiki/Configuration +service: + golangci-lint-version: 1.38.0 # use the fixed version to not introduce new linters unexpectedly diff --git a/Makefile b/Makefile index e8d03f65..cd36b9cb 100644 --- a/Makefile +++ b/Makefile @@ -4,7 +4,7 @@ PKGS := $(shell go list ./... | grep -v example | grep -v tools) -all: build test +all: lint build test test: go test -v $(PKGS) @@ -12,5 +12,8 @@ test: build: go build +lint: + golangci-lint run -v + clean: go clean diff --git a/client.go b/client.go index 52278682..3472cfcb 100644 --- a/client.go +++ b/client.go @@ -90,7 +90,7 @@ type ClientConfig struct { } // setupClientWithConfig setups the client using the client config -func setupClientWithConfig(ctx context.Context, config ClientConfig) (c *APIClient, err error) { +func setupClientWithConfig(ctx context.Context, config *ClientConfig) (c *APIClient, err error) { if !strings.HasPrefix(config.Endpoint, "http") { return c, fmt.Errorf("endpoint must starts with http or https") } @@ -154,46 +154,43 @@ func setupClientWithEndpoint(ctx context.Context, endpoint string) (c *APIClient } // setupClientAuth setups the authentication in the client using the client config -func (c *APIClient) setupClientAuth(config ClientConfig) error { +func (c *APIClient) setupClientAuth(config *ClientConfig) error { if config.Session != nil { c.auth = &redfish.AuthToken{ Session: config.Session.ID, Token: config.Session.Token, } - } else { - if config.Username != "" { - var auth *redfish.AuthToken - if config.BasicAuth { - auth = &redfish.AuthToken{ - Username: config.Username, - Password: config.Password, - BasicAuth: true, - } - } else { - var err error - auth, err = c.Service.CreateSession(config.Username, config.Password) - if err != nil { - return err - } + } else if config.Username != "" { + var auth *redfish.AuthToken + if config.BasicAuth { + auth = &redfish.AuthToken{ + Username: config.Username, + Password: config.Password, + BasicAuth: true, + } + } else { + var err error + auth, err = c.Service.CreateSession(config.Username, config.Password) + if err != nil { + return err } - - c.auth = auth } + + c.auth = auth } return nil } // Connect creates a new client connection to a Redfish service. -func Connect(config ClientConfig) (c *APIClient, err error) { - - client, err := setupClientWithConfig(context.Background(), config) +func Connect(config ClientConfig) (c *APIClient, err error) { // nolint:gocritic + client, err := setupClientWithConfig(context.Background(), &config) if err != nil { return c, err } // Authenticate with the service - err = client.setupClientAuth(config) + err = client.setupClientAuth(&config) if err != nil { return c, err } @@ -202,14 +199,14 @@ func Connect(config ClientConfig) (c *APIClient, err error) { } // ConnectContext is the same as Connect, but sets the ctx. -func ConnectContext(ctx context.Context, config ClientConfig) (c *APIClient, err error) { - client, err := setupClientWithConfig(ctx, config) +func ConnectContext(ctx context.Context, config ClientConfig) (c *APIClient, err error) { // nolint:gocritic + client, err := setupClientWithConfig(ctx, &config) if err != nil { return c, err } // Authenticate with the service - err = client.setupClientAuth(config) + err = client.setupClientAuth(&config) if err != nil { return c, err } @@ -243,7 +240,7 @@ func (c *APIClient) CloneWithSession() (*APIClient, error) { return nil, fmt.Errorf("client already has a session") } - newClient := APIClient(*c) + newClient := *c newClient.HTTPClient = c.HTTPClient service, err := ServiceRoot(&newClient) if err != nil { @@ -317,7 +314,7 @@ func (c *APIClient) Delete(url string) (*http.Response, error) { } // runRequest performs JSON REST calls -func (c *APIClient) runRequest(method string, url string, payload interface{}) (*http.Response, error) { +func (c *APIClient) runRequest(method, url string, payload interface{}) (*http.Response, error) { if url == "" { return nil, fmt.Errorf("unable to execute request, no target provided") } @@ -335,7 +332,7 @@ func (c *APIClient) runRequest(method string, url string, payload interface{}) ( } // runRequestWithMultipartPayload performs REST calls with a multipart payload -func (c *APIClient) runRequestWithMultipartPayload(method string, url string, payload map[string]io.Reader) (*http.Response, error) { +func (c *APIClient) runRequestWithMultipartPayload(method, url string, payload map[string]io.Reader) (*http.Response, error) { if url == "" { return nil, fmt.Errorf("unable to execute request, no target provided") } @@ -366,7 +363,7 @@ func (c *APIClient) runRequestWithMultipartPayload(method string, url string, pa } // runRawRequest actually performs the REST calls. -func (c *APIClient) runRawRequest(method string, url string, payloadBuffer io.ReadSeeker, contentType string) (*http.Response, error) { +func (c *APIClient) runRawRequest(method, url string, payloadBuffer io.ReadSeeker, contentType string) (*http.Response, error) { if url == "" { return nil, common.ConstructError(0, []byte("unable to execute request, no target provided")) } @@ -391,11 +388,9 @@ func (c *APIClient) runRawRequest(method string, url string, payloadBuffer io.Re if c.auth.Token != "" { req.Header.Set("X-Auth-Token", c.auth.Token) req.Header.Set("Cookie", fmt.Sprintf("sessionKey=%s", c.auth.Token)) - } else { - if c.auth.BasicAuth == true && c.auth.Username != "" && c.auth.Password != "" { - encodedAuth := base64.StdEncoding.EncodeToString([]byte(fmt.Sprintf("%v:%v", c.auth.Username, c.auth.Password))) - req.Header.Set("Authorization", fmt.Sprintf("Basic %v", encodedAuth)) - } + } else if c.auth.BasicAuth && c.auth.Username != "" && c.auth.Password != "" { + encodedAuth := base64.StdEncoding.EncodeToString([]byte(fmt.Sprintf("%v:%v", c.auth.Username, c.auth.Password))) + req.Header.Set("Authorization", fmt.Sprintf("Basic %v", encodedAuth)) } } req.Close = true diff --git a/client_test.go b/client_test.go index b20b0a20..c8c39d71 100644 --- a/client_test.go +++ b/client_test.go @@ -46,11 +46,10 @@ const ( nonErrorStructErrorStatus = "Internal Server Error" ) -// TestError400 tests the parsing of error reply. -func TestError400(t *testing.T) { +func testError(code int, t *testing.T) { ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.WriteHeader(400) - w.Write([]byte(expectErrorStatus)) + w.WriteHeader(code) + w.Write([]byte(expectErrorStatus)) // nolint })) defer ts.Close() @@ -60,10 +59,10 @@ func TestError400(t *testing.T) { } errStruct, ok := err.(*common.Error) if !ok { - t.Errorf("400 should return known error type: %v", err) + t.Errorf("%d should return known error type: %v", code, err) } - if errStruct.HTTPReturnedStatusCode != 400 { - t.Errorf("The error code is different from 400") + if errStruct.HTTPReturnedStatusCode != code { + t.Errorf("The error code is different from %d", code) } errBody, err := json.MarshalIndent(errStruct, " ", " ") if err != nil { @@ -74,39 +73,21 @@ func TestError400(t *testing.T) { } } +// TestError400 tests the parsing of error reply. +func TestError400(t *testing.T) { + testError(400, t) +} + // TestError404 tests the parsing of error reply. func TestError404(t *testing.T) { - ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.WriteHeader(404) - w.Write([]byte(expectErrorStatus)) - })) - defer ts.Close() - - _, err := Connect(ClientConfig{Endpoint: ts.URL, HTTPClient: ts.Client()}) - if err == nil { - t.Error("Update call should fail") - } - errStruct, ok := err.(*common.Error) - if !ok { - t.Errorf("404 should return known error type: %v", err) - } - if errStruct.HTTPReturnedStatusCode != 404 { - t.Errorf("The error code is different from 404") - } - errBody, err := json.MarshalIndent(errStruct, " ", " ") - if err != nil { - t.Errorf("Marshall error %v got: %s", errStruct, err) - } - if errMsg != string(errBody) { - t.Errorf("Expect:\n%s\nGot:\n%s", errMsg, string(errBody)) - } + testError(404, t) } // TestErrorOther tests failures that do not return an Error struct func TestErrorOther(t *testing.T) { ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(500) - w.Write([]byte(nonErrorStructErrorStatus)) + w.Write([]byte(nonErrorStructErrorStatus)) // nolint })) defer ts.Close() @@ -128,7 +109,6 @@ func TestErrorOther(t *testing.T) { // TestConnectContextTimeout func TestConnectContextTimeout(t *testing.T) { - // ctx will timeout very quickly ctx, cancel := context.WithTimeout( context.Background(), @@ -148,7 +128,6 @@ func TestConnectContextTimeout(t *testing.T) { // TestConnectContextCancel func TestConnectContextCancel(t *testing.T) { - // ctx will be cancelled ctx, cancel := context.WithCancel(context.Background()) cancel() @@ -166,7 +145,6 @@ func TestConnectContextCancel(t *testing.T) { // TestConnectDefaultContextTimeout func TestConnectDefaultContextTimeout(t *testing.T) { - // ctx will timeout very quickly ctx, cancel := context.WithTimeout( context.Background(), @@ -185,7 +163,6 @@ func TestConnectDefaultContextTimeout(t *testing.T) { // TestConnectDefaultContextCancel func TestConnectDefaultContextCancel(t *testing.T) { - // ctx will be cancelled ctx, cancel := context.WithCancel(context.Background()) cancel() @@ -203,7 +180,7 @@ func TestConnectDefaultContextCancel(t *testing.T) { func TestClientRunRawRequestNoURL(t *testing.T) { client := APIClient{} - _, err := client.runRawRequest("", "", nil, "") + _, err := client.runRawRequest("", "", nil, "") // nolint:bodyclose if err == nil { t.Error("Request without relative path should have failed") } diff --git a/common/testclient.go b/common/testclient.go index ca5601ac..dcf38ccb 100644 --- a/common/testclient.go +++ b/common/testclient.go @@ -47,7 +47,7 @@ func (c *TestClient) actionCount(action string) int { var actionCount int for _, call := range c.calls { if call.Action == action { - actionCount = actionCount + 1 + actionCount++ } } return actionCount @@ -105,7 +105,7 @@ func (c *TestClient) Reset() { } // recordCall is a helper to record any API calls made through this client -func (c *TestClient) recordCall(action string, url string, payload interface{}) { +func (c *TestClient) recordCall(action, url string, payload interface{}) { call := TestAPICall{ Action: action, URL: url, @@ -115,10 +115,9 @@ func (c *TestClient) recordCall(action string, url string, payload interface{}) c.calls = append(c.calls, call) } -// Get performs a GET request against the Redfish service. -func (c *TestClient) Get(url string) (*http.Response, error) { - c.recordCall(http.MethodGet, url, nil) - customReturnForAction := c.getCustomReturnForAction(http.MethodGet) +func (c *TestClient) performAction(action, url string, payload interface{}) (*http.Response, error) { + c.recordCall(action, url, payload) + customReturnForAction := c.getCustomReturnForAction(action) if customReturnForAction == nil { return nil, nil } @@ -134,78 +133,27 @@ func (c *TestClient) Get(url string) (*http.Response, error) { return resp, nil } +// Get performs a GET request against the Redfish service. +func (c *TestClient) Get(url string) (*http.Response, error) { + return c.performAction(http.MethodGet, url, nil) +} + // Post performs a Post request against the Redfish service. func (c *TestClient) Post(url string, payload interface{}) (*http.Response, error) { - c.recordCall(http.MethodPost, url, payload) - customReturnForAction := c.getCustomReturnForAction(http.MethodPost) - if customReturnForAction == nil { - return nil, nil - } - resp := customReturnForAction.(*http.Response) - if resp.StatusCode != 200 && resp.StatusCode != 201 && resp.StatusCode != 202 && resp.StatusCode != 204 { - payload, err := ioutil.ReadAll(resp.Body) - if err != nil { - return nil, err - } - defer resp.Body.Close() - return nil, ConstructError(resp.StatusCode, payload) - } - return resp, nil + return c.performAction(http.MethodPost, url, payload) } // Put performs a Put request against the Redfish service. func (c *TestClient) Put(url string, payload interface{}) (*http.Response, error) { - c.recordCall(http.MethodPut, url, payload) - customReturnForAction := c.getCustomReturnForAction(http.MethodPut) - if customReturnForAction == nil { - return nil, nil - } - resp := customReturnForAction.(*http.Response) - if resp.StatusCode != 200 && resp.StatusCode != 201 && resp.StatusCode != 202 && resp.StatusCode != 204 { - payload, err := ioutil.ReadAll(resp.Body) - if err != nil { - return nil, err - } - defer resp.Body.Close() - return nil, ConstructError(resp.StatusCode, payload) - } - return resp, nil + return c.performAction(http.MethodPut, url, payload) } // Patch performs a Patch request against the Redfish service. func (c *TestClient) Patch(url string, payload interface{}) (*http.Response, error) { - c.recordCall(http.MethodPatch, url, payload) - customReturnForAction := c.getCustomReturnForAction(http.MethodPatch) - if customReturnForAction == nil { - return nil, nil - } - resp := customReturnForAction.(*http.Response) - if resp.StatusCode != 200 && resp.StatusCode != 201 && resp.StatusCode != 202 && resp.StatusCode != 204 { - payload, err := ioutil.ReadAll(resp.Body) - if err != nil { - return nil, err - } - defer resp.Body.Close() - return nil, ConstructError(resp.StatusCode, payload) - } - return resp, nil + return c.performAction(http.MethodPatch, url, payload) } // Delete performs a Delete request against the Redfish service. func (c *TestClient) Delete(url string) (*http.Response, error) { - c.recordCall(http.MethodDelete, url, nil) - customReturnForAction := c.getCustomReturnForAction(http.MethodDelete) - if customReturnForAction == nil { - return nil, nil - } - resp := customReturnForAction.(*http.Response) - if resp.StatusCode != 200 && resp.StatusCode != 201 && resp.StatusCode != 202 && resp.StatusCode != 204 { - payload, err := ioutil.ReadAll(resp.Body) - if err != nil { - return nil, err - } - defer resp.Body.Close() - return nil, ConstructError(resp.StatusCode, payload) - } - return resp, nil + return c.performAction(http.MethodDelete, url, nil) } diff --git a/common/types.go b/common/types.go index 77107941..62f9b62b 100644 --- a/common/types.go +++ b/common/types.go @@ -42,9 +42,7 @@ func (e *Entity) SetClient(c Client) { } // Update commits changes to an entity. -func (e *Entity) Update(originalEntity reflect.Value, currentEntity reflect.Value, - allowedUpdates []string) error { - +func (e *Entity) Update(originalEntity, currentEntity reflect.Value, allowedUpdates []string) error { payload := make(map[string]interface{}) for i := 0; i < originalEntity.NumField(); i++ { @@ -93,7 +91,7 @@ func (e *Entity) Update(originalEntity reflect.Value, currentEntity reflect.Valu // If there are any allowed updates, try to send updates to the system and // return the result. if len(payload) > 0 { - _, err := e.Client.Patch(e.ODataID, payload) + _, err := e.Client.Patch(e.ODataID, payload) // nolint:bodyclose if err != nil { return err } @@ -756,6 +754,6 @@ type ErrExtendedInfo struct { MessageArgs []string // An optional string representing the severity of the error. Severity string - //An optional string describing recommended action(s) to take to resolve the error. + // An optional string describing recommended action(s) to take to resolve the error. Resolution string } diff --git a/examples/change_login.go b/examples/change_login.md similarity index 91% rename from examples/change_login.go rename to examples/change_login.md index b63eba93..04fc4ecd 100644 --- a/examples/change_login.go +++ b/examples/change_login.md @@ -1,3 +1,8 @@ +# Change Login + +This is an example snippet of changing the username and password of an account. + +```go // // SPDX-License-Identifier: BSD-3-Clause // @@ -49,3 +54,4 @@ func main() { } } } +``` diff --git a/examples/query_chassis.go b/examples/query_chassis.md similarity index 88% rename from examples/query_chassis.go rename to examples/query_chassis.md index ed1bdb68..737ea497 100644 --- a/examples/query_chassis.go +++ b/examples/query_chassis.md @@ -1,3 +1,8 @@ +# Query Chassis + +This is an example of querying the chassis information. + +```go // // SPDX-License-Identifier: BSD-3-Clause // @@ -36,3 +41,4 @@ func main() { fmt.Printf("Chassis: %#v\n\n", chass) } } +``` diff --git a/examples/query_sessions.go b/examples/query_sessions.md similarity index 86% rename from examples/query_sessions.go rename to examples/query_sessions.md index 3d65a102..f447dc63 100644 --- a/examples/query_sessions.go +++ b/examples/query_sessions.md @@ -1,3 +1,9 @@ +# Query Session + +This is an example of querying the current active session information from the +service. + +```go // // SPDX-License-Identifier: BSD-3-Clause // @@ -37,3 +43,4 @@ func main() { fmt.Printf("Sessions: %#v\n\n", session) } } +``` diff --git a/examples/reboot.go b/examples/reboot.md similarity index 90% rename from examples/reboot.go rename to examples/reboot.md index ee339c2c..5680a99f 100644 --- a/examples/reboot.go +++ b/examples/reboot.md @@ -1,3 +1,11 @@ +# Reboot + +This is an example of rebooting a system. + +```go +// +// SPDX-License-Identifier: BSD-3-Clause +// package main import ( @@ -49,3 +57,4 @@ func main() { } } } +``` diff --git a/redfish/accountservice.go b/redfish/accountservice.go index 06e2c135..264abdae 100644 --- a/redfish/accountservice.go +++ b/redfish/accountservice.go @@ -127,11 +127,11 @@ type ExternalAccountProvider struct { // certificates shall contain a link to a Resource // Collection of certificates of the CertificateCollection type that the // external account provider uses. - certificates string + // certificates string // ldapService shall contain any additional mapping // information needed to parse a generic LDAP service. This property // should only be present inside the LDAP property. - ldapService string + // ldapService string // PasswordSet shall contain `true` if a valid value was // provided for the Password property. Otherwise, the property shall // contain `false`. @@ -201,10 +201,10 @@ type AccountService struct { // Directory services as an external account provider, this entity shall // be populated by default. This entity shall not be present in the // AdditionalExternalAccountProviders Resource Collection. - activeDirectory string + // activeDirectory string // additionalExternalAccountProviders shall contain the // additional external account providers that this Account Service uses. - additionalExternalAccountProviders string + // additionalExternalAccountProviders string // AuthFailureLoggingThreshold shall contain the // threshold for when an authorization failure is logged. This value // represents a modulo function. The failure shall be logged every `n`th @@ -233,7 +233,7 @@ type AccountService struct { // type PrivilegeMapping that contains the privileges that are required // for a user context to complete a requested operation on a URI // associated with this Service. - privilegeMap string + // privilegeMap string // roles shall contain a link to a Resource Collection // of type RoleCollection. roles string @@ -287,11 +287,13 @@ func (accountservice *AccountService) UnmarshalJSON(b []byte) error { // Update commits updates to this object's properties to the running system. func (accountservice *AccountService) Update() error { - // Get a representation of the object's original state so we can find what // to update. original := new(AccountService) - original.UnmarshalJSON(accountservice.rawData) + err := original.UnmarshalJSON(accountservice.rawData) + if err != nil { + return err + } readWriteFields := []string{ "AccountLockoutCounterResetAfter", diff --git a/redfish/assembly.go b/redfish/assembly.go index 34727e87..b74d846b 100644 --- a/redfish/assembly.go +++ b/redfish/assembly.go @@ -53,11 +53,13 @@ func (assembly *Assembly) UnmarshalJSON(b []byte) error { // Update commits updates to this object's properties to the running system. func (assembly *Assembly) Update() error { - // Get a representation of the object's original state so we can find what // to update. original := new(Assembly) - original.UnmarshalJSON(assembly.rawData) + err := original.UnmarshalJSON(assembly.rawData) + if err != nil { + return err + } readWriteFields := []string{ "Assemblies", diff --git a/redfish/assembly_test.go b/redfish/assembly_test.go index 9cabcd26..0437c65f 100644 --- a/redfish/assembly_test.go +++ b/redfish/assembly_test.go @@ -10,6 +10,8 @@ import ( "testing" ) +const AssembyName = "Assembly One" + var assemblyBody = strings.NewReader( `{ "@odata.id": "/redfish/v1/Assembly/1", @@ -84,7 +86,7 @@ func TestAssembly(t *testing.T) { t.Errorf("Received invalid ID: %s", result.ID) } - if result.Name != "Assembly One" { + if result.Name != AssembyName { t.Errorf("Received invalid name: %s", result.Name) } @@ -111,7 +113,7 @@ func TestAssemblyData(t *testing.T) { t.Errorf("Received invalid model: %s", result.Model) } - if result.Name != "Assembly One" { + if result.Name != AssembyName { t.Errorf("Received invalid name: %s", result.Name) } diff --git a/redfish/bios.go b/redfish/bios.go index 08e2f758..5883ddcb 100644 --- a/redfish/bios.go +++ b/redfish/bios.go @@ -172,7 +172,7 @@ func ListReferencedBioss(c common.Client, link string) ([]*Bios, error) { } // ChangePassword shall change the selected BIOS password. -func (bios *Bios) ChangePassword(passwordName string, oldPassword string, newPassword string) error { +func (bios *Bios) ChangePassword(passwordName, oldPassword, newPassword string) error { if passwordName == "" { return fmt.Errorf("password name must be supplied") } @@ -223,13 +223,15 @@ func (bios *Bios) AllowedAttributeUpdateApplyTimes() []common.ApplyTime { // UpdateBiosAttributes is used to update attribute values. func (bios *Bios) UpdateBiosAttributes(attrs BiosAttributes) error { - payload := make(map[string]interface{}) // Get a representation of the object's original state so we can find what // to update. original := new(Bios) - original.UnmarshalJSON(bios.rawData) + err := original.UnmarshalJSON(bios.rawData) + if err != nil { + return err + } for key := range attrs { if original.Attributes[key] != attrs[key] { diff --git a/redfish/chassis.go b/redfish/chassis.go index 5a2be02c..53feeac0 100644 --- a/redfish/chassis.go +++ b/redfish/chassis.go @@ -279,11 +279,13 @@ func (chassis *Chassis) UnmarshalJSON(b []byte) error { // Update commits updates to this object's properties to the running system. func (chassis *Chassis) Update() error { - // Get a representation of the object's original state so we can find what // to update. original := new(Chassis) - original.UnmarshalJSON(chassis.rawData) + err := original.UnmarshalJSON(chassis.rawData) + if err != nil { + return err + } readWriteFields := []string{ "AssetTag", diff --git a/redfish/chassis_test.go b/redfish/chassis_test.go index 8150198d..3cb96ff3 100644 --- a/redfish/chassis_test.go +++ b/redfish/chassis_test.go @@ -12,6 +12,9 @@ import ( "github.com/stmcginnis/gofish/common" ) +const TestAssetTag = "TestAssetTag" +const TestChassisPath = "/redfish/v1/Chassis/Chassis-1" + var chassisBody = `{ "@odata.context": "/redfish/v1/$metadata#Chassis.Chassis", "@odata.id": "/redfish/v1/Chassis/Chassis-1", @@ -208,7 +211,7 @@ func TestChassisUpdate(t *testing.T) { testClient := &common.TestClient{} result.SetClient(testClient) - result.AssetTag = "TestAssetTag" + result.AssetTag = TestAssetTag err = result.Update() if err != nil { diff --git a/redfish/compositionservice.go b/redfish/compositionservice.go index 08ac08f6..dacb0976 100644 --- a/redfish/compositionservice.go +++ b/redfish/compositionservice.go @@ -68,11 +68,13 @@ func (compositionservice *CompositionService) UnmarshalJSON(b []byte) error { // Update commits updates to this object's properties to the running system. func (compositionservice *CompositionService) Update() error { - // Get a representation of the object's original state so we can find what // to update. original := new(CompositionService) - original.UnmarshalJSON(compositionservice.rawData) + err := original.UnmarshalJSON(compositionservice.rawData) + if err != nil { + return err + } readWriteFields := []string{ "AllowOverprovisioning", diff --git a/redfish/computersystem.go b/redfish/computersystem.go index 6e948dfb..c1a0e551 100644 --- a/redfish/computersystem.go +++ b/redfish/computersystem.go @@ -406,7 +406,7 @@ type ComputerSystem struct { // ComputerSystem. HostWatchdogTimer WatchdogTimer // hostedServices shall describe services supported by this computer system. - hostedServices string + // hostedServices string // HostingRoles shall be the hosting roles supported by this computer system. HostingRoles []string @@ -581,7 +581,10 @@ func (computersystem *ComputerSystem) Update() error { // Get a representation of the object's original state so we can find what // to update. cs := new(ComputerSystem) - cs.UnmarshalJSON(computersystem.rawData) + err := cs.UnmarshalJSON(computersystem.rawData) + if err != nil { + return err + } readWriteFields := []string{ "AssetTag", @@ -709,7 +712,7 @@ func (computersystem *ComputerSystem) SecureBoot() (*SecureBoot, error) { } // SetBoot set a boot object based on a payload request -func (computersystem *ComputerSystem) SetBoot(b Boot) error { +func (computersystem *ComputerSystem) SetBoot(b Boot) error { // nolint type temp struct { Boot Boot } @@ -762,7 +765,7 @@ func (computersystem *ComputerSystem) Reset(resetType ResetType) error { func (computersystem *ComputerSystem) SetDefaultBootOrder() error { // This action wasn't added until 1.5.0, make sure this is supported. if computersystem.setDefaultBootOrderTarget == "" { - return fmt.Errorf("SetDefaultBootOrder is not supported by this system") + return fmt.Errorf("SetDefaultBootOrder is not supported by this system") // nolint:golint } _, err := computersystem.Client.Post(computersystem.setDefaultBootOrderTarget, nil) diff --git a/redfish/computersystem_test.go b/redfish/computersystem_test.go index 48b59384..53d5f3e4 100644 --- a/redfish/computersystem_test.go +++ b/redfish/computersystem_test.go @@ -129,7 +129,7 @@ var computerSystemBody = `{ }` // TestComputerSystem tests the parsing of ComputerSystem objects. -func TestComputerSystem(t *testing.T) { +func TestComputerSystem(t *testing.T) { // nolint var result ComputerSystem err := json.NewDecoder(strings.NewReader(computerSystemBody)).Decode(&result) @@ -236,7 +236,7 @@ func TestComputerSystem(t *testing.T) { t.Errorf("Received invalid number of chassis: %d", len(result.chassis)) } - if result.chassis[0] != "/redfish/v1/Chassis/Chassis-1" { + if result.chassis[0] != TestChassisPath { t.Errorf("Received invalid chassis reference: %s", result.chassis[0]) } @@ -268,7 +268,7 @@ func TestComputerSystemUpdate(t *testing.T) { testClient := &common.TestClient{} result.SetClient(testClient) - result.AssetTag = "TestAssetTag" + result.AssetTag = TestAssetTag result.HostName = "TestHostName" result.IndicatorLED = common.BlinkingIndicatorLED err = result.Update() diff --git a/redfish/drive.go b/redfish/drive.go index b107359a..28c31ecc 100644 --- a/redfish/drive.go +++ b/redfish/drive.go @@ -227,7 +227,7 @@ type Drive struct { pcieFunctions []string // PCIeFunctionCount is the number of PCIeFunctions. PCIeFunctionCount int - storagePools []string + // storagePools []string StoragePoolsCount int // secureEraseTarget is the URL for SecureErase actions. secureEraseTarget string @@ -290,11 +290,13 @@ func (drive *Drive) UnmarshalJSON(b []byte) error { // Update commits updates to this object's properties to the running system. func (drive *Drive) Update() error { - // Get a representation of the object's original state so we can find what // to update. original := new(Drive) - original.UnmarshalJSON(drive.rawData) + err := original.UnmarshalJSON(drive.rawData) + if err != nil { + return err + } readWriteFields := []string{ "AssetTag", diff --git a/redfish/drive_test.go b/redfish/drive_test.go index 8b020889..ed3d6f68 100644 --- a/redfish/drive_test.go +++ b/redfish/drive_test.go @@ -134,7 +134,7 @@ func TestDrive(t *testing.T) { t.Error("Failure predicted should be false.") } - if result.chassis != "/redfish/v1/Chassis/Chassis-1" { + if result.chassis != TestChassisPath { t.Errorf("Invalid chassis link: %s", result.chassis) } @@ -155,7 +155,7 @@ func TestDriveUpdate(t *testing.T) { testClient := &common.TestClient{} result.SetClient(testClient) - result.AssetTag = "TestAssetTag" + result.AssetTag = TestAssetTag result.IndicatorLED = common.LitIndicatorLED result.StatusIndicator = HotspareStatusIndicator result.WriteCacheEnabled = false diff --git a/redfish/endpoint.go b/redfish/endpoint.go index 1ef2685a..cc5b84ea 100644 --- a/redfish/endpoint.go +++ b/redfish/endpoint.go @@ -79,7 +79,7 @@ type ConnectedEntity struct { // entityLink shall be a reference to an entity of the // type specified by the description of the value of the EntityType // property. - entityLink common.Link + // entityLink common.Link // EntityPciID shall be the PCI ID of the connected PCIe entity. EntityPciID PciID `json:"entityPciId"` // entityRole shall indicate if the specified entity is an initiator, @@ -150,13 +150,13 @@ type Endpoint struct { PortsCount int // addressPools shall contain an array of links to // resources of type AddressPool with which this endpoint is associated. - addressPools []string + // addressPools []string // AddressPoolsCount is the number of AddressPools. AddressPoolsCount int // connectedPorts shall contain an array of links to // resources of type Port that represent ports associated with this // endpoint. - connectedPorts []string + // connectedPorts []string // ConnectedPortCount is the number of ConnectedPorts. ConnectedPortsCount int } diff --git a/redfish/ethernetinterface.go b/redfish/ethernetinterface.go index dbd82eb1..709f5af3 100644 --- a/redfish/ethernetinterface.go +++ b/redfish/ethernetinterface.go @@ -251,11 +251,13 @@ func (ethernetinterface *EthernetInterface) UnmarshalJSON(b []byte) error { // Update commits updates to this object's properties to the running system. func (ethernetinterface *EthernetInterface) Update() error { - // Get a representation of the object's original state so we can find what // to update. original := new(EthernetInterface) - original.UnmarshalJSON(ethernetinterface.rawData) + err := original.UnmarshalJSON(ethernetinterface.rawData) + if err != nil { + return err + } readWriteFields := []string{ "AutoNeg", diff --git a/redfish/eventdestination.go b/redfish/eventdestination.go index 46f46c35..526963a7 100644 --- a/redfish/eventdestination.go +++ b/redfish/eventdestination.go @@ -164,7 +164,7 @@ type EventDestination struct { // sent to the subscriber. If this property is absent or the array is // empty, the service shall send metric reports originating from any // metric report definition to the subscriber. - metricReportDefinitions []string + // metricReportDefinitions []string // MetricReportDefinitions@odata.count is MetricReportDefinitionsCount int `json:"MetricReportDefinitions@odata.count"` // originResources shall specify an array of Resources, Resource Collections, @@ -175,7 +175,7 @@ type EventDestination struct { // If this property is absent or the array is empty, the service shall send // Events originating from any Resource, Resource Collection, or // Referenceable Member to the subscriber. - originResources []string + // originResources []string // OriginResourcesCount is the number of OriginResources. OriginResourcesCount int `json:"OriginResources@odata.count"` // Protocol is used to indicate that the event type shall adhere to that @@ -240,11 +240,13 @@ func (eventdestination *EventDestination) UnmarshalJSON(b []byte) error { // Update commits updates to this object's properties to the running system. func (eventdestination *EventDestination) Update() error { - // Get a representation of the object's original state so we can find what // to update. original := new(EventDestination) - original.UnmarshalJSON(eventdestination.rawData) + err := original.UnmarshalJSON(eventdestination.rawData) + if err != nil { + return err + } readWriteFields := []string{ "Context", @@ -260,7 +262,7 @@ func (eventdestination *EventDestination) Update() error { // GetEventDestination will get a EventDestination instance from the service. func GetEventDestination(c common.Client, uri string) (*EventDestination, error) { // validate uri - if len(strings.TrimSpace(uri)) == 0 { + if strings.TrimSpace(uri) == "" { return nil, fmt.Errorf("uri should not be empty") } @@ -298,12 +300,12 @@ func validateCreateEventDestinationParams( eventTypes []EventType, ) error { // validate uri - if len(strings.TrimSpace(uri)) == 0 { + if strings.TrimSpace(uri) == "" { return fmt.Errorf("uri should not be empty") } // validate destination - if len(strings.TrimSpace(destination)) == 0 { + if strings.TrimSpace(destination) == "" { return fmt.Errorf("empty destination is not valid") } @@ -347,7 +349,6 @@ func CreateEventDestination( context string, oem interface{}, ) (string, error) { - // validate input parameters err := validateCreateEventDestinationParams( uri, @@ -395,11 +396,10 @@ func CreateEventDestination( // DeleteEventDestination will delete a EventDestination. func DeleteEventDestination(c common.Client, uri string) (err error) { // validate uri - if len(strings.TrimSpace(uri)) == 0 { + if strings.TrimSpace(uri) == "" { return fmt.Errorf("uri should not be empty") } _, err = c.Delete(uri) - //defer resp.Body.Close() return err } diff --git a/redfish/eventservice.go b/redfish/eventservice.go index 30ab7c5a..fc3de0f8 100644 --- a/redfish/eventservice.go +++ b/redfish/eventservice.go @@ -174,7 +174,7 @@ type EventService struct { } // UnmarshalJSON unmarshals a EventService object from the raw JSON. -func (eventservice *EventService) UnmarshalJSON(b []byte) error { +func (eventservice *EventService) UnmarshalJSON(b []byte) error { // nolint:dupl type temp EventService type Actions struct { SubmitTestEvent struct { @@ -205,11 +205,13 @@ func (eventservice *EventService) UnmarshalJSON(b []byte) error { // Update commits updates to this object's properties to the running system. func (eventservice *EventService) Update() error { - // Get a representation of the object's original state so we can find what // to update. original := new(EventService) - original.UnmarshalJSON(eventservice.rawData) + err := original.UnmarshalJSON(eventservice.rawData) + if err != nil { + return err + } readWriteFields := []string{ "DeliveryRetryAttempts", @@ -267,7 +269,7 @@ func ListReferencedEventServices(c common.Client, link string) ([]*EventService, // GetEventSubscriptions gets all the subscriptions using the event service. func (eventservice *EventService) GetEventSubscriptions() ([]*EventDestination, error) { - if len(strings.TrimSpace(eventservice.subscriptions)) == 0 { + if strings.TrimSpace(eventservice.subscriptions) == "" { return nil, fmt.Errorf("empty subscription link in the event service") } @@ -299,7 +301,7 @@ func (eventservice *EventService) CreateEventSubscription( context string, oem interface{}, ) (string, error) { - if len(strings.TrimSpace(eventservice.subscriptions)) == 0 { + if strings.TrimSpace(eventservice.subscriptions) == "" { return "", fmt.Errorf("empty subscription link in the event service") } diff --git a/redfish/eventservice_test.go b/redfish/eventservice_test.go index 1a4422a2..b3297fdd 100644 --- a/redfish/eventservice_test.go +++ b/redfish/eventservice_test.go @@ -112,7 +112,6 @@ func TestEventService(t *testing.T) { t.Errorf("invalid event type: %s", et) } } - } // TestEventServiceUpdate tests the Update call. @@ -298,7 +297,7 @@ func TestEventServiceGetEventSubscription(t *testing.T) { ProtoMinor: 1, Body: ioutil.NopCloser(bytes.NewBufferString(eventDestinationBody)), ContentLength: int64(len(eventDestinationBody)), - Header: make(http.Header, 0), + Header: make(http.Header), }, }, }, @@ -336,7 +335,7 @@ func TestEventServiceGetEventSubscriptions(t *testing.T) { ProtoMinor: 1, Body: ioutil.NopCloser(bytes.NewBufferString(eventDestinationsBody)), ContentLength: int64(len(eventDestinationsBody)), - Header: make(http.Header, 0), + Header: make(http.Header), }, // defining the custom return for the second GET operation &http.Response{ @@ -347,7 +346,7 @@ func TestEventServiceGetEventSubscriptions(t *testing.T) { ProtoMinor: 1, Body: ioutil.NopCloser(bytes.NewBufferString(eventDestinationBody)), ContentLength: int64(len(eventDestinationBody)), - Header: make(http.Header, 0), + Header: make(http.Header), }, }, }, @@ -444,7 +443,7 @@ func TestEventServiceCreateEventSubscriptionWithoutOptionalParameters(t *testing // TestEventServiceCreateEventSubscriptionInputParametersValidation // tests the validation of input parameters for CreateEventSubscription. -func TestEventServiceCreateEventSubscriptionInputParametersValidation(t *testing.T) { +func TestEventServiceCreateEventSubscriptionInputParametersValidation(t *testing.T) { // nolint var result EventService err := json.NewDecoder(strings.NewReader(eventServiceBody)).Decode(&result) if err != nil { diff --git a/redfish/hostinterface.go b/redfish/hostinterface.go index de5c24d9..4d048bc9 100644 --- a/redfish/hostinterface.go +++ b/redfish/hostinterface.go @@ -157,11 +157,13 @@ func (hostinterface *HostInterface) UnmarshalJSON(b []byte) error { // Update commits updates to this object's properties to the running system. func (hostinterface *HostInterface) Update() error { - // Get a representation of the object's original state so we can find what // to update. original := new(HostInterface) - original.UnmarshalJSON(hostinterface.rawData) + err := original.UnmarshalJSON(hostinterface.rawData) + if err != nil { + return err + } readWriteFields := []string{ "AuthNoneRoleId", diff --git a/redfish/hostinterface_test.go b/redfish/hostinterface_test.go index 3d8e208a..e72b45f4 100644 --- a/redfish/hostinterface_test.go +++ b/redfish/hostinterface_test.go @@ -114,8 +114,8 @@ func TestHostInterfaceUpdate(t *testing.T) { // TODO: Need to handle converted names // result.AuthNoneRoleID = "role-test" - result.FirmwareAuthEnabled = true // result.FirmwareAuthRoleID = "role-1" + result.FirmwareAuthEnabled = true result.InterfaceEnabled = true result.KernelAuthEnabled = true err = result.Update() diff --git a/redfish/ipaddresses.go b/redfish/ipaddresses.go index 32169ad5..e4474843 100644 --- a/redfish/ipaddresses.go +++ b/redfish/ipaddresses.go @@ -93,7 +93,7 @@ type IPv6Address struct { // assigned on a network interface. type IPv6GatewayStaticAddress struct { // Address provides access to a static IPv6 address that is currently - //assigned on a network interface. + // assigned on a network interface. Address string // PrefixLength provides the IPv6 network prefix length in bits for this address. PrefixLength int8 diff --git a/redfish/logservice.go b/redfish/logservice.go index ab3ee0bb..06fe9818 100644 --- a/redfish/logservice.go +++ b/redfish/logservice.go @@ -89,7 +89,7 @@ type LogService struct { } // UnmarshalJSON unmarshals a LogService object from the raw JSON. -func (logservice *LogService) UnmarshalJSON(b []byte) error { +func (logservice *LogService) UnmarshalJSON(b []byte) error { // nolint:dupl type temp LogService type Actions struct { ClearLog struct { @@ -120,11 +120,13 @@ func (logservice *LogService) UnmarshalJSON(b []byte) error { // Update commits updates to this object's properties to the running system. func (logservice *LogService) Update() error { - // Get a representation of the object's original state so we can find what // to update. original := new(LogService) - original.UnmarshalJSON(logservice.rawData) + err := original.UnmarshalJSON(logservice.rawData) + if err != nil { + return err + } readWriteFields := []string{ "DateTime", diff --git a/redfish/logservice_test.go b/redfish/logservice_test.go index 1c1732e8..903deeb6 100644 --- a/redfish/logservice_test.go +++ b/redfish/logservice_test.go @@ -81,7 +81,7 @@ func TestLogService(t *testing.T) { } // TestLogServiceUpdate tests the Update call. -func TestLogServiceUpdate(t *testing.T) { +func TestLogServiceUpdate(t *testing.T) { // nolint:dupl var result LogService err := json.NewDecoder(strings.NewReader(logServiceBody)).Decode(&result) diff --git a/redfish/manager.go b/redfish/manager.go index e8929fe3..0207f535 100644 --- a/redfish/manager.go +++ b/redfish/manager.go @@ -196,7 +196,7 @@ type Manager struct { GraphicalConsole GraphicalConsole // hostInterfaces shall be a link to a collection of type // HostInterfaceCollection. - hostInterfaces string + // hostInterfaces string // logServices shall contain a reference to a collection of type // LogServiceCollection which are for the use of this manager. logServices string @@ -356,11 +356,13 @@ func (manager *Manager) UnmarshalJSON(b []byte) error { // Update commits updates to this object's properties to the running system. func (manager *Manager) Update() error { - // Get a representation of the object's original state so we can find what // to update. original := new(Manager) - original.UnmarshalJSON(manager.rawData) + err := original.UnmarshalJSON(manager.rawData) + if err != nil { + return err + } readWriteFields := []string{ "AutoDSTEnabled", diff --git a/redfish/manager_test.go b/redfish/manager_test.go index 99c12546..2f143e5b 100644 --- a/redfish/manager_test.go +++ b/redfish/manager_test.go @@ -6,10 +6,11 @@ package redfish import ( "encoding/json" - "github.com/stmcginnis/gofish/common" "reflect" "strings" "testing" + + "github.com/stmcginnis/gofish/common" ) var oemLinksBody = ` @@ -129,7 +130,7 @@ var managerBody = `{ }, "Oem": ` + oemLinksBody + -` }, + ` }, "Actions": { "#Manager.Reset": { "target": "/redfish/v1/Managers/BMC-1/Actions/Manager.Reset", @@ -141,7 +142,7 @@ var managerBody = `{ }, "Oem": ` + oemDataBody + -` }` + ` }` // TestManager tests the parsing of Manager objects. func TestManager(t *testing.T) { diff --git a/redfish/manageraccount.go b/redfish/manageraccount.go index f197d3f9..981bde27 100644 --- a/redfish/manageraccount.go +++ b/redfish/manageraccount.go @@ -90,7 +90,6 @@ type ManagerAccount struct { // UnmarshalJSON unmarshals a ManagerAccount object from the raw JSON. func (manageraccount *ManagerAccount) UnmarshalJSON(b []byte) error { - type temp ManagerAccount type AccountLinks struct { Role common.Link @@ -120,11 +119,13 @@ func (manageraccount *ManagerAccount) UnmarshalJSON(b []byte) error { // Update commits updates to this object's properties to the running system. func (manageraccount *ManagerAccount) Update() error { - // Get a representation of the object's original state so we can find what // to update. original := new(ManagerAccount) - original.UnmarshalJSON(manageraccount.rawData) + err := original.UnmarshalJSON(manageraccount.rawData) + if err != nil { + return err + } readWriteFields := []string{ "AccountTypes", diff --git a/redfish/memory.go b/redfish/memory.go index 2007499a..edb60c5e 100644 --- a/redfish/memory.go +++ b/redfish/memory.go @@ -366,11 +366,13 @@ func (memory *Memory) UnmarshalJSON(b []byte) error { // Update commits updates to this object's properties to the running system. func (memory *Memory) Update() error { - // Get a representation of the object's original state so we can find what // to update. original := new(Memory) - original.UnmarshalJSON(memory.rawData) + err := original.UnmarshalJSON(memory.rawData) + if err != nil { + return err + } readWriteFields := []string{ "SecurityState", diff --git a/redfish/memory_test.go b/redfish/memory_test.go index 327f2761..7d64652b 100644 --- a/redfish/memory_test.go +++ b/redfish/memory_test.go @@ -102,7 +102,7 @@ func TestMemory(t *testing.T) { t.Errorf("Received invalid name: %s", result.Name) } - if result.chassis != "/redfish/v1/Chassis/Chassis-1" { + if result.chassis != TestChassisPath { t.Errorf("Invalid chassis link: %s", result.chassis) } @@ -129,7 +129,7 @@ func TestMemory(t *testing.T) { } // TestMemoryUpdate tests the Update call. -func TestMemoryUpdate(t *testing.T) { +func TestMemoryUpdate(t *testing.T) { // nolint:dupl var result Memory err := json.NewDecoder(strings.NewReader(memoryBody)).Decode(&result) diff --git a/redfish/messageregistry.go b/redfish/messageregistry.go index ed300e92..20b62a16 100644 --- a/redfish/messageregistry.go +++ b/redfish/messageregistry.go @@ -12,6 +12,8 @@ import ( "github.com/stmcginnis/gofish/common" ) +const MessageIDSectionLength = 4 + // MessageRegistryMessage is a message contained in the message registry. type MessageRegistryMessage struct { // Description is a short description of how and when to use this message. @@ -122,7 +124,7 @@ func ListReferencedMessageRegistriesByLanguage( language string, ) ([]*MessageRegistry, error) { language = strings.TrimSpace(language) - if len(language) == 0 { + if language == "" { return nil, fmt.Errorf("received empty language") } @@ -165,12 +167,12 @@ func GetMessageRegistryByLanguage( language string, ) (*MessageRegistry, error) { registry = strings.TrimSpace(registry) - if len(registry) == 0 { + if registry == "" { return nil, fmt.Errorf("received empty registry") } language = strings.TrimSpace(language) - if len(language) == 0 { + if language == "" { return nil, fmt.Errorf("received empty language") } @@ -214,14 +216,13 @@ func GetMessageFromMessageRegistryByLanguage( messageID string, language string, ) (*MessageRegistryMessage, error) { - messageID = strings.TrimSpace(messageID) - if len(messageID) == 0 { + if messageID == "" { return nil, fmt.Errorf("received empty messageID") } language = strings.TrimSpace(language) - if len(language) == 0 { + if language == "" { return nil, fmt.Errorf("received empty language") } @@ -229,7 +230,7 @@ func GetMessageFromMessageRegistryByLanguage( messageIDSplitted := strings.Split(messageID, ".") // validate messageID - if len(messageIDSplitted) != 4 { + if len(messageIDSplitted) != MessageIDSectionLength { return nil, fmt.Errorf("received invalid messageID %s", messageID) } diff --git a/redfish/messageregistry_test.go b/redfish/messageregistry_test.go index cd149ca7..5698c83b 100644 --- a/redfish/messageregistry_test.go +++ b/redfish/messageregistry_test.go @@ -67,7 +67,7 @@ var messageRegistryBody = `{ }` // TestMessageRegistry tests the parsing of MessageRegistry objects. -func TestMessageRegistry(t *testing.T) { +func TestMessageRegistry(t *testing.T) { // nolint:funlen,gocyclo var result MessageRegistry err := json.NewDecoder(strings.NewReader(messageRegistryBody)).Decode(&result) @@ -233,6 +233,8 @@ func TestMessageRegistry(t *testing.T) { t.Errorf("Received invalid OemInfoN: %s for the messageKey: %s", v, messageKey) } } + default: + t.Error("Unexpected value format") } } default: diff --git a/redfish/networkadapter.go b/redfish/networkadapter.go index 84621392..c223f3e0 100644 --- a/redfish/networkadapter.go +++ b/redfish/networkadapter.go @@ -53,7 +53,7 @@ type ControllerCapabilities struct { // SRIOV shall contain Single-Root Input/Output Virtualization (SR-IOV) // capabilities. SRIOV struct { - //SRIOVVEPACapable shall be a boolean indicating whether this + // SRIOVVEPACapable shall be a boolean indicating whether this // controller supports Single Root Input/Output Virtualization // (SR-IOV) in Virtual Ethernet Port Aggregator (VEPA) mode. SRIOVVEPACapable bool diff --git a/redfish/networkdevicefunction.go b/redfish/networkdevicefunction.go index 7009a60e..7e6da4ac 100644 --- a/redfish/networkdevicefunction.go +++ b/redfish/networkdevicefunction.go @@ -238,7 +238,7 @@ type NetworkDeviceFunction struct { ODataType string `json:"@odata.type"` // AssignablePhysicalPorts shall be an array of physical port references // that this network device function may be assigned to. - assignablePhysicalPorts []string + // assignablePhysicalPorts []string // AssignablePhysicalPortsCount is the number of assignable physical ports. AssignablePhysicalPortsCount int `json:"AssignablePhysicalPorts@odata.count"` // BootMode shall be the boot mode configured for this network device @@ -328,11 +328,13 @@ func (networkdevicefunction *NetworkDeviceFunction) UnmarshalJSON(b []byte) erro // Update commits updates to this object's properties to the running system. func (networkdevicefunction *NetworkDeviceFunction) Update() error { - // Get a representation of the object's original state so we can find what // to update. original := new(NetworkDeviceFunction) - original.UnmarshalJSON(networkdevicefunction.rawData) + err := original.UnmarshalJSON(networkdevicefunction.rawData) + if err != nil { + return err + } readWriteFields := []string{ "BootMode", diff --git a/redfish/networkdevicefunction_test.go b/redfish/networkdevicefunction_test.go index 0f9a0b70..1be97954 100644 --- a/redfish/networkdevicefunction_test.go +++ b/redfish/networkdevicefunction_test.go @@ -118,7 +118,7 @@ func TestNetworkDeviceFunction(t *testing.T) { } // TestNetworkDeviceFunctionUpdate tests the Update call. -func TestNetworkDeviceFunctionUpdate(t *testing.T) { +func TestNetworkDeviceFunctionUpdate(t *testing.T) { // nolint:dupl var result NetworkDeviceFunction err := json.NewDecoder(strings.NewReader(networkDeviceFunctionBody)).Decode(&result) diff --git a/redfish/networkport.go b/redfish/networkport.go index 725fea4d..bcd7b35f 100644 --- a/redfish/networkport.go +++ b/redfish/networkport.go @@ -125,7 +125,7 @@ type NetworkPort struct { // ODataType is the odata type. ODataType string `json:"@odata.type"` // Actions shall contain the available actions for this resource. - actions string + // actions string // ActiveLinkTechnology shall be the // configured link technology of this port. ActiveLinkTechnology LinkNetworkTechnology @@ -225,11 +225,13 @@ func (networkport *NetworkPort) UnmarshalJSON(b []byte) error { // Update commits updates to this object's properties to the running system. func (networkport *NetworkPort) Update() error { - // Get a representation of the object's original state so we can find what // to update. original := new(NetworkPort) - original.UnmarshalJSON(networkport.rawData) + err := original.UnmarshalJSON(networkport.rawData) + if err != nil { + return err + } readWriteFields := []string{ "ActiveLinkTechnology", diff --git a/redfish/pciedevice.go b/redfish/pciedevice.go index f8412cdc..884db348 100644 --- a/redfish/pciedevice.go +++ b/redfish/pciedevice.go @@ -93,7 +93,7 @@ type PCIeDevice struct { } // UnmarshalJSON unmarshals a PCIeDevice object from the raw JSON. -func (pciedevice *PCIeDevice) UnmarshalJSON(b []byte) error { +func (pciedevice *PCIeDevice) UnmarshalJSON(b []byte) error { // nolint:dupl type temp PCIeDevice type links struct { Chassis common.Links @@ -129,11 +129,13 @@ func (pciedevice *PCIeDevice) UnmarshalJSON(b []byte) error { // Update commits updates to this object's properties to the running system. func (pciedevice *PCIeDevice) Update() error { - // Get a representation of the object's original state so we can find what // to update. original := new(PCIeDevice) - original.UnmarshalJSON(pciedevice.rawData) + err := original.UnmarshalJSON(pciedevice.rawData) + if err != nil { + return err + } readWriteFields := []string{ "AssetTag", diff --git a/redfish/pciedevice_test.go b/redfish/pciedevice_test.go index 4805b077..b5222cc0 100644 --- a/redfish/pciedevice_test.go +++ b/redfish/pciedevice_test.go @@ -87,7 +87,7 @@ func TestPCIeDevice(t *testing.T) { } // TestPCIeDeviceUpdate tests the Update call. -func TestPCIeDeviceUpdate(t *testing.T) { +func TestPCIeDeviceUpdate(t *testing.T) { // nolint:dupl var result PCIeDevice err := json.NewDecoder(strings.NewReader(pcieDeviceBody)).Decode(&result) @@ -98,7 +98,7 @@ func TestPCIeDeviceUpdate(t *testing.T) { testClient := &common.TestClient{} result.SetClient(testClient) - result.AssetTag = "TestAssetTag" + result.AssetTag = TestAssetTag err = result.Update() if err != nil { diff --git a/redfish/power.go b/redfish/power.go index 0597e770..2d0308aa 100644 --- a/redfish/power.go +++ b/redfish/power.go @@ -227,7 +227,7 @@ type PowerControl struct { } // UnmarshalJSON unmarshals a PowerControl object from the raw JSON. -func (powercontrol *PowerControl) UnmarshalJSON(b []byte) error { +func (powercontrol *PowerControl) UnmarshalJSON(b []byte) error { // nolint:dupl type temp PowerControl type t1 struct { temp @@ -413,11 +413,13 @@ func (powersupply *PowerSupply) UnmarshalJSON(b []byte) error { // Update commits updates to this object's properties to the running system. func (powersupply *PowerSupply) Update() error { - // Get a representation of the object's original state so we can find what // to update. original := new(PowerSupply) - original.UnmarshalJSON(powersupply.rawData) + err := original.UnmarshalJSON(powersupply.rawData) + if err != nil { + return err + } readWriteFields := []string{ "IndicatorLED", @@ -485,7 +487,7 @@ type Voltage struct { } // UnmarshalJSON unmarshals a Voltage object from the raw JSON. -func (voltage *Voltage) UnmarshalJSON(b []byte) error { +func (voltage *Voltage) UnmarshalJSON(b []byte) error { // nolint:dupl type temp Voltage type t1 struct { temp diff --git a/redfish/processor.go b/redfish/processor.go index 53ce3dd7..c2b22dec 100644 --- a/redfish/processor.go +++ b/redfish/processor.go @@ -45,10 +45,10 @@ type InstructionSet string const ( - // x86InstructionSet x86 32-bit. - x86InstructionSet InstructionSet = "x86" - // x86_64InstructionSet x86 64-bit. - x8664InstructionSet InstructionSet = "x86-64" + // X86InstructionSet x86 32-bit. + X86InstructionSet InstructionSet = "x86" + // X86_64InstructionSet x86 64-bit. + X8664InstructionSet InstructionSet = "x86-64" // IA64InstructionSet Intel IA-64. IA64InstructionSet InstructionSet = "IA-64" // ARMA32InstructionSet ARM 32-bit. @@ -70,8 +70,8 @@ type ProcessorArchitecture string const ( - // x86ProcessorArchitecture x86 or x86-64. - x86ProcessorArchitecture ProcessorArchitecture = "x86" + // X86ProcessorArchitecture x86 or x86-64. + X86ProcessorArchitecture ProcessorArchitecture = "x86" // IA64ProcessorArchitecture Intel Itanium. IA64ProcessorArchitecture ProcessorArchitecture = "IA-64" // ARMProcessorArchitecture ARM. @@ -228,7 +228,7 @@ type FpgaInterface struct { InterfaceType FpgaInterfaceType // pcie shall be an object the describes the PCI-e related information about // this FPGA interface. TODO: Get link to PCIeInterface. - pcie string + // pcie string } // FpgaReconfigurationSlot shall contain information about the FPGA @@ -238,7 +238,7 @@ type FpgaReconfigurationSlot struct { // resources provided by the code programmed into a reconfiguration slot and // shall reference a resource of type AccelerationFunction. // TODO: Get link to resource. - accelerationFunction string + // accelerationFunction string // ProgrammableFromHost shall indicate // whether the reconfiguration slot can be reprogrammed from the host // using system software. If set to false, system software shall not be diff --git a/redfish/redundancy.go b/redfish/redundancy.go index 182ae58c..6ec7ff96 100644 --- a/redfish/redundancy.go +++ b/redfish/redundancy.go @@ -94,11 +94,13 @@ func (redundancy *Redundancy) UnmarshalJSON(b []byte) error { // Update commits updates to this object's properties to the running system. func (redundancy *Redundancy) Update() error { - // Get a representation of the object's original state so we can find what // to update. original := new(Redundancy) - original.UnmarshalJSON(redundancy.rawData) + err := original.UnmarshalJSON(redundancy.rawData) + if err != nil { + return err + } readWriteFields := []string{ "Mode", diff --git a/redfish/redundancy_test.go b/redfish/redundancy_test.go index 5c1655cc..5134baf2 100644 --- a/redfish/redundancy_test.go +++ b/redfish/redundancy_test.go @@ -59,7 +59,7 @@ func TestRedundancy(t *testing.T) { } // TestRedundancyUpdate tests the Update call. -func TestRedundancyUpdate(t *testing.T) { +func TestRedundancyUpdate(t *testing.T) { // nolint:dupl var result Redundancy err := json.NewDecoder(strings.NewReader(redundancyBody)).Decode(&result) diff --git a/redfish/role.go b/redfish/role.go index a4014b74..4466687d 100644 --- a/redfish/role.go +++ b/redfish/role.go @@ -86,11 +86,13 @@ func (role *Role) UnmarshalJSON(b []byte) error { // Update commits updates to this object's properties to the running system. func (role *Role) Update() error { - // Get a representation of the object's original state so we can find what // to update. original := new(Role) - original.UnmarshalJSON(role.rawData) + err := original.UnmarshalJSON(role.rawData) + if err != nil { + return err + } readWriteFields := []string{ "AssignedPrivileges", diff --git a/redfish/secureboot.go b/redfish/secureboot.go index a8f4bcd1..0a69c379 100644 --- a/redfish/secureboot.go +++ b/redfish/secureboot.go @@ -108,11 +108,13 @@ func (secureboot *SecureBoot) UnmarshalJSON(b []byte) error { // Update commits updates to this object's properties to the running system. func (secureboot *SecureBoot) Update() error { - // Get a representation of the object's original state so we can find what // to update. original := new(SecureBoot) - original.UnmarshalJSON(secureboot.rawData) + err := original.UnmarshalJSON(secureboot.rawData) + if err != nil { + return err + } readWriteFields := []string{ "SecureBootEnable", diff --git a/redfish/secureboot_test.go b/redfish/secureboot_test.go index f7fb822c..f55b00a7 100644 --- a/redfish/secureboot_test.go +++ b/redfish/secureboot_test.go @@ -64,7 +64,7 @@ func TestSecureBoot(t *testing.T) { } // TestSecureBootUpdate tests the Update call. -func TestSecureBootUpdate(t *testing.T) { +func TestSecureBootUpdate(t *testing.T) { // nolint:dupl var result SecureBoot err := json.NewDecoder(strings.NewReader(secureBootBody)).Decode(&result) diff --git a/redfish/session.go b/redfish/session.go index 5f9073cf..0357eaf7 100644 --- a/redfish/session.go +++ b/redfish/session.go @@ -79,7 +79,7 @@ type authPayload struct { } // CreateSession creates a new session and returns the token and id -func CreateSession(c common.Client, uri string, username string, password string) (auth *AuthToken, err error) { +func CreateSession(c common.Client, uri, username, password string) (auth *AuthToken, err error) { a := &authPayload{ UserName: username, Password: password, @@ -103,8 +103,8 @@ func CreateSession(c common.Client, uri string, username string, password string } // DeleteSession deletes a session using the location as argument -func DeleteSession(c common.Client, url string) (err error) { - resp, err := c.Delete(url) +func DeleteSession(c common.Client, sessionURL string) (err error) { + resp, err := c.Delete(sessionURL) if err != nil { return err } diff --git a/redfish/storage.go b/redfish/storage.go index a9900fff..51201aea 100644 --- a/redfish/storage.go +++ b/redfish/storage.go @@ -190,7 +190,6 @@ func (storage *Storage) SetEncryptionKey(key string) error { // GetOperationApplyTimeValues returns the OperationApplyTime values applicable for this storage func (storage *Storage) GetOperationApplyTimeValues() ([]common.OperationApplyTime, error) { return AllowedVolumesUpdateApplyTimes(storage.Client, storage.volumes) - } // StorageController is used to represent a resource that represents a @@ -267,7 +266,7 @@ type StorageController struct { } // UnmarshalJSON unmarshals a StorageController object from the raw JSON. -func (storagecontroller *StorageController) UnmarshalJSON(b []byte) error { +func (storagecontroller *StorageController) UnmarshalJSON(b []byte) error { // nolint:dupl type temp StorageController type links struct { Endpoints common.Links @@ -303,11 +302,13 @@ func (storagecontroller *StorageController) UnmarshalJSON(b []byte) error { // Update commits updates to this object's properties to the running system. func (storagecontroller *StorageController) Update() error { - // Get a representation of the object's original state so we can find what // to update. original := new(StorageController) - original.UnmarshalJSON(storagecontroller.rawData) + err := original.UnmarshalJSON(storagecontroller.rawData) + if err != nil { + return err + } readWriteFields := []string{ "AssetTag", diff --git a/redfish/storage_test.go b/redfish/storage_test.go index ff5d23b1..364b1000 100644 --- a/redfish/storage_test.go +++ b/redfish/storage_test.go @@ -169,7 +169,7 @@ func TestStorageControllerUpdate(t *testing.T) { } scResult := result.StorageControllers[0] - scResult.AssetTag = "TestAssetTag" + scResult.AssetTag = TestAssetTag // TODO: This highlights an issue that child objects of an object do not // get their client set. Need to review objects like Storage that include diff --git a/redfish/updateservice_test.go b/redfish/updateservice_test.go index aa2fe7d0..aa14f965 100644 --- a/redfish/updateservice_test.go +++ b/redfish/updateservice_test.go @@ -95,9 +95,11 @@ func TestUpdateService(t *testing.T) { t.Errorf("Received invalid OemInfoN: %s", v) } } + default: + t.Error("Invalid Oem values") } } default: - t.Errorf("Received invalid Oem") + t.Error("Received invalid Oem") } } diff --git a/redfish/virtualmedia.go b/redfish/virtualmedia.go index a8f17efb..b9294f65 100644 --- a/redfish/virtualmedia.go +++ b/redfish/virtualmedia.go @@ -42,7 +42,7 @@ const ( DVDMediaType VirtualMediaType = "DVD" ) -// TransferMethod is how the data is transfered. +// TransferMethod is how the data is transferred. type TransferMethod string const ( @@ -172,11 +172,13 @@ func (virtualmedia *VirtualMedia) UnmarshalJSON(b []byte) error { // Update commits updates to this object's properties to the running system. func (virtualmedia *VirtualMedia) Update() error { - // Get a representation of the object's original state so we can find what // to update. original := new(VirtualMedia) - original.UnmarshalJSON(virtualmedia.rawData) + err := original.UnmarshalJSON(virtualmedia.rawData) + if err != nil { + return err + } readWriteFields := []string{ "Image", @@ -205,7 +207,7 @@ func (virtualmedia *VirtualMedia) EjectMedia() error { } // InsertMedia sends a request to insert virtual media. -func (virtualmedia *VirtualMedia) InsertMedia(image string, inserted bool, writeProtected bool) error { +func (virtualmedia *VirtualMedia) InsertMedia(image string, inserted, writeProtected bool) error { if !virtualmedia.SupportsMediaInsert { return errors.New("redfish service does not support VirtualMedia.InsertMedia calls") } @@ -237,7 +239,7 @@ type VirtualMediaConfig struct { } // InsertMediaConfig sends a request to insert virtual media using the VirtualMediaConfig struct -func (virtualmedia *VirtualMedia) InsertMediaConfig(config VirtualMediaConfig) error { +func (virtualmedia *VirtualMedia) InsertMediaConfig(config VirtualMediaConfig) error { //nolint if !virtualmedia.SupportsMediaInsert { return errors.New("redfish service does not support VirtualMedia.InsertMedia calls") } diff --git a/redfish/vlannetworkinterface.go b/redfish/vlannetworkinterface.go index 086be6d5..4ae863d8 100644 --- a/redfish/vlannetworkinterface.go +++ b/redfish/vlannetworkinterface.go @@ -61,11 +61,13 @@ func (vlannetworkinterface *VLanNetworkInterface) UnmarshalJSON(b []byte) error // Update commits updates to this object's properties to the running system. func (vlannetworkinterface *VLanNetworkInterface) Update() error { - // Get a representation of the object's original state so we can find what // to update. original := new(VLanNetworkInterface) - original.UnmarshalJSON(vlannetworkinterface.rawData) + err := original.UnmarshalJSON(vlannetworkinterface.rawData) + if err != nil { + return err + } readWriteFields := []string{ "VLANEnable", diff --git a/redfish/vlannetworkinterface_test.go b/redfish/vlannetworkinterface_test.go index 5ed508a7..ea34524e 100644 --- a/redfish/vlannetworkinterface_test.go +++ b/redfish/vlannetworkinterface_test.go @@ -50,7 +50,7 @@ func TestVlanNetworkInterface(t *testing.T) { } // TestVlanNetworkInterfaceUpdate tests the Update call. -func TestVlanNetworkInterfaceUpdate(t *testing.T) { +func TestVlanNetworkInterfaceUpdate(t *testing.T) { // nolint:dupl var result VLanNetworkInterface err := json.NewDecoder(strings.NewReader(vlanNetworkInterfaceBody)).Decode(&result) diff --git a/redfish/volume.go b/redfish/volume.go index c21466c3..506d4df2 100644 --- a/redfish/volume.go +++ b/redfish/volume.go @@ -291,8 +291,6 @@ func AllowedVolumesUpdateApplyTimes(c common.Client, link string) ([]common.Oper } var applyTimes []common.OperationApplyTime - for _, v := range temp.OperationApplyTimeSupport.SupportedValues { - applyTimes = append(applyTimes, v) - } + applyTimes = append(applyTimes, temp.OperationApplyTimeSupport.SupportedValues...) return applyTimes, nil } diff --git a/serviceroot.go b/serviceroot.go index fa39c078..35ed4341 100644 --- a/serviceroot.go +++ b/serviceroot.go @@ -251,7 +251,7 @@ func (serviceroot *Service) Tasks() ([]*redfish.Task, error) { } // CreateSession creates a new session and returns the token and id -func (serviceroot *Service) CreateSession(username string, password string) (*redfish.AuthToken, error) { +func (serviceroot *Service) CreateSession(username, password string) (*redfish.AuthToken, error) { return redfish.CreateSession(serviceroot.Client, serviceroot.sessions, username, password) } @@ -302,7 +302,7 @@ func (serviceroot *Service) MessageRegistriesByLanguage(language string) ([]*red // contain the Message Registry name and it major and minor versions, as defined // by the Redfish Specification, for example: "Alert.1.0.0". // language is the RFC5646-conformant language code for the message registry, for example: "en". -func (serviceroot *Service) MessageRegistryByLanguage(registry string, language string) (*redfish.MessageRegistry, error) { +func (serviceroot *Service) MessageRegistryByLanguage(registry, language string) (*redfish.MessageRegistry, error) { return redfish.GetMessageRegistryByLanguage(serviceroot.Client, serviceroot.registries, registry, language) } @@ -313,7 +313,7 @@ func (serviceroot *Service) MessageRegistryByLanguage(registry string, language // - The segment between the 2nd and 3rd period is the minor version: 0 // - The segment after the 3rd period is the Message Identifier in the Registry: LanDisconnect // language is the RFC5646-conformant language code for the message registry, for example: "en". -func (serviceroot *Service) MessageByLanguage(messageID string, language string) (*redfish.MessageRegistryMessage, error) { +func (serviceroot *Service) MessageByLanguage(messageID, language string) (*redfish.MessageRegistryMessage, error) { return redfish.GetMessageFromMessageRegistryByLanguage(serviceroot.Client, serviceroot.registries, messageID, language) } diff --git a/swordfish/dataprotectionloscapabilities.go b/swordfish/dataprotectionloscapabilities.go index 21b42855..c93696a7 100644 --- a/swordfish/dataprotectionloscapabilities.go +++ b/swordfish/dataprotectionloscapabilities.go @@ -151,11 +151,13 @@ func (dataprotectionloscapabilities *DataProtectionLoSCapabilities) UnmarshalJSO // Update commits updates to this object's properties to the running system. func (dataprotectionloscapabilities *DataProtectionLoSCapabilities) Update() error { - // Get a representation of the object's original state so we can find what // to update. original := new(DataProtectionLoSCapabilities) - original.UnmarshalJSON(dataprotectionloscapabilities.rawData) + err := original.UnmarshalJSON(dataprotectionloscapabilities.rawData) + if err != nil { + return err + } readWriteFields := []string{ "SupportedLinesOfService", diff --git a/swordfish/datasecurityloscapabilities.go b/swordfish/datasecurityloscapabilities.go index c46ebdab..7d1c7702 100644 --- a/swordfish/datasecurityloscapabilities.go +++ b/swordfish/datasecurityloscapabilities.go @@ -148,7 +148,7 @@ type DataSecurityLoSCapabilities struct { // types for users (or programs). SupportedUserAuthenticationTypes []AuthenticationType // rawData holds the original serialized JSON so we can compare updates. - rawData []byte + // rawData []byte } // // UnmarshalJSON unmarshals a DataSecurityLoSCapabilities object from the raw JSON. diff --git a/swordfish/datastorageloscapabilities.go b/swordfish/datastorageloscapabilities.go index 63fe6607..34447d4e 100644 --- a/swordfish/datastorageloscapabilities.go +++ b/swordfish/datastorageloscapabilities.go @@ -105,11 +105,13 @@ func (datastorageloscapabilities *DataStorageLoSCapabilities) UnmarshalJSON(b [] // Update commits updates to this object's properties to the running system. func (datastorageloscapabilities *DataStorageLoSCapabilities) Update() error { - // Get a representation of the object's original state so we can find what // to update. original := new(DataStorageLoSCapabilities) - original.UnmarshalJSON(datastorageloscapabilities.rawData) + err := original.UnmarshalJSON(datastorageloscapabilities.rawData) + if err != nil { + return err + } readWriteFields := []string{ "MaximumRecoverableCapacitySourceCount", diff --git a/swordfish/endpointgroup.go b/swordfish/endpointgroup.go index c110cbf0..bc55e340 100644 --- a/swordfish/endpointgroup.go +++ b/swordfish/endpointgroup.go @@ -106,11 +106,13 @@ func (endpointgroup *EndpointGroup) UnmarshalJSON(b []byte) error { // Update commits updates to this object's properties to the running system. func (endpointgroup *EndpointGroup) Update() error { - // Get a representation of the object's original state so we can find what // to update. original := new(EndpointGroup) - original.UnmarshalJSON(endpointgroup.rawData) + err := original.UnmarshalJSON(endpointgroup.rawData) + if err != nil { + return err + } readWriteFields := []string{ "AccessState", diff --git a/swordfish/endpointgroup_test.go b/swordfish/endpointgroup_test.go index 57a9bd23..9a2a1d8d 100644 --- a/swordfish/endpointgroup_test.go +++ b/swordfish/endpointgroup_test.go @@ -67,7 +67,7 @@ func TestEndpointGroup(t *testing.T) { } // TestEndpointGroupUpdate tests the Update call. -func TestEndpointGroupUpdate(t *testing.T) { +func TestEndpointGroupUpdate(t *testing.T) { // nolint:dupl var result EndpointGroup err := json.NewDecoder(strings.NewReader(endpointGroupBody)).Decode(&result) diff --git a/swordfish/fileshare.go b/swordfish/fileshare.go index 92eca877..836a70d8 100644 --- a/swordfish/fileshare.go +++ b/swordfish/fileshare.go @@ -135,11 +135,13 @@ func (fileshare *FileShare) UnmarshalJSON(b []byte) error { // Update commits updates to this object's properties to the running system. func (fileshare *FileShare) Update() error { - // Get a representation of the object's original state so we can find what // to update. original := new(FileShare) - original.UnmarshalJSON(fileshare.rawData) + err := original.UnmarshalJSON(fileshare.rawData) + if err != nil { + return err + } readWriteFields := []string{ "CASupported", diff --git a/swordfish/filesystem.go b/swordfish/filesystem.go index 8b105a76..3834f720 100644 --- a/swordfish/filesystem.go +++ b/swordfish/filesystem.go @@ -168,9 +168,9 @@ type FileSystem struct { // exportedShares shall be an array of exported file shares of this file // system. Each entry shall define an exported file share of this file // system. - exportedShares string //FileShareCollection + exportedShares string // FileShareCollection // importedShares shall be an array of imported file shares. - importedShares []string //ImportedShare + // importedShares []string // ImportedShare // ReplicaTargets shall reference the target replicas that // are sourced by this replica. replicaTargets []string @@ -230,11 +230,13 @@ func (filesystem *FileSystem) UnmarshalJSON(b []byte) error { // Update commits updates to this object's properties to the running system. func (filesystem *FileSystem) Update() error { - // Get a representation of the object's original state so we can find what // to update. original := new(FileSystem) - original.UnmarshalJSON(filesystem.rawData) + err := original.UnmarshalJSON(filesystem.rawData) + if err != nil { + return err + } readWriteFields := []string{ "AccessCapabilities", diff --git a/swordfish/ioconnectivityloscapabilities.go b/swordfish/ioconnectivityloscapabilities.go index 6daff621..a94783e7 100644 --- a/swordfish/ioconnectivityloscapabilities.go +++ b/swordfish/ioconnectivityloscapabilities.go @@ -66,11 +66,13 @@ func (ioconnectivityloscapabilities *IOConnectivityLoSCapabilities) UnmarshalJSO // Update commits updates to this object's properties to the running system. func (ioconnectivityloscapabilities *IOConnectivityLoSCapabilities) Update() error { - // Get a representation of the object's original state so we can find what // to update. original := new(IOConnectivityLoSCapabilities) - original.UnmarshalJSON(ioconnectivityloscapabilities.rawData) + err := original.UnmarshalJSON(ioconnectivityloscapabilities.rawData) + if err != nil { + return err + } readWriteFields := []string{ "MaxSupportedBytesPerSecond", diff --git a/swordfish/ioperformanceloscapabilities.go b/swordfish/ioperformanceloscapabilities.go index 8e48b154..dcc23a54 100644 --- a/swordfish/ioperformanceloscapabilities.go +++ b/swordfish/ioperformanceloscapabilities.go @@ -94,11 +94,13 @@ func (ioperformanceloscapabilities *IOPerformanceLoSCapabilities) UnmarshalJSON( // Update commits updates to this object's properties to the running system. func (ioperformanceloscapabilities *IOPerformanceLoSCapabilities) Update() error { - // Get a representation of the object's original state so we can find what // to update. original := new(IOPerformanceLoSCapabilities) - original.UnmarshalJSON(ioperformanceloscapabilities.rawData) + err := original.UnmarshalJSON(ioperformanceloscapabilities.rawData) + if err != nil { + return err + } readWriteFields := []string{ "IOLimitingIsSupported", diff --git a/swordfish/ioperformanceloscapabilities_test.go b/swordfish/ioperformanceloscapabilities_test.go index 95d6ac61..b23b1f3b 100644 --- a/swordfish/ioperformanceloscapabilities_test.go +++ b/swordfish/ioperformanceloscapabilities_test.go @@ -122,7 +122,7 @@ func TestIOPerformanceLoSCapabilities(t *testing.T) { } // TestIOPerformanceLoSCapabilitiesUpdate tests the Update call. -func TestIOPerformanceLoSCapabilitiesUpdate(t *testing.T) { +func TestIOPerformanceLoSCapabilitiesUpdate(t *testing.T) { // nolint:dupl var result IOPerformanceLoSCapabilities err := json.NewDecoder(strings.NewReader(ioPerformanceLoSCapabilitiesBody)).Decode(&result) diff --git a/swordfish/spareresourceset.go b/swordfish/spareresourceset.go index 11e63ed3..daca175f 100644 --- a/swordfish/spareresourceset.go +++ b/swordfish/spareresourceset.go @@ -85,11 +85,13 @@ func (spareresourceset *SpareResourceSet) UnmarshalJSON(b []byte) error { // Update commits updates to this object's properties to the running system. func (spareresourceset *SpareResourceSet) Update() error { - // Get a representation of the object's original state so we can find what // to update. original := new(SpareResourceSet) - original.UnmarshalJSON(spareresourceset.rawData) + err := original.UnmarshalJSON(spareresourceset.rawData) + if err != nil { + return err + } readWriteFields := []string{ "OnLine", diff --git a/swordfish/spareresourceset_test.go b/swordfish/spareresourceset_test.go index 7bc7555f..16791c79 100644 --- a/swordfish/spareresourceset_test.go +++ b/swordfish/spareresourceset_test.go @@ -106,7 +106,7 @@ func TestSpareResourceSet(t *testing.T) { } // TestSpareResourceSetUpdate tests the Update call. -func TestSpareResourceSetUpdate(t *testing.T) { +func TestSpareResourceSetUpdate(t *testing.T) { // nolint:dupl var result SpareResourceSet err := json.NewDecoder(strings.NewReader(spareResourceSetBody)).Decode(&result) diff --git a/swordfish/storagegroup.go b/swordfish/storagegroup.go index d3864703..5c038f49 100644 --- a/swordfish/storagegroup.go +++ b/swordfish/storagegroup.go @@ -96,7 +96,7 @@ type StorageGroup struct { ReplicaInfo ReplicaInfo // ReplicaTargets shall reference the target replicas that // are sourced by this replica. - replicaTargets []string + // replicaTargets []string // ReplicaTargetsCount is number of replica targets. ReplicaTargetsCount int `json:"ReplicaTargets@odata.count"` // serverEndpointGroups is used to make requests to the storage exposed @@ -104,7 +104,7 @@ type StorageGroup struct { // to the storage via any server-side endpoint. If empty, the // implementation shall not allow access to the storage via any server- // side endpoint. - serverEndpointGroups []string + // serverEndpointGroups []string // ServerEndpointGroupsCount is the number of server endpoints. ServerEndpointGroupsCount int `json:"ServerEndpointGroups@odata.count"` // Status is the status of this group. @@ -184,11 +184,13 @@ func (storagegroup *StorageGroup) UnmarshalJSON(b []byte) error { // Update commits updates to this object's properties to the running system. func (storagegroup *StorageGroup) Update() error { - // Get a representation of the object's original state so we can find what // to update. original := new(StorageGroup) - original.UnmarshalJSON(storagegroup.rawData) + err := original.UnmarshalJSON(storagegroup.rawData) + if err != nil { + return err + } readWriteFields := []string{ "AccessState", @@ -283,7 +285,7 @@ func (storagegroup *StorageGroup) ClassOfService() (*ClassOfService, error) { return GetClassOfService(storagegroup.Client, storagegroup.classOfService) } -//MappedVolume is an exposed volume mapping. +// MappedVolume is an exposed volume mapping. type MappedVolume struct { // LogicalUnitNumber is the value is a SCSI Logical Unit Number for the Volume. LogicalUnitNumber int diff --git a/swordfish/storagepool.go b/swordfish/storagepool.go index 191124e5..b2823efd 100644 --- a/swordfish/storagepool.go +++ b/swordfish/storagepool.go @@ -86,7 +86,7 @@ type StoragePool struct { // StoragePool is associated with and shall reference resources of type // Drive. This property shall only contain references to Drive entities // which are currently assigned as a dedicated spare and are able to support - //this StoragePool. + // this StoragePool. dedicatedSpareDrives []string // DedicatedSpareDrivesCount is the number of drives. DedicatedSpareDrivesCount int @@ -144,11 +144,13 @@ func (storagepool *StoragePool) UnmarshalJSON(b []byte) error { // Update commits updates to this object's properties to the running system. func (storagepool *StoragePool) Update() error { - // Get a representation of the object's original state so we can find what // to update. original := new(StoragePool) - original.UnmarshalJSON(storagepool.rawData) + err := original.UnmarshalJSON(storagepool.rawData) + if err != nil { + return err + } readWriteFields := []string{ "CapacitySources", diff --git a/swordfish/storagepool_test.go b/swordfish/storagepool_test.go index 38b5f167..dcfe3d6d 100644 --- a/swordfish/storagepool_test.go +++ b/swordfish/storagepool_test.go @@ -119,7 +119,7 @@ func TestStoragePool(t *testing.T) { } // TestStoragePoolUpdate tests the Update call. -func TestStoragePoolUpdate(t *testing.T) { +func TestStoragePoolUpdate(t *testing.T) { // nolint:dupl var result StoragePool err := json.NewDecoder(strings.NewReader(storagePoolBody)).Decode(&result) diff --git a/swordfish/storageservice.go b/swordfish/storageservice.go index 32327ad5..33198ccc 100644 --- a/swordfish/storageservice.go +++ b/swordfish/storageservice.go @@ -219,7 +219,6 @@ func (storageservice *StorageService) DataSecurityLoSCapabilities() (*DataSecuri return nil, nil } return GetDataSecurityLoSCapabilities(storageservice.Client, storageservice.dataSecurityLoSCapabilities) - } // DataStorageLoSCapabilities references the data storage capabilities of this service. @@ -228,7 +227,6 @@ func (storageservice *StorageService) DataStorageLoSCapabilities() (*DataStorage return nil, nil } return GetDataStorageLoSCapabilities(storageservice.Client, storageservice.dataStorageLoSCapabilities) - } // DefaultClassOfService references the default class of service for entities diff --git a/swordfish/volume.go b/swordfish/volume.go index 24416ea1..1b181802 100644 --- a/swordfish/volume.go +++ b/swordfish/volume.go @@ -274,7 +274,7 @@ type Volume struct { // EncryptionTypes is used by this Volume. EncryptionTypes []redfish.EncryptionTypes // IOStatistics shall represent IO statistics for this volume. - //IOStatistics IOStatistics + // IOStatistics IOStatistics // Identifiers shall contain a list of all known durable // names for the associated volume. Identifiers []common.Identifier @@ -330,7 +330,7 @@ type Volume struct { RemainingCapacityPercent int // ReplicaInfo shall describe the replica relationship // between this storage volume and a corresponding source volume. - //ReplicaInfo redfish.ReplicaInfo + // ReplicaInfo redfish.ReplicaInfo // ReplicaTargets shall reference the target replicas that // are sourced by this replica. ReplicaTargets []string @@ -514,11 +514,13 @@ func (volume *Volume) UnmarshalJSON(b []byte) error { // Update commits updates to this object's properties to the running system. func (volume *Volume) Update() error { - // Get a representation of the object's original state so we can find what // to update. original := new(Volume) - original.UnmarshalJSON(volume.rawData) + err := original.UnmarshalJSON(volume.rawData) + if err != nil { + return err + } readWriteFields := []string{ "AccessCapabilities", @@ -665,12 +667,10 @@ func (volume *Volume) StoragePools() ([]*StoragePool, error) { // AssignReplicaTarget is used to establish a replication relationship by // assigning an existing volume to serve as a target replica for an existing // source volume. -func (volume *Volume) AssignReplicaTarget( - replicaType ReplicaType, updateMode ReplicaUpdateMode, targetVolumeODataID string) error { - +func (volume *Volume) AssignReplicaTarget(replicaType ReplicaType, updateMode ReplicaUpdateMode, targetVolumeODataID string) error { // This action wasn't added until later revisions if volume.assignReplicaTargetTarget == "" { - return fmt.Errorf("AssignReplicaTarget action is not supported by this system") + return fmt.Errorf("AssignReplicaTarget action is not supported by this system") // nolint } // Define this action's parameters @@ -694,9 +694,8 @@ func (volume *Volume) AssignReplicaTarget( // CheckConsistency is used to force a check of the Volume's parity or redundant // data to ensure it matches calculated values. func (volume *Volume) CheckConsistency() error { - if volume.checkConsistencyTarget == "" { - return fmt.Errorf("CheckConsistency action is not supported by this system") + return fmt.Errorf("CheckConsistency action is not supported by this system") // nolint } _, err := volume.Client.Post(volume.checkConsistencyTarget, nil) @@ -705,7 +704,6 @@ func (volume *Volume) CheckConsistency() error { // Initialize is used to prepare the contents of the volume for use by the system. func (volume *Volume) Initialize(initType InitializeType) error { - if volume.initializeTarget == "" { return fmt.Errorf("initialize action is not supported by this system") } @@ -726,10 +724,9 @@ func (volume *Volume) Initialize(initType InitializeType) error { // source and target volume, remove the replication relationship, and optionally // delete the target volume. func (volume *Volume) RemoveReplicaRelationship(deleteTarget bool, targetVolumeODataID string) error { - // This action wasn't added until later revisions if volume.removeReplicaRelationshipTarget == "" { - return fmt.Errorf("RemoveReplicaRelationship action is not supported by this system") + return fmt.Errorf("RemoveReplicaRelationship action is not supported by this system") // nolint } // Define this action's parameters @@ -752,10 +749,9 @@ func (volume *Volume) RemoveReplicaRelationship(deleteTarget bool, targetVolumeO // source and target volume, without otherwise altering the replication // relationship. func (volume *Volume) ResumeReplication(targetVolumeODataID string) error { - // This action wasn't added until later revisions if volume.resumeReplicationTarget == "" { - return fmt.Errorf("ResumeReplication action is not supported by this system") + return fmt.Errorf("ResumeReplication action is not supported by this system") // nolint } // Define this action's parameters @@ -773,10 +769,9 @@ func (volume *Volume) ResumeReplication(targetVolumeODataID string) error { // ReverseReplicationRelationship is used to reverse the replication // relationship between a source and target volume. func (volume *Volume) ReverseReplicationRelationship(targetVolumeODataID string) error { - // This action wasn't added until later revisions if volume.reverseReplicationRelationshipTarget == "" { - return fmt.Errorf("ReverseReplicationRelationship action is not supported by this system") + return fmt.Errorf("ReverseReplicationRelationship action is not supported by this system") // nolint } // Define this action's parameters @@ -794,10 +789,9 @@ func (volume *Volume) ReverseReplicationRelationship(targetVolumeODataID string) // SplitReplication is used to split the replication relationship and suspend // data synchronization between a source and target volume. func (volume *Volume) SplitReplication(targetVolumeODataID string) error { - // This action wasn't added until later revisions if volume.splitReplicationTarget == "" { - return fmt.Errorf("SplitReplication action is not supported by this system") + return fmt.Errorf("SplitReplication action is not supported by this system") // nolint } // Define this action's parameters @@ -816,10 +810,9 @@ func (volume *Volume) SplitReplication(targetVolumeODataID string) error { // source and target volume, without otherwise altering the replication // relationship. func (volume *Volume) SuspendReplication(targetVolumeODataID string) error { - // This action wasn't added until later revisions if volume.suspendReplicationTarget == "" { - return fmt.Errorf("SuspendReplication action is not supported by this system") + return fmt.Errorf("SuspendReplication action is not supported by this system") // nolint } // Define this action's parameters