From c8e493c106a3112bb15b42a1a9196abcd553c8ad Mon Sep 17 00:00:00 2001 From: Rounak Adhikary Date: Fri, 29 Sep 2023 08:26:01 -0400 Subject: [PATCH] Chnaging to golangci-lint --- .github/workflows/terraform-ci.yml | 28 +- .golangci.yaml | 340 +++++++++++++++++- GNUmakefile | 3 + common/job_management.go | 4 +- main.go | 3 - redfish/common.go | 19 +- redfish/data_source_redfish_bios.go | 2 +- .../data_source_redfish_firmware_inventory.go | 1 - redfish/data_source_redfish_storage.go | 8 +- redfish/data_source_redfish_virtual_media.go | 4 +- redfish/provider.go | 5 +- redfish/resource_redfish_bios.go | 7 +- redfish/resource_redfish_power.go | 7 +- redfish/resource_redfish_simple_update.go | 4 +- redfish/resource_redfish_storage_volume.go | 28 +- redfish/resource_redfish_user_account.go | 14 +- redfish/resource_redfish_virtual_media.go | 31 +- 17 files changed, 411 insertions(+), 97 deletions(-) diff --git a/.github/workflows/terraform-ci.yml b/.github/workflows/terraform-ci.yml index 00e360af..26d6181e 100644 --- a/.github/workflows/terraform-ci.yml +++ b/.github/workflows/terraform-ci.yml @@ -32,6 +32,21 @@ env: # A workflow run is made up of one or more jobs that can run sequentially or in parallel jobs: + golangci: + name: Check Go formatting, linting, vetting using golangci-lint + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v3 + - uses: actions/setup-go@v4 + with: + go-version: ${{ env.GO_VERSION }} + - name: golangci-lint + uses: golangci/golangci-lint-action@v3 + with: + # Require: The version of golangci-lint to use. + # When `install-mode` is `binary` (default) the value can be v1.2 or v1.2.3 or `latest` to use the latest version. + # When `install-mode` is `goinstall` the value can be v1.2.3, `latest`, or the hash of a commit. + version: v1.54 code-check: name: Check Go formatting, linting, vetting runs-on: ubuntu-latest @@ -41,15 +56,7 @@ jobs: - name: Run the formatter, linter, and vetter uses: dell/common-github-actions/go-code-formatter-linter-vetter@main with: - directories: ./... - - uses: WillAbides/setup-go-faster@v1.7.0 - with: - go-version: ${{ env.GO_VERSION }} - - name: Run the static check - uses: dominikh/staticcheck-action@v1.2.0 - with: - version: "2022.1" - install-go: false + directories: ./redfish # TBD ./... sanitize: name: Check for forbidden words runs-on: ubuntu-latest @@ -59,7 +66,7 @@ jobs: - name: Run the forbidden words scan uses: dell/common-github-actions/code-sanitizer@main with: - args: /github/workspace + args: ./redfish # TBD ./ build: name: Build @@ -70,7 +77,6 @@ jobs: with: go-version: ${{ env.GO_VERSION }} - uses: actions/checkout@v3 - - run: go mod download - run: go build -v . go_security_scan: diff --git a/.golangci.yaml b/.golangci.yaml index a9980e2a..17173e0c 100644 --- a/.golangci.yaml +++ b/.golangci.yaml @@ -21,8 +21,8 @@ run: # Default value is empty list, # but default dirs are skipped independently of this option's value (see skip-dirs-use-default). # "/" will be replaced by current OS file path separator to properly work on Windows. - # skip-dirs: - # - gofish/dell + skip-dirs: + - gofish/dell # # Enables skipping of directories: # # - vendor$, third_party$, testdata$, examples$, Godeps$, builtin$ # # Default: true @@ -66,24 +66,342 @@ linters-settings: # SA1019: d.GetOkExists is deprecated, ignoring now since we shall be moving to plugin framework soon checks: ["all", "-SA1019"] revive: + # Maximum number of open files at the same time. + # See https://github.com/mgechev/revive#command-line-flags + # Defaults to unlimited. + max-open-files: 2048 + # When set to false, ignores files with "GENERATED" header, similar to golint. + # See https://github.com/mgechev/revive#available-rules for details. + # Default: false + ignore-generated-header: true + # Sets the default severity. + # See https://github.com/mgechev/revive#configuration + # Default: warning + severity: error + # Enable all available rules. + # Default: false + # enable-all-rules: true + # Sets the default failure confidence. + # This means that linting errors with less than 0.8 confidence will be ignored. + # Default: 0.8 + # confidence: 0.1 rules: - - name: unused-parameter + # https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#add-constant + - name: add-constant severity: warning - disabled: true - - name: var-declaration + disabled: false + arguments: + - maxLitCount: "3" + allowStrs: '""' + allowInts: "0,1,2" + allowFloats: "0.0,0.,1.0,1.,2.0,2." + # https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#argument-limit + - name: argument-limit + severity: warning + disabled: false + arguments: [4] #TBD + # https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#atomic + - name: atomic + severity: warning + disabled: false + # https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#banned-characters + - name: banned-characters + severity: warning + disabled: false + arguments: ["Ω", "Σ", "σ", "7"] + # https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#bare-return + # - name: bare-return + # disabled: true + # https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#blank-imports + - name: blank-imports + severity: warning + disabled: false + # https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#bool-literal-in-expr + - name: bool-literal-in-expr + severity: warning + disabled: false + # https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#call-to-gc + # - name: call-to-gc + # severity: warning + # disabled: false + # https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#cognitive-complexity + - name: cognitive-complexity + severity: warning + disabled: false + arguments: [80] #TBD + # https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#comment-spacings + - name: comment-spacings + severity: warning + disabled: false + arguments: + - nosec + # https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#confusing-naming + - name: confusing-naming + severity: warning + disabled: false + # https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#confusing-results + - name: confusing-results + severity: warning + disabled: false + # https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#constant-logical-expr + - name: constant-logical-expr + severity: warning + disabled: false + # https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#context-as-argument + # - name: context-as-argument + # severity: warning + # disabled: false + # arguments: + # - allowTypesBefore: "*testing.T,*github.com/user/repo/testing.Harness" + # https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#context-keys-type + # - name: context-keys-type + # severity: warning + # disabled: false + # https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#cyclomatic + - name: cyclomatic + severity: warning + disabled: false + arguments: [20] # TBD + # https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#datarace + - name: datarace + severity: warning + disabled: false + # https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#deep-exit + - name: deep-exit + severity: warning + disabled: false + # https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#defer + - name: defer + severity: warning + disabled: false + arguments: + - ["call-chain", "loop"] + # https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#dot-imports + - name: dot-imports severity: warning - disabled: true + disabled: false + # https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#duplicated-imports + - name: duplicated-imports + severity: warning + disabled: false + # https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#early-return + - name: early-return + severity: warning + disabled: false + arguments: + - "preserveScope" + # https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#empty-block + - name: empty-block + severity: warning + disabled: false + # https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#empty-lines + - name: empty-lines + severity: warning + disabled: false + # https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#error-naming + - name: error-naming + severity: warning + disabled: false + # https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#error-return + - name: error-return + severity: warning + disabled: false + # https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#error-strings + - name: error-strings + severity: warning + disabled: false + # https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#errorf + - name: errorf + severity: warning + disabled: false + # https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#exported - name: exported + severity: warning + disabled: false + arguments: + - "checkPrivateReceivers" + - "sayRepetitiveInsteadOfStutters" + # https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#flag-parameter + - name: flag-parameter + severity: warning + disabled: false + # https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#function-result-limit + - name: function-result-limit + severity: warning + disabled: false + arguments: [4] + # https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#function-length + - name: function-length + severity: warning + disabled: false + arguments: [10, 0] + # https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#get-return + - name: get-return + severity: warning + disabled: false + # https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#identical-branches + - name: identical-branches + severity: warning + disabled: false + # https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#if-return + - name: if-return + severity: warning + disabled: false + # https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#increment-decrement + - name: increment-decrement + severity: warning + disabled: false + # https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#indent-error-flow + - name: indent-error-flow + severity: warning + disabled: false + # arguments: + # - "preserveScope" + # https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#imports-blacklist + - name: imports-blacklist + severity: warning + disabled: false + arguments: + - "crypto/md5" + - "crypto/sha1" + # https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#import-shadowing + - name: import-shadowing + severity: warning + disabled: false + # https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#line-length-limit + - name: line-length-limit + severity: warning + disabled: false + arguments: [100] #TBD 80 + # https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#modifies-parameter + - name: modifies-parameter + severity: warning + disabled: false + # https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#modifies-value-receiver + - name: modifies-value-receiver + severity: warning + disabled: false + # https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#nested-structs + - name: nested-structs + severity: warning + disabled: false + # https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#optimize-operands-order + - name: optimize-operands-order + severity: warning + disabled: false + # https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#package-comments + - name: package-comments + severity: warning + disabled: false + # https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#range + - name: range + severity: warning + disabled: false + # https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#range-val-in-closure + - name: range-val-in-closure + severity: warning + disabled: false + # https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#range-val-address + - name: range-val-address + severity: warning + disabled: false + # https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#receiver-naming + - name: receiver-naming + severity: warning + disabled: false + # https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#redefines-builtin-id + - name: redefines-builtin-id + severity: warning + disabled: false + # https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#string-of-int + - name: string-of-int + severity: warning + disabled: false + # https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#superfluous-else + - name: superfluous-else + severity: warning + disabled: false + arguments: + - "preserveScope" + # https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#time-equal + - name: time-equal + severity: warning + disabled: false + # https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#time-naming + - name: time-naming + severity: warning + disabled: false + # https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#var-naming + - name: var-naming + severity: warning + disabled: false + arguments: + - ["ID"] # AllowList + - ["VM"] # DenyList + - - upperCaseConst: true + # https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#var-declaration + - name: var-declaration + severity: warning + disabled: false + # https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#unconditional-recursion + - name: unconditional-recursion + severity: warning + disabled: false + # https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#unexported-naming + - name: unexported-naming + severity: warning + disabled: false + # https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#unexported-return + - name: unexported-return + severity: warning + disabled: false + # https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#unhandled-error + - name: unhandled-error + severity: warning + disabled: false + # arguments: + # - "fmt.Printf" + # - "myFunction" + # https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#unnecessary-stmt + - name: unnecessary-stmt + severity: warning + disabled: false + # https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#unreachable-code + - name: unreachable-code + severity: warning + disabled: false + # https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#unused-parameter + - name: unused-parameter + severity: warning + disabled: false + arguments: + - allowRegex: "^_" + # https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#unused-receiver + - name: unused-receiver + severity: warning + disabled: false + arguments: + - allowRegex: "^_" + # https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#useless-break + - name: useless-break + severity: warning + disabled: false + # https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#waitgroup-by-value + - name: waitgroup-by-value + severity: warning disabled: false # enable revive linter linters: enable: - revive + - gofmt + - gofumpt + - gosec issues: - exclude: - - SA1019 # SA1019 static check: -# include: -# - EXC0012 # EXC0012 revive: Annoying issue about not having a comment. The rare codebase has such comments -# - EXC0014 # EXC0014 revive: Annoying issue about not having a comment. The rare codebase has such comments \ No newline at end of file + exclude: + - SA1019 # SA1019 static check: + include: + - EXC0012 # EXC0012 revive: Annoying issue about not having a comment. The rare codebase has such comments + - EXC0014 # EXC0014 revive: Annoying issue about not having a comment. The rare codebase has such comments diff --git a/GNUmakefile b/GNUmakefile index 4272c891..5e68c5fb 100644 --- a/GNUmakefile +++ b/GNUmakefile @@ -27,6 +27,9 @@ fmtcheck: errcheck: @sh -c "'$(CURDIR)/scripts/errcheck.sh'" +check: + golangci-lint run --fix + lint: @echo "==> Checking source code against linters..." tfproviderlint ./redfish diff --git a/common/job_management.go b/common/job_management.go index b2417184..12228b3a 100644 --- a/common/job_management.go +++ b/common/job_management.go @@ -28,11 +28,11 @@ func WaitForJobToFinish(service *gofish.Service, jobURI string, timeBetweenAttem for { select { case <-attemptTick.C: - //For some reason iDRAC 4.40.00.0 from time to time gives the following error: iDRAC is not ready. The configuration values cannot be accessed. Please retry after a few minutes. + // For some reason iDRAC 4.40.00.0 from time to time gives the following error: iDRAC is not ready. The configuration values cannot be accessed. Please retry after a few minutes. job, err := redfish.GetTask(service.GetClient(), jobURI) if err == nil { log.Printf("[DEBUG] - Attempting one more time... Job state is %s\n", job.TaskState) - //Check if job has finished + // Check if job has finished switch status := job.TaskState; status { case redfish.CompletedTaskState: return nil diff --git a/main.go b/main.go index 7e360d26..e3640cd9 100644 --- a/main.go +++ b/main.go @@ -2,7 +2,6 @@ package main import ( "context" - "flag" "log" @@ -21,7 +20,6 @@ import ( //go:generate go run github.com/hashicorp/terraform-plugin-docs/cmd/tfplugindocs func main() { - var debugMode bool // Set this flag to true if you want the provider to run in debug mode. Leaving it as is will cause it to run @@ -44,5 +42,4 @@ func main() { } plugin.Serve(opts) - } diff --git a/redfish/common.go b/redfish/common.go index f03375bc..acfb3fd7 100644 --- a/redfish/common.go +++ b/redfish/common.go @@ -14,9 +14,7 @@ import ( // Based on an instance of Service from the gofish library, retrieve a concrete system on which we can take action func getSystemResource(service *gofish.Service) (*redfish.ComputerSystem, error) { - systems, err := service.Systems() - if err != nil { return nil, err } @@ -31,7 +29,7 @@ func getSystemResource(service *gofish.Service) (*redfish.ComputerSystem, error) // See https://github.com/stmcginnis/gofish for details. This function returns a Service struct which can then be // used to make any required API calls. func NewConfig(provider *schema.ResourceData, resource *schema.ResourceData) (*gofish.Service, error) { - //Get redfish connection details from resource block + // Get redfish connection details from resource block var providerUser, providerPassword string if v, ok := provider.GetOk("user"); ok { @@ -41,10 +39,10 @@ func NewConfig(provider *schema.ResourceData, resource *schema.ResourceData) (*g providerPassword = v.(string) } - resourceServerConfig := resource.Get("redfish_server").([]interface{}) //It must be just one element + resourceServerConfig := resource.Get("redfish_server").([]interface{}) // It must be just one element - //Overwrite parameters (just user and password for client connection) - //Get redfish username at resource level over provider level + // Overwrite parameters (just user and password for client connection) + // Get redfish username at resource level over provider level var redfishClientUser, redfishClientPass string if len(resourceServerConfig[0].(map[string]interface{})["user"].(string)) > 0 { redfishClientUser = resourceServerConfig[0].(map[string]interface{})["user"].(string) @@ -53,7 +51,7 @@ func NewConfig(provider *schema.ResourceData, resource *schema.ResourceData) (*g redfishClientUser = providerUser log.Println("Using redfish user from provider") } - //Get redfish password at resource level over provider level + // Get redfish password at resource level over provider level if len(resourceServerConfig[0].(map[string]interface{})["password"].(string)) > 0 { redfishClientPass = resourceServerConfig[0].(map[string]interface{})["password"].(string) log.Println("Using redfish password from resource") @@ -61,7 +59,7 @@ func NewConfig(provider *schema.ResourceData, resource *schema.ResourceData) (*g redfishClientPass = providerPassword log.Println("Using redfish password from provider") } - //If for some reason none user or pass has been set at provider/resource level, trow an error + // If for some reason none user or pass has been set at provider/resource level, trow an error if len(redfishClientUser) == 0 || len(redfishClientPass) == 0 { return nil, fmt.Errorf("Error. Either Redfish client username or password has not been set. Please check your configuration") } @@ -89,7 +87,6 @@ func NewConfig(provider *schema.ResourceData, resource *schema.ResourceData) (*g // interact with the server. It will return a tuple consisting of the server's power state at time of return and // diagnostics func PowerOperation(resetType string, maximumWaitTime int, checkInterval int, service *gofish.Service) (redfish.PowerState, diag.Diagnostics) { - var diags diag.Diagnostics system, err := getSystemResource(service) @@ -104,9 +101,8 @@ func PowerOperation(resetType string, maximumWaitTime int, checkInterval int, se if system.PowerState == "Off" { log.Printf("[TRACE]: Server already powered off. No action required.") return redfish.OffPowerState, diags - } else { - targetPowerState = "Off" } + targetPowerState = "Off" } if resetType == "On" || resetType == "ForceOn" { @@ -168,7 +164,6 @@ func PowerOperation(resetType string, maximumWaitTime int, checkInterval int, se // TODO : Change to warning when updated to plugin framework log.Printf("[ERROR]: The system failed to update the server's power status within the maximum wait time specified!") return system.PowerState, diags - } // getRedfishServerEndpoint returns the endpoint from an schema. This might be useful diff --git a/redfish/data_source_redfish_bios.go b/redfish/data_source_redfish_bios.go index c0c179a7..a7711bde 100644 --- a/redfish/data_source_redfish_bios.go +++ b/redfish/data_source_redfish_bios.go @@ -3,6 +3,7 @@ package redfish import ( "context" "fmt" + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/stmcginnis/gofish" @@ -83,7 +84,6 @@ func readRedfishBios(service *gofish.Service, d *schema.ResourceData) diag.Diagn systems, err := service.Systems() if err != nil { return diag.Errorf("error fetching computer systems collection: %s", err) - } bios, err := systems[0].Bios() diff --git a/redfish/data_source_redfish_firmware_inventory.go b/redfish/data_source_redfish_firmware_inventory.go index 76e2b8d9..ea3a36d8 100644 --- a/redfish/data_source_redfish_firmware_inventory.go +++ b/redfish/data_source_redfish_firmware_inventory.go @@ -118,7 +118,6 @@ func getInventoryItems(fwInventories []*redfish.SoftwareInventory) []InventoryIt inventoryItemList := make([]InventoryItem, 0) for _, fwInv := range fwInventories { - if strings.HasPrefix(fwInv.Entity.ID, "Installed") { inv.entityID = fwInv.Entity.ID inv.entityName = fwInv.Entity.Name diff --git a/redfish/data_source_redfish_storage.go b/redfish/data_source_redfish_storage.go index 3cce2d88..322a081b 100644 --- a/redfish/data_source_redfish_storage.go +++ b/redfish/data_source_redfish_storage.go @@ -84,7 +84,7 @@ func dataSourceRedfishStorageRead(ctx context.Context, d *schema.ResourceData, m func readRedfishStorageCollection(service *gofish.Service, d *schema.ResourceData) diag.Diagnostics { var diags diag.Diagnostics - m := make([]map[string]interface{}, 0) //List where all storage controller will be held + m := make([]map[string]interface{}, 0) // List where all storage controller will be held systems, err := service.Systems() if err != nil { @@ -95,9 +95,9 @@ func readRedfishStorageCollection(service *gofish.Service, d *schema.ResourceDat return diag.Errorf("Error when retrieving storage: %s", err) } - var mToAdd map[string]interface{} //Map where each controller and its disks will be written + var mToAdd map[string]interface{} // Map where each controller and its disks will be written for _, s := range storage { - mToAdd = make(map[string]interface{}) //Create new mToAdd instace + mToAdd = make(map[string]interface{}) // Create new mToAdd instace mToAdd["storage_controller_id"] = s.ID drives, err := s.Drives() if err != nil { @@ -109,7 +109,7 @@ func readRedfishStorageCollection(service *gofish.Service, d *schema.ResourceDat driveNames = append(driveNames, d.Name) } mToAdd["drives"] = driveNames - m = append(m, mToAdd) //Insert controller into list + m = append(m, mToAdd) // Insert controller into list } err = d.Set("storage", m) diff --git a/redfish/data_source_redfish_virtual_media.go b/redfish/data_source_redfish_virtual_media.go index 148bf8ee..b5970587 100644 --- a/redfish/data_source_redfish_virtual_media.go +++ b/redfish/data_source_redfish_virtual_media.go @@ -83,13 +83,13 @@ func dataSourceRedfishVirtualMediaRead(ctx context.Context, d *schema.ResourceDa func readRedfishVirtualMediaCollection(service *gofish.Service, d *schema.ResourceData) diag.Diagnostics { var diags diag.Diagnostics - //Get manager.Since this provider is thought to work with individual servers, should be only one. + // Get manager.Since this provider is thought to work with individual servers, should be only one. manager, err := service.Managers() if err != nil { return diag.Errorf("Error retrieving the managers: %s", err) } - //Get virtual media + // Get virtual media virtualMedia, err := manager[0].VirtualMedia() if err != nil { return diag.Errorf("Error retrieving the virtual media instances: %s", err) diff --git a/redfish/provider.go b/redfish/provider.go index 012ee3b3..1c9e54ab 100644 --- a/redfish/provider.go +++ b/redfish/provider.go @@ -9,6 +9,7 @@ import ( // This is a global MutexKV for use within this plugin var redfishMutexKV = mutexkv.NewMutexKV() +// Provider returns the provider schema func Provider() *schema.Provider { provider := &schema.Provider{ Schema: map[string]*schema.Schema{ @@ -57,8 +58,8 @@ func Provider() *schema.Provider { return provider } -func providerConfigure(d *schema.ResourceData, terraformVersion string) (interface{}, error) { - /*Redfish token issued by iDRAC needs to be revoked when the provider is done. +func providerConfigure(d *schema.ResourceData, _ string) (interface{}, error) { + /* Redfish token issued by iDRAC needs to be revoked when the provider is done. At the moment, the terraform SDK (Provider.StopFunc) is not implemented. To follow up, please refer to this pull request: https://github.com/hashicorp/terraform-plugin-sdk/pull/377 */ diff --git a/redfish/resource_redfish_bios.go b/redfish/resource_redfish_bios.go index 5fbdea33..52ece522 100644 --- a/redfish/resource_redfish_bios.go +++ b/redfish/resource_redfish_bios.go @@ -117,6 +117,7 @@ func getResourceRedfishBiosSchema() map[string]*schema.Schema { } } +//revive:disable-next-line:unused-parameter TBD v is not needed func resourceRedfishBiosCustomizeDiff(_ context.Context, diff *schema.ResourceDiff, v interface{}) error { if diff.Id() == "" { return nil @@ -240,7 +241,6 @@ func updateRedfishBiosResource(service *gofish.Service, d *schema.ResourceData) } func readRedfishBiosResource(service *gofish.Service, d *schema.ResourceData) diag.Diagnostics { - log.Printf("[DEBUG] %s: Beginning read", d.Id()) var diags diag.Diagnostics @@ -265,7 +265,6 @@ func readRedfishBiosResource(service *gofish.Service, d *schema.ResourceData) di } func copyBiosAttributes(bios *redfish.Bios, attributes map[string]string) error { - // TODO: BIOS Attributes' values might be any of several types. // terraform-sdk currently does not support a map with different // value types. So we will convert int and float values to string. @@ -282,7 +281,6 @@ func copyBiosAttributes(bios *redfish.Bios, attributes map[string]string) error } func patchBiosAttributes(d *schema.ResourceData, bios *redfish.Bios, attributes map[string]interface{}) (biosTaskURI string, err error) { - payload := make(map[string]interface{}) payload["Attributes"] = attributes @@ -335,7 +333,6 @@ func patchBiosAttributes(d *schema.ResourceData, bios *redfish.Bios, attributes } func getBiosResource(service *gofish.Service) (*redfish.Bios, error) { - system, err := getSystemResource(service) if err != nil { log.Printf("[ERROR]: Failed to get system resource: %s", err) @@ -352,7 +349,6 @@ func getBiosResource(service *gofish.Service) (*redfish.Bios, error) { } func getBiosAttrsToPatch(d *schema.ResourceData, attributes map[string]string) (map[string]interface{}, error) { - attrs := make(map[string]interface{}) attrsToPatch := make(map[string]interface{}) @@ -379,7 +375,6 @@ func getBiosAttrsToPatch(d *schema.ResourceData, attributes map[string]string) ( attrsToPatch[key] = newVal } } - } else { err := fmt.Errorf("BIOS attribute %s not found", key) return attrsToPatch, err diff --git a/redfish/resource_redfish_power.go b/redfish/resource_redfish_power.go index 392541c8..ea112c2d 100644 --- a/redfish/resource_redfish_power.go +++ b/redfish/resource_redfish_power.go @@ -31,9 +31,10 @@ const ( // Custom function for calculating power state. Given some desired_power_action, we know what the expected power // state should be after the action is applied. Instead of marking the value of power_state as unknown during // PlanResourceChange, we can calculate exactly what the end power_state should be. +// +//revive:disable-next-line:unused-parameter TBD funcs is not needed func CheckPowerDiff(funcs ...schema.CustomizeDiffFunc) schema.CustomizeDiffFunc { return func(ctx context.Context, d *schema.ResourceDiff, meta interface{}) error { - var err error resetType, ok := d.GetOk("desired_power_action") @@ -128,7 +129,6 @@ func getResourceRedfishPowerSchema() map[string]*schema.Schema { } func resourceRedfishPowerRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - log.Printf("[DEBUG] %s: Beginning read", d.Id()) var diags diag.Diagnostics @@ -162,7 +162,6 @@ func resourceRedfishPowerRead(ctx context.Context, d *schema.ResourceData, m int } func resourceRedfishPowerUpdate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - var diags diag.Diagnostics // Lock the mutex to avoid race conditions with other resources @@ -178,7 +177,6 @@ func resourceRedfishPowerUpdate(ctx context.Context, d *schema.ResourceData, m i // Takes the m interface and feeds it the user input data d. You can then reference it with X.GetOk("user") service, err := NewConfig(m.(*schema.ResourceData), d) - if err != nil { return diag.Errorf(err.Error()) } @@ -212,7 +210,6 @@ func resourceRedfishPowerUpdate(ctx context.Context, d *schema.ResourceData, m i } func resourceRedfishPowerDelete(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - var diags diag.Diagnostics d.SetId("") diff --git a/redfish/resource_redfish_simple_update.go b/redfish/resource_redfish_simple_update.go index 45dfe517..854543a6 100644 --- a/redfish/resource_redfish_simple_update.go +++ b/redfish/resource_redfish_simple_update.go @@ -204,7 +204,7 @@ func updateRedfishSimpleUpdate(ctx context.Context, service *gofish.Service, d * return diag.Errorf("error while retrieving UpdateService - %s", err) } - //Check if the transfer protocol is available in the redfish instance + // Check if the transfer protocol is available in the redfish instance err = checkTransferProtocol(transferProtocol, updateService) if err != nil { var availableTransferProtocols string @@ -359,8 +359,8 @@ func getFWfromInventory(softwareInventories []*redfish.SoftwareInventory, softwa } return nil, fmt.Errorf("couldn't find FW on Firmware inventory") } -func pullUpdate(service *gofish.Service, d *schema.ResourceData, resetType string) error { +func pullUpdate(service *gofish.Service, d *schema.ResourceData, resetType string) error { // Get update service from root updateService, err := service.UpdateService() if err != nil { diff --git a/redfish/resource_redfish_storage_volume.go b/redfish/resource_redfish_storage_volume.go index 0b753a68..5c6e913b 100644 --- a/redfish/resource_redfish_storage_volume.go +++ b/redfish/resource_redfish_storage_volume.go @@ -99,7 +99,8 @@ func getResourceRedfishStorageVolumeSchema() map[string]*schema.Schema { Optional: true, ValidateFunc: validation.StringInSlice([]string{ string(redfishcommon.ImmediateApplyTime), - string(redfishcommon.OnResetApplyTime)}, false), + string(redfishcommon.OnResetApplyTime), + }, false), Default: string(redfishcommon.ImmediateApplyTime), }, "reset_type": { @@ -267,7 +268,7 @@ func createRedfishStorageVolume(service *gofish.Service, d *schema.ResourceData) return diag.Errorf("Storage controller %s does not support settings_apply_time: %s", storageID, applyTime) } - //Get drives + // Get drives allStorageDrives, err := storage.Drives() if err != nil { return diag.Errorf("Error when getting the drives attached to controller - %s", err) @@ -296,7 +297,6 @@ func createRedfishStorageVolume(service *gofish.Service, d *schema.ResourceData) // Handle this scenario - TBD return diag.Errorf("there was an issue when restarting the server") } - } // Wait for the job to finish @@ -305,7 +305,7 @@ func createRedfishStorageVolume(service *gofish.Service, d *schema.ResourceData) return diag.Errorf("Error, job %s wasn't able to complete: %s", jobID, err) } - //Get storage volumes + // Get storage volumes volumes, err := storage.Volumes() if err != nil { return diag.Errorf("there was an issue when retrieving volumes - %s", err) @@ -319,13 +319,12 @@ func createRedfishStorageVolume(service *gofish.Service, d *schema.ResourceData) diags = readRedfishStorageVolume(service, d) return diags - } func readRedfishStorageVolume(service *gofish.Service, d *schema.ResourceData) diag.Diagnostics { var diags diag.Diagnostics - //Check if the volume exists + // Check if the volume exists _, err := redfish.GetVolume(service.GetClient(), d.Id()) if err != nil { e, ok := err.(*redfishcommon.Error) @@ -422,7 +421,6 @@ func updateRedfishStorageVolume(ctx context.Context, service *gofish.Service, d // Handle this scenario - TBD return diag.Errorf("there was an issue when restarting the server") } - } // Wait for the job to finish @@ -464,7 +462,7 @@ func deleteRedfishStorageVolume(service *gofish.Service, d *schema.ResourceData) } } - //WAIT FOR VOLUME TO DELETE + // WAIT FOR VOLUME TO DELETE err = common.WaitForJobToFinish(service, jobID, intervalStorageVolumeJobCheckTime, volumeJobTimeout.(int)) if err != nil { return diag.Errorf("Error, timeout reached when waiting for job %s to finish. %s", jobID, err) @@ -483,7 +481,7 @@ func getStorageController(storageControllers []*redfish.Storage, diskControllerI } func deleteVolume(service *gofish.Service, volumeURI string) (jobID string, err error) { - //TODO - Check if we can delete immediately or if we need to schedule a job + // TODO - Check if we can delete immediately or if we need to schedule a job res, err := service.GetClient().Delete(volumeURI) if err != nil { return "", fmt.Errorf("error while deleting the volume %s", volumeURI) @@ -517,6 +515,7 @@ func getDrives(drives []*redfish.Drive, driveNames []string) ([]*redfish.Drive, /* createVolume creates a virtualdisk on a disk controller by using the redfish API */ +//revive:disable:argument-limit func createVolume(service *gofish.Service, storageLink string, volumeType string, @@ -527,8 +526,9 @@ func createVolume(service *gofish.Service, writeCachePolicy string, diskCachePolicy string, drives []*redfish.Drive, - applyTime string) (jobID string, err error) { - + applyTime string, +) (jobID string, err error) { + //revive:enable:argument-limit newVolume := make(map[string]interface{}) newVolume["VolumeType"] = volumeType newVolume["DisplayName"] = volumeName @@ -569,14 +569,16 @@ func createVolume(service *gofish.Service, return jobID, nil } +//revive:disable:argument-limit func updateVolume(service *gofish.Service, storageLink string, readCachePolicy string, writeCachePolicy string, volumeName string, diskCachePolicy string, - applyTime string) (jobID string, err error) { - + applyTime string, +) (jobID string, err error) { + //revive:enable:argument-limit payload := make(map[string]interface{}) payload["ReadCachePolicy"] = readCachePolicy payload["WriteCachePolicy"] = writeCachePolicy diff --git a/redfish/resource_redfish_user_account.go b/redfish/resource_redfish_user_account.go index a6b66fee..e1d6e990 100644 --- a/redfish/resource_redfish_user_account.go +++ b/redfish/resource_redfish_user_account.go @@ -174,7 +174,7 @@ func createRedfishUserAccount(service *gofish.Service, d *schema.ResourceData) d payload := make(map[string]interface{}) for _, account := range accountList { - if len(account.UserName) == 0 && account.ID != "1" { //ID 1 is reserved + if len(account.UserName) == 0 && account.ID != "1" { // ID 1 is reserved payload["UserName"] = d.Get("username").(string) payload["Password"] = d.Get("password").(string) payload["Enabled"] = d.Get("enabled").(bool) @@ -185,21 +185,21 @@ func createRedfishUserAccount(service *gofish.Service, d *schema.ResourceData) d url, _ := filepath.Split(account.ODataID) account.ODataID = url + account.ID } - //Ideally a go routine for each server should be done + // Ideally a go routine for each server should be done res, err := service.GetClient().Patch(account.ODataID, payload) if err != nil { - return diag.Errorf("Error when contacting the redfish API %v", err) //This error might happen when a user was created outside terraform + return diag.Errorf("Error when contacting the redfish API %v", err) // This error might happen when a user was created outside terraform } if res.StatusCode != 200 { return diag.Errorf("There was an issue with the APIClient. HTTP error code %d", res.StatusCode) } - //Set ID to terraform state file + // Set ID to terraform state file d.SetId(account.ID) diags = readRedfishUserAccount(service, d) return diags } } - //No room for new users + // No room for new users return diag.Errorf("There are no room for new users") } @@ -215,7 +215,7 @@ func readRedfishUserAccount(service *gofish.Service, d *schema.ResourceData) dia if err != nil { return diag.Errorf("Error when retrieving accounts %v", err) } - if account == nil { //User doesn't exist. Needs to be recreated. + if account == nil { // User doesn't exist. Needs to be recreated. d.SetId("") return diags } @@ -341,7 +341,7 @@ func getAccount(accountList []*redfish.ManagerAccount, id string) (*redfish.Mana return account, nil } } - return nil, nil //This will be returned if there are no errors but the user does not exist + return nil, nil // This will be returned if there are no errors but the user does not exist } // To check if given username is equal to any existing username diff --git a/redfish/resource_redfish_virtual_media.go b/redfish/resource_redfish_virtual_media.go index 73d352aa..a7b3b32a 100644 --- a/redfish/resource_redfish_virtual_media.go +++ b/redfish/resource_redfish_virtual_media.go @@ -101,6 +101,7 @@ func getResourceRedfishVirtualMediaSchema() map[string]*schema.Schema { } } +//revive:disable-next-line:unused-parameter TBD ctx is not needed func resourceRedfishVirtualMediaCreate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { service, err := NewConfig(m.(*schema.ResourceData), d) if err != nil { @@ -143,7 +144,7 @@ func createRedfishVirtualMedia(service *gofish.Service, d *schema.ResourceData) redfishMutexKV.Lock(getRedfishServerEndpoint(d)) defer redfishMutexKV.Unlock(getRedfishServerEndpoint(d)) - //Get terraform schema data + // Get terraform schema data image := d.Get("image").(string) if !strings.HasSuffix(image, ".iso") && !strings.HasSuffix(image, ".img") { return diag.Errorf("Unable to Process the request because the value entered for the parameter Image is not supported by the implementation. Please provide an image with extension iso or img.") @@ -164,13 +165,13 @@ func createRedfishVirtualMedia(service *gofish.Service, d *schema.ResourceData) if v, ok := d.GetOkExists("inserted"); ok { inserted = v.(bool) } else { - inserted = true //If inserted is not set, set it to true + inserted = true // If inserted is not set, set it to true } var writeProtected bool if v, ok := d.GetOkExists("write_protected"); ok { writeProtected = v.(bool) } else { - writeProtected = true //If write_protected is not set, set it to true + writeProtected = true // If write_protected is not set, set it to true } virtualMediaConfig := redfish.VirtualMediaConfig{ @@ -181,7 +182,7 @@ func createRedfishVirtualMedia(service *gofish.Service, d *schema.ResourceData) WriteProtected: writeProtected, } - //Get Systems details + // Get Systems details systems, err := service.Systems() if err != nil { return diag.Errorf("Error when retrieving systems: %s", err) @@ -197,7 +198,7 @@ func createRedfishVirtualMedia(service *gofish.Service, d *schema.ResourceData) if len(virtualMediaCollection) != 0 { for index := range virtualMediaCollection { - //Get specific virtual media + // Get specific virtual media virtualMedia, err := getVirtualMedia(virtualMediaCollection[index].ID, virtualMediaCollection) if err != nil { return diag.Errorf("Virtual Media selected doesn't exist: %s", err) @@ -215,7 +216,7 @@ func createRedfishVirtualMedia(service *gofish.Service, d *schema.ResourceData) } } else { // This implementation is added to support iDRAC firmware version 5.x. As virtual media can only be accessed through Managers card on 5.x. - //Get OOB Manager card - managers[0] will be our oob card + // Get OOB Manager card - managers[0] will be our oob card managers, err := service.Managers() if err != nil { return diag.Errorf("Couldn't retrieve managers from redfish API: %s", err) @@ -257,15 +258,15 @@ func readRedfishVirtualMedia(service *gofish.Service, d *schema.ResourceData) di virtualMedia, err := redfish.GetVirtualMedia(service.GetClient(), d.Id()) if err != nil { - return diag.Errorf("Virtual Media doesn't exist: %s", err) //This error won't be triggered ever + return diag.Errorf("Virtual Media doesn't exist: %s", err) // This error won't be triggered ever } - if len(virtualMedia.Image) == 0 { //Nothing is mounted here + if len(virtualMedia.Image) == 0 { // Nothing is mounted here d.SetId("") return diags } - //Get terraform schema data + // Get terraform schema data image := d.Get("image").(string) var transferMethod string @@ -311,10 +312,10 @@ func updateRedfishVirtualMedia(ctx context.Context, service *gofish.Service, d * redfishMutexKV.Lock(getRedfishServerEndpoint(d)) defer redfishMutexKV.Unlock(getRedfishServerEndpoint(d)) - //Hot update os not possible. Unmount and mount needs to be done to update + // Hot update os not possible. Unmount and mount needs to be done to update virtualMedia, err := redfish.GetVirtualMedia(service.GetClient(), d.Id()) if err != nil { - return diag.Errorf("Virtual Media doesn't exist: %s", err) //This error won't be triggered ever + return diag.Errorf("Virtual Media doesn't exist: %s", err) // This error won't be triggered ever } err = virtualMedia.EjectMedia() @@ -322,7 +323,7 @@ func updateRedfishVirtualMedia(ctx context.Context, service *gofish.Service, d * return diag.Errorf("There was an error when ejecting media: %s", err) } - //Get terraform schema data + // Get terraform schema data image := d.Get("image").(string) if !strings.HasSuffix(image, ".iso") && !strings.HasSuffix(image, ".img") { return diag.Errorf("Unable to Process the request because the value entered for the parameter Image is not supported by the implementation. Please provide an image with extension iso or img.") @@ -343,13 +344,13 @@ func updateRedfishVirtualMedia(ctx context.Context, service *gofish.Service, d * if v, ok := d.GetOkExists("inserted"); ok { inserted = v.(bool) } else { - inserted = true //If inserted is not set, set it to true + inserted = true // If inserted is not set, set it to true } var writeProtected bool if v, ok := d.GetOkExists("write_protected"); ok { writeProtected = v.(bool) } else { - writeProtected = true //If write_protected is not set, set it to true + writeProtected = true // If write_protected is not set, set it to true } virtualMediaConfig := redfish.VirtualMediaConfig{ @@ -377,7 +378,7 @@ func deleteRedfishVirtualMedia(service *gofish.Service, d *schema.ResourceData) virtualMedia, err := redfish.GetVirtualMedia(service.GetClient(), d.Id()) if err != nil { - return diag.Errorf("Virtual Media doesn't exist: %s", err) //This error won't be triggered ever + return diag.Errorf("Virtual Media doesn't exist: %s", err) // This error won't be triggered ever } err = virtualMedia.EjectMedia()