From 7b306efb7cec787ade1e0807933b1bd3da942947 Mon Sep 17 00:00:00 2001 From: Kashif Khan Date: Thu, 18 Jan 2024 10:21:57 +0200 Subject: [PATCH] Enabled more golangci linters Signed-off-by: Kashif Khan --- .golangci.yaml | 254 +++++++++--------- Makefile | 5 +- .../metal3.io/v1alpha1/baremetalhost_types.go | 127 ++++----- .../v1alpha1/baremetalhost_types_test.go | 1 - .../v1alpha1/baremetalhost_validation.go | 12 +- .../v1alpha1/baremetalhost_webhook.go | 12 +- .../v1alpha1/bmceventsubscription_types.go | 2 +- .../bmceventsubscription_validation.go | 11 +- .../v1alpha1/bmceventsubscription_webhook.go | 8 +- .../v1alpha1/firmwareschema_types.go | 14 +- apis/metal3.io/v1alpha1/groupversion_info.go | 4 +- apis/metal3.io/v1alpha1/hardwaredata_types.go | 6 +- .../v1alpha1/hostfirmwarecomponents_types.go | 18 +- .../hostfirmwarecomponents_types_test.go | 2 +- .../v1alpha1/hostfirmwaresettings_types.go | 12 +- .../hostfirmwaresettings_types_test.go | 1 - .../v1alpha1/preprovisioningimage_types.go | 12 +- apis/metal3.io/v1alpha1/profile/profile.go | 18 +- cmd/make-virt-host/main.go | 4 +- .../crds/bases/metal3.io_baremetalhosts.yaml | 14 +- .../crds/bases/metal3.io_firmwareschemas.yaml | 6 +- .../crds/bases/metal3.io_hardwaredata.yaml | 6 +- .../metal3.io_hostfirmwarecomponents.yaml | 6 +- .../bases/metal3.io_hostfirmwaresettings.yaml | 6 +- .../metal3.io_preprovisioningimages.yaml | 6 +- config/render/capm3.yaml | 38 +-- controllers/metal3.io/action_result.go | 2 +- .../metal3.io/baremetalhost_controller.go | 5 +- .../bmceventsubscription_controller.go | 7 +- controllers/metal3.io/host_config_data.go | 4 +- .../metal3.io/host_config_data_test.go | 9 +- pkg/hardwareutils/bmc/access.go | 8 +- pkg/hardwareutils/bmc/access_test.go | 2 +- pkg/hardwareutils/bmc/credentials.go | 2 +- pkg/hardwareutils/bmc/errors.go | 2 +- pkg/hardwareutils/bmc/ibmc.go | 19 +- pkg/hardwareutils/bmc/idrac.go | 24 +- pkg/hardwareutils/bmc/idrac_virtualmedia.go | 19 +- pkg/hardwareutils/bmc/ilo4.go | 18 +- pkg/hardwareutils/bmc/ilo5.go | 13 +- pkg/hardwareutils/bmc/ipmi.go | 4 +- pkg/hardwareutils/bmc/irmc.go | 19 +- pkg/hardwareutils/bmc/redfish.go | 30 +-- pkg/hardwareutils/bmc/redfish_virtualmedia.go | 6 +- pkg/provisioner/demo/demo.go | 72 +---- pkg/provisioner/fixture/fixture.go | 2 +- pkg/provisioner/ironic/clients/features.go | 4 +- pkg/provisioner/ironic/dependencies.go | 2 +- .../ironic/devicehints/devicehints.go | 4 +- pkg/provisioner/ironic/ironic.go | 5 +- pkg/provisioner/ironic/testserver/ironic.go | 53 ++-- pkg/provisioner/ironic/testserver/server.go | 43 ++- test/e2e/bmc.go | 4 +- test/e2e/common.go | 9 +- test/e2e/e2e_suite_test.go | 8 +- test/e2e/live_iso_test.go | 2 +- test/e2e/provisioning_and_annotation_test.go | 6 +- 57 files changed, 470 insertions(+), 542 deletions(-) diff --git a/.golangci.yaml b/.golangci.yaml index 19aaf51de6..b32ad74659 100644 --- a/.golangci.yaml +++ b/.golangci.yaml @@ -1,45 +1,45 @@ run: deadline: 5m skip-dirs: - - mock* + - mock* skip-files: - - "zz_generated.*\\.go$" - - ".*conversion.*\\.go$" + - "zz_generated.*\\.go$" + - ".*conversion.*\\.go$" linters: disable-all: true enable: - - asciicheck - - bodyclose - - dogsled - # - errcheck - # - errorlint - - exportloopref - # - goconst - # - gocritic - # - godot - # - gofmt - # - goimports - # - gosimple - # - govet - # - importas - # - gosec - # - ineffassign - # - misspell - # - nakedret - # - nilerr - # - noctx - # - nolintlint - # - prealloc - # - predeclared - # - revive - # - rowserrcheck - # - staticcheck - # - stylecheck - # - thelper - # - typecheck - # - unconvert - # - unused - # - whitespace + - asciicheck + - bodyclose + - dogsled + # - errcheck + # - errorlint + - exportloopref + - goconst + - gocritic + - godot + - gofmt + - goimports + - gosimple + - govet + - importas + - gosec + - ineffassign + - misspell + # - nakedret + # - nilerr + # - noctx + - nolintlint + - prealloc + - predeclared + - revive + - rowserrcheck + - staticcheck + - stylecheck + - thelper + - typecheck + - unconvert + - unused + - whitespace # Run with --fast=false for more extensive checks fast: true @@ -52,25 +52,25 @@ linters-settings: importas: no-unaliased: true alias: - # Kubernetes - - pkg: k8s.io/api/core/v1 - alias: corev1 - - pkg: k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1 - alias: apiextensionsv1 - - pkg: k8s.io/apimachinery/pkg/apis/meta/v1 - alias: metav1 - - pkg: k8s.io/apimachinery/pkg/api/errors - alias: k8serrors - - pkg: k8s.io/apimachinery/pkg/util/errors - alias: kerrors - - pkg: k8s.io/component-base/logs/api/v1 - alias: logsv1 - # Controller Runtime - - pkg: sigs.k8s.io/controller-runtime - alias: ctrl - # BMO - - pkg: github.com/metal3-io/baremetal-operator/apis/metal3.io/v1alpha1 - alias: metal3api + # Kubernetes + - pkg: k8s.io/api/core/v1 + alias: corev1 + - pkg: k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1 + alias: apiextensionsv1 + - pkg: k8s.io/apimachinery/pkg/apis/meta/v1 + alias: metav1 + - pkg: k8s.io/apimachinery/pkg/api/errors + alias: k8serrors + - pkg: k8s.io/apimachinery/pkg/util/errors + alias: kerrors + - pkg: k8s.io/component-base/logs/api/v1 + alias: logsv1 + # Controller Runtime + - pkg: sigs.k8s.io/controller-runtime + alias: ctrl + # BMO + - pkg: github.com/metal3-io/baremetal-operator/apis/metal3.io/v1alpha1 + alias: metal3api nolintlint: allow-unused: false allow-leading-space: false @@ -81,80 +81,88 @@ linters-settings: go: "1.20" gocritic: enabled-tags: - - experimental + - experimental disabled-checks: - - appendAssign - - dupImport # https://github.com/go-critic/go-critic/issues/845 - - evalOrder - - ifElseChain - - octalLiteral - - regexpSimplify - - sloppyReassign - - truncateCmp - - typeDefFirst - - unnamedResult - - unnecessaryDefer - - whyNoLint - - wrapperFunc + - appendAssign + - dupImport # https://github.com/go-critic/go-critic/issues/845 + - evalOrder + - ifElseChain + - octalLiteral + - regexpSimplify + - sloppyReassign + - truncateCmp + - typeDefFirst + - unnamedResult + - unnecessaryDefer + - whyNoLint + - wrapperFunc unused: go: "1.20" issues: exclude-rules: - - path: test/e2e - linters: - - gosec - - path: _test\.go - linters: - - unused - # Specific exclude rules for deprecated fields that are still part of the codebase. - # These should be removed as the referenced deprecated item is removed from the project. - - linters: - - staticcheck - text: "SA1019:" - # Disable linters for conversion - - linters: - - staticcheck - text: "SA1019:" - path: .*(api|types)\/.*\/conversion.*\.go$ - # Dot imports for gomega or ginkgo are allowed - # within test files. - - path: _test\.go - text: should not use dot imports - - path: (test|e2e)/.*.go - text: should not use dot imports - - linters: - - revive - text: "exported: exported method .*\\.(Reconcile|SetupWithManager|SetupWebhookWithManager) should have comment or be unexported" - # Exclude some packages or code to require comments, for example test code, or fake clients. - - linters: - - revive - text: exported (method|function|type|const) (.+) should have comment or be unexported - source: (func|type).*Fake.* - - linters: - - revive - text: exported (method|function|type|const) (.+) should have comment or be unexported - path: fake_\.go - - linters: - - revive - text: exported (method|function|type|const) (.+) should have comment or be unexported - path: .*(api|types)\/.*\/conversion.*\.go$ - - linters: - - revive - text: "var-naming: don't use underscores in Go names;" - path: .*(api|types)\/.*\/conversion.*\.go$ - - linters: - - revive - text: "receiver-naming: receiver name" - path: .*(api|types)\/.*\/conversion.*\.go$ - - linters: - - stylecheck - text: "ST1003: should not use underscores in Go names;" - path: .*(api|types)\/.*\/conversion.*\.go$ - - linters: - - stylecheck - text: "ST1016: methods on the same type should have the same receiver name" - path: .*(api|types)\/.*\/conversion.*\.go$ + - path: test/e2e + linters: + - gosec + - path: test/e2e + linters: + - goconst + - path: _test\.go + linters: + - goconst + - path: _test\.go + linters: + - unused + - revive + - stylecheck + # Specific exclude rules for deprecated fields that are still part of the codebase. + # These should be removed as the referenced deprecated item is removed from the project. + - linters: + - staticcheck + text: "SA1019:" + # Disable linters for conversion + - linters: + - staticcheck + text: "SA1019:" + path: .*(api|types)\/.*\/conversion.*\.go$ + # Dot imports for gomega or ginkgo are allowed + # within test files. + - path: _test\.go + text: should not use dot imports + - path: (test|e2e)/.*.go + text: should not use dot imports + - linters: + - revive + text: "exported: exported method .*\\.(Reconcile|SetupWithManager|SetupWebhookWithManager) should have comment or be unexported" + # Exclude some packages or code to require comments, for example test code, or fake clients. + - linters: + - revive + text: exported (method|function|type|const) (.+) should have comment or be unexported + source: (func|type).*Fake.* + - linters: + - revive + text: exported (method|function|type|const) (.+) should have comment or be unexported + path: fake_\.go + - linters: + - revive + text: exported (method|function|type|const) (.+) should have comment or be unexported + path: .*(api|types)\/.*\/conversion.*\.go$ + - linters: + - revive + text: "var-naming: don't use underscores in Go names;" + path: .*(api|types)\/.*\/conversion.*\.go$ + - linters: + - revive + text: "receiver-naming: receiver name" + path: .*(api|types)\/.*\/conversion.*\.go$ + - linters: + - stylecheck + text: "ST1003: should not use underscores in Go names;" + path: .*(api|types)\/.*\/conversion.*\.go$ + - linters: + - stylecheck + text: "ST1016: methods on the same type should have the same receiver name" + path: .*(api|types)\/.*\/conversion.*\.go$ include: - - EXC0002 # include "missing comments" issues from golangci-lint + - EXC0002 # include "missing comments" issues from golangci-lint max-issues-per-linter: 0 max-same-issues: 0 diff --git a/Makefile b/Makefile index ac2747977c..d641bffafc 100644 --- a/Makefile +++ b/Makefile @@ -139,8 +139,9 @@ $(GOLANGCI_LINT_BIN): $(GOLANGCI_LINT) ## Build a local copy of golangci-lint. .PHONY: lint lint: $(GOLANGCI_LINT) $(GOLANGCI_LINT) run -v ./... - cd test; $(GOLANGCI_LINT) run -v - cd pkg/hardwareutils; $(GOLANGCI_LINT) run -v + cd apis; $(GOLANGCI_LINT) run -v ./... + cd test; $(GOLANGCI_LINT) run -v ./... + cd pkg/hardwareutils; $(GOLANGCI_LINT) run -v ./... .PHONY: manifest-lint manifest-lint: ## Run manifest validation diff --git a/apis/metal3.io/v1alpha1/baremetalhost_types.go b/apis/metal3.io/v1alpha1/baremetalhost_types.go index af629b646e..e857f67d1e 100644 --- a/apis/metal3.io/v1alpha1/baremetalhost_types.go +++ b/apis/metal3.io/v1alpha1/baremetalhost_types.go @@ -35,11 +35,11 @@ const ( BareMetalHostFinalizer string = "baremetalhost.metal3.io" // PausedAnnotation is the annotation that pauses the reconciliation (triggers - // an immediate requeue) + // an immediate requeue). PausedAnnotation = "baremetalhost.metal3.io/paused" // DetachedAnnotation is the annotation which stops provisioner management of the host - // unlike in the paused case, the host status may be updated + // unlike in the paused case, the host status may be updated. DetachedAnnotation = "baremetalhost.metal3.io/detached" // StatusAnnotation is the annotation that keeps a copy of the Status of BMH @@ -49,17 +49,22 @@ const ( StatusAnnotation = "baremetalhost.metal3.io/status" // RebootAnnotationPrefix is the annotation which tells the host which mode to use - // when rebooting - hard/soft + // when rebooting - hard/soft. RebootAnnotationPrefix = "reboot.metal3.io" // InspectAnnotationPrefix is used to specify if automatic introspection carried out - // during registration of BMH is enabled or disabled + // during registration of BMH is enabled or disabled. InspectAnnotationPrefix = "inspect.metal3.io" // HardwareDetailsAnnotation provides the hardware details for the host // in case its not already part of the host status and when introspection - // is disabed + // is disabled. HardwareDetailsAnnotation = InspectAnnotationPrefix + "/hardwaredetails" + + // Disabled is a constant string="disabled" + // This is particularly useful to check if inspect annotation is disabled + // inspect.metal3.io=disabled. + InspectAnnotationValueDisabled = "disabled" ) // RootDeviceHints holds the hints for specifying the storage location @@ -106,11 +111,11 @@ type RootDeviceHints struct { Rotational *bool `json:"rotational,omitempty"` } -// BootMode is the boot mode of the system +// BootMode is the boot mode of the system. // +kubebuilder:validation:Enum=UEFI;UEFISecureBoot;legacy type BootMode string -// Allowed boot mode from metal3 +// Allowed boot mode from metal3. const ( UEFI BootMode = "UEFI" UEFISecureBoot BootMode = "UEFISecureBoot" @@ -118,7 +123,7 @@ const ( DefaultBootMode BootMode = UEFI ) -// OperationalStatus represents the state of the host +// OperationalStatus represents the state of the host. type OperationalStatus string const ( @@ -136,15 +141,15 @@ const ( OperationalStatusError OperationalStatus = "error" // OperationalStatusDelayed is the status value for when the host - // deployment needs to be delayed to limit simultaneous hosts provisioning + // deployment needs to be delayed to limit simultaneous hosts provisioning. OperationalStatusDelayed = "delayed" // OperationalStatusDetached is the status value when the host is - // marked unmanaged via the detached annotation + // marked unmanaged via the detached annotation. OperationalStatusDetached OperationalStatus = "detached" ) -// OperationalStatusAllowed represents the allowed values of OperationalStatus +// OperationalStatusAllowed represents the allowed values of OperationalStatus. var OperationalStatusAllowed = []string{"", string(OperationalStatusOK), string(OperationalStatusDiscovered), string(OperationalStatusError), string(OperationalStatusDelayed), string(OperationalStatusDetached)} // ErrorType indicates the class of problem that has caused the Host resource @@ -172,11 +177,11 @@ const ( // controller is unable to modify the power state of the Host. PowerManagementError ErrorType = "power management error" // DetachError is an error condition occurring when the - // controller is unable to detatch the host from the provisioner + // controller is unable to detatch the host from the provisioner. DetachError ErrorType = "detach error" ) -// ErrorTypeAllowed represents the allowed values of ErrorType +// ErrorTypeAllowed represents the allowed values of ErrorType. var ErrorTypeAllowed = []string{"", string(ProvisionedRegistrationError), string(RegistrationError), string(InspectionError), string(PreparationError), string(ProvisioningError), string(PowerManagementError)} // ProvisioningState defines the states the provisioner will report @@ -184,47 +189,47 @@ var ErrorTypeAllowed = []string{"", string(ProvisionedRegistrationError), string type ProvisioningState string const ( - // StateNone means the state is unknown + // StateNone means the state is unknown. StateNone ProvisioningState = "" // StateUnmanaged means there is insufficient information available to - // register the host + // register the host. StateUnmanaged ProvisioningState = "unmanaged" - // StateRegistering means we are telling the backend about the host + // StateRegistering means we are telling the backend about the host. StateRegistering ProvisioningState = "registering" // StateMatchProfile used to mean we are assigning a profile. - // It no longer does anything, profile matching is done on registration + // It no longer does anything, profile matching is done on registration. StateMatchProfile ProvisioningState = "match profile" - // StatePreparing means we are removing existing configuration and set new configuration to the host + // StatePreparing means we are removing existing configuration and set new configuration to the host. StatePreparing ProvisioningState = "preparing" - // StateReady is a deprecated name for StateAvailable + // StateReady is a deprecated name for StateAvailable. StateReady ProvisioningState = "ready" - // StateAvailable means the host can be consumed + // StateAvailable means the host can be consumed. StateAvailable ProvisioningState = "available" // StateProvisioning means we are writing an image to the host's - // disk(s) + // disk(s). StateProvisioning ProvisioningState = "provisioning" // StateProvisioned means we have written an image to the host's - // disk(s) + // disk(s). StateProvisioned ProvisioningState = "provisioned" // StateExternallyProvisioned means something else is managing the - // image on the host + // image on the host. StateExternallyProvisioned ProvisioningState = "externally provisioned" // StateDeprovisioning means we are removing an image from the - // host's disk(s) + // host's disk(s). StateDeprovisioning ProvisioningState = "deprovisioning" // StateInspecting means we are running the agent on the host to - // learn about the hardware components available there + // learn about the hardware components available there. StateInspecting ProvisioningState = "inspecting" // StatePoweringOffBeforeDelete means we are in the process of @@ -232,7 +237,7 @@ const ( StatePoweringOffBeforeDelete ProvisioningState = "powering off before delete" // StateDeleting means we are in the process of cleaning up the host - // ready for deletion + // ready for deletion. StateDeleting ProvisioningState = "deleting" ) @@ -256,7 +261,7 @@ type BMCDetails struct { DisableCertificateVerification bool `json:"disableCertificateVerification,omitempty"` } -// HardwareRAIDVolume defines the desired configuration of volume in hardware RAID +// HardwareRAIDVolume defines the desired configuration of volume in hardware RAID. type HardwareRAIDVolume struct { // Size (Integer) of the logical disk to be created in GiB. // If unspecified or set be 0, the maximum capacity of disk will be used for logical disk. @@ -287,7 +292,7 @@ type HardwareRAIDVolume struct { PhysicalDisks []string `json:"physicalDisks,omitempty"` } -// SoftwareRAIDVolume defines the desired configuration of volume in software RAID +// SoftwareRAIDVolume defines the desired configuration of volume in software RAID. type SoftwareRAIDVolume struct { // Size (Integer) of the logical disk to be created in GiB. // If unspecified or set be 0, the maximum capacity of disk will be used for logical disk. @@ -303,7 +308,7 @@ type SoftwareRAIDVolume struct { PhysicalDisks []RootDeviceHints `json:"physicalDisks,omitempty"` } -// RAIDConfig contains the configuration that are required to config RAID in Bare Metal server +// RAIDConfig contains the configuration that are required to config RAID in Bare Metal server. type RAIDConfig struct { // The list of logical disks for hardware RAID, if rootDeviceHints isn't used, first volume is root volume. // You can set the value of this field to `[]` to clear all the hardware RAID configurations. @@ -325,7 +330,7 @@ type RAIDConfig struct { SoftwareRAIDVolumes []SoftwareRAIDVolume `json:"softwareRAIDVolumes"` } -// FirmwareConfig contains the configuration that you want to configure BIOS settings in Bare metal server +// FirmwareConfig contains the configuration that you want to configure BIOS settings in Bare metal server. type FirmwareConfig struct { // Supports the virtualization of platform hardware. // This supports following options: true, false. @@ -343,7 +348,7 @@ type FirmwareConfig struct { SriovEnabled *bool `json:"sriovEnabled,omitempty"` } -// BareMetalHostSpec defines the desired state of BareMetalHost +// BareMetalHostSpec defines the desired state of BareMetalHost. type BareMetalHostSpec struct { // Important: Run "make generate manifests" to regenerate code // after modifying this file @@ -443,7 +448,7 @@ type BareMetalHostSpec struct { // +kubebuilder:validation:Enum:=metadata;disabled type AutomatedCleaningMode string -// Allowed automated cleaning modes +// Allowed automated cleaning modes. const ( CleaningModeDisabled AutomatedCleaningMode = "disabled" CleaningModeMetadata AutomatedCleaningMode = "metadata" @@ -454,16 +459,16 @@ const ( type ChecksumType string const ( - // MD5 checksum type + // MD5 checksum type. MD5 ChecksumType = "md5" - // SHA256 checksum type + // SHA256 checksum type. SHA256 ChecksumType = "sha256" - // SHA512 checksum type + // SHA512 checksum type. SHA512 ChecksumType = "sha512" - // Automatically detect + // Automatically detect. AutoChecksum ChecksumType = "auto" ) @@ -509,16 +514,16 @@ type CustomDeploy struct { // +kubebuilder:validation:Format=double type ClockSpeed float64 -// ClockSpeed multipliers +// ClockSpeed multipliers. const ( MegaHertz ClockSpeed = 1.0 GigaHertz = 1000 * MegaHertz ) -// Capacity is a disk size in Bytes +// Capacity is a disk size in Bytes. type Capacity int64 -// Capacity multipliers +// Capacity multipliers. const ( Byte Capacity = 1 KibiByte = Byte * 1024 @@ -604,7 +609,7 @@ type Storage struct { // +kubebuilder:validation:Maximum=4094 type VLANID int32 -// VLAN represents the name and ID of a VLAN +// VLAN represents the name and ID of a VLAN. type VLAN struct { ID VLANID `json:"id,omitempty"` @@ -685,17 +690,17 @@ type CredentialsStatus struct { Version string `json:"credentialsVersion,omitempty"` } -// RebootMode defines known variations of reboot modes +// RebootMode defines known variations of reboot modes. type RebootMode string const ( - // RebootModeHard defined for hard reset of a node + // RebootModeHard defined for hard reset of a node. RebootModeHard RebootMode = "hard" - // RebootModeSoft defined for soft reset of a node + // RebootModeSoft defined for soft reset of a node. RebootModeSoft RebootMode = "soft" ) -// RebootAnnotationArguments defines the arguments of the RebootAnnotation type +// RebootAnnotationArguments defines the arguments of the RebootAnnotation type. type RebootAnnotationArguments struct { Mode RebootMode `json:"mode"` Force bool `json:"force"` @@ -756,7 +761,7 @@ type OperationHistory struct { Deprovision OperationMetric `json:"deprovision,omitempty"` } -// BareMetalHostStatus defines the observed state of BareMetalHost +// BareMetalHostStatus defines the observed state of BareMetalHost. type BareMetalHostStatus struct { // Important: Run "make generate manifests" to regenerate code // after modifying this file @@ -856,6 +861,8 @@ type BareMetalHost struct { } // BootMode returns the boot method to use for the host. +// +//nolint:stylecheck func (host *BareMetalHost) BootMode() BootMode { mode := host.Spec.BootMode if mode == "" { @@ -864,34 +871,12 @@ func (host *BareMetalHost) BootMode() BootMode { return mode } -// setLabel updates the given label when necessary and returns true -// when a change is made or false when no change is made. -func (host *BareMetalHost) setLabel(name, value string) bool { - if host.Labels == nil { - host.Labels = make(map[string]string) - } - if host.Labels[name] != value { - host.Labels[name] = value - return true - } - return false -} - -// getLabel returns the value associated with the given label. If -// there is no value, an empty string is returned. -func (host *BareMetalHost) getLabel(name string) string { - if host.Labels == nil { - return "" - } - return host.Labels[name] -} - -// HasBMCDetails returns true if the BMC details are set +// HasBMCDetails returns true if the BMC details are set. func (host *BareMetalHost) HasBMCDetails() bool { return host.Spec.BMC.Address != "" || host.Spec.BMC.CredentialsName != "" } -// NeedsHardwareProfile returns true if the profile is not set +// NeedsHardwareProfile returns true if the profile is not set. func (host *BareMetalHost) NeedsHardwareProfile() bool { return host.Status.HardwareProfile == "" } @@ -1078,7 +1063,7 @@ func (host *BareMetalHost) OperationMetricForState(operation ProvisioningState) return } -// GetChecksum method returns the checksum of an image +// GetChecksum method returns the checksum of an image. func (image *Image) GetChecksum() (checksum, checksumType string, ok bool) { if image == nil { return @@ -1113,7 +1098,7 @@ func (image *Image) GetChecksum() (checksum, checksumType string, ok bool) { // +kubebuilder:object:root=true -// BareMetalHostList contains a list of BareMetalHost +// BareMetalHostList contains a list of BareMetalHost. type BareMetalHostList struct { metav1.TypeMeta `json:",inline"` metav1.ListMeta `json:"metadata,omitempty"` diff --git a/apis/metal3.io/v1alpha1/baremetalhost_types_test.go b/apis/metal3.io/v1alpha1/baremetalhost_types_test.go index 815dccdce7..7ee7f7bb71 100644 --- a/apis/metal3.io/v1alpha1/baremetalhost_types_test.go +++ b/apis/metal3.io/v1alpha1/baremetalhost_types_test.go @@ -10,7 +10,6 @@ import ( ) func TestHostNeedsHardwareInspection(t *testing.T) { - testCases := []struct { Scenario string Host BareMetalHost diff --git a/apis/metal3.io/v1alpha1/baremetalhost_validation.go b/apis/metal3.io/v1alpha1/baremetalhost_validation.go index e1073d8543..ad2c85b255 100644 --- a/apis/metal3.io/v1alpha1/baremetalhost_validation.go +++ b/apis/metal3.io/v1alpha1/baremetalhost_validation.go @@ -22,7 +22,7 @@ var ( inspectAnnotationAllowedString = "\"disabled\" or \"\"" ) -// validateHost validates BareMetalHost resource for creation +// validateHost validates BareMetalHost resource for creation. func (host *BareMetalHost) validateHost() []error { var errs []error var bmcAccess bmc.AccessDetails @@ -67,7 +67,7 @@ func (host *BareMetalHost) validateHost() []error { } // validateChanges validates BareMetalHost resource on changes -// but also covers the validations of creation +// but also covers the validations of creation. func (host *BareMetalHost) validateChanges(old *BareMetalHost) []error { var errs []error @@ -154,7 +154,6 @@ func validateRAID(r *RAIDConfig) []error { } func validateBMHName(bmhname string) error { - invalidname, _ := regexp.MatchString(`[^A-Za-z0-9\.\-\_]`, bmhname) if invalidname { return errors.New("BareMetalHost resource name cannot contain characters other than [A-Za-z0-9._-]") @@ -169,7 +168,6 @@ func validateBMHName(bmhname string) error { } func validateDNSName(hostaddress string) error { - if hostaddress == "" { return nil } @@ -183,7 +181,6 @@ func validateAnnotations(host *BareMetalHost) []error { var err error for annotation, value := range host.Annotations { - switch { case annotation == StatusAnnotation: err = validateStatusAnnotation(value) @@ -207,7 +204,6 @@ func validateAnnotations(host *BareMetalHost) []error { func validateStatusAnnotation(statusAnnotation string) error { if statusAnnotation != "" { - objBMHStatus := &BareMetalHostStatus{} deco := json.NewDecoder(strings.NewReader(statusAnnotation)) @@ -225,7 +221,6 @@ func validateStatusAnnotation(statusAnnotation string) error { } func validateImageURL(imageURL string) error { - _, err := url.ParseRequestURI(imageURL) if err != nil { return fmt.Errorf("image URL %s is invalid: %w", imageURL, err) @@ -254,9 +249,8 @@ func validateRootDeviceHints(rdh *RootDeviceHints) error { // When making changes to this function for operationalstatus and errortype, // also make the corresponding changes in the OperationalStatus and // ErrorType fields in the struct definition of BareMetalHostStatus in -// the file baremetalhost_types.go +// the file baremetalhost_types.go. func checkStatusAnnotation(bmhStatus *BareMetalHostStatus) error { - if !slices.Contains(OperationalStatusAllowed, string(bmhStatus.OperationalStatus)) { return fmt.Errorf("invalid operationalStatus '%s' in the %s annotation", string(bmhStatus.OperationalStatus), StatusAnnotation) } diff --git a/apis/metal3.io/v1alpha1/baremetalhost_webhook.go b/apis/metal3.io/v1alpha1/baremetalhost_webhook.go index 0e5f646f05..f4138c1b8c 100644 --- a/apis/metal3.io/v1alpha1/baremetalhost_webhook.go +++ b/apis/metal3.io/v1alpha1/baremetalhost_webhook.go @@ -15,7 +15,7 @@ package v1alpha1 import ( "fmt" - "k8s.io/apimachinery/pkg/util/errors" + kerrors "k8s.io/apimachinery/pkg/util/errors" "k8s.io/apimachinery/pkg/runtime" logf "sigs.k8s.io/controller-runtime/pkg/log" @@ -27,13 +27,13 @@ var baremetalhostlog = logf.Log.WithName("webhooks").WithName("BareMetalHost") //+kubebuilder:webhook:verbs=create;update,path=/validate-metal3-io-v1alpha1-baremetalhost,mutating=false,failurePolicy=fail,sideEffects=none,admissionReviewVersions=v1;v1beta,groups=metal3.io,resources=baremetalhosts,versions=v1alpha1,name=baremetalhost.metal3.io -// ValidateCreate implements webhook.Validator so a webhook will be registered for the type +// ValidateCreate implements webhook.Validator so a webhook will be registered for the type. func (r *BareMetalHost) ValidateCreate() (admission.Warnings, error) { baremetalhostlog.Info("validate create", "namespace", r.Namespace, "name", r.Name) - return nil, errors.NewAggregate(r.validateHost()) + return nil, kerrors.NewAggregate(r.validateHost()) } -// ValidateUpdate implements webhook.Validator so a webhook will be registered for the type +// ValidateUpdate implements webhook.Validator so a webhook will be registered for the type. func (r *BareMetalHost) ValidateUpdate(old runtime.Object) (admission.Warnings, error) { baremetalhostlog.Info("validate update", "namespace", r.Namespace, "name", r.Name) bmh, casted := old.(*BareMetalHost) @@ -41,10 +41,10 @@ func (r *BareMetalHost) ValidateUpdate(old runtime.Object) (admission.Warnings, baremetalhostlog.Error(fmt.Errorf("old object conversion error for %s/%s", r.Namespace, r.Name), "validate update error") return nil, nil } - return nil, errors.NewAggregate(r.validateChanges(bmh)) + return nil, kerrors.NewAggregate(r.validateChanges(bmh)) } -// ValidateDelete implements webhook.Validator so a webhook will be registered for the type +// ValidateDelete implements webhook.Validator so a webhook will be registered for the type. func (r *BareMetalHost) ValidateDelete() (admission.Warnings, error) { return nil, nil } diff --git a/apis/metal3.io/v1alpha1/bmceventsubscription_types.go b/apis/metal3.io/v1alpha1/bmceventsubscription_types.go index aa8b8e6995..d01c61b328 100644 --- a/apis/metal3.io/v1alpha1/bmceventsubscription_types.go +++ b/apis/metal3.io/v1alpha1/bmceventsubscription_types.go @@ -68,7 +68,7 @@ type BMCEventSubscription struct { // +kubebuilder:object:root=true -// BMCEventSubscriptionList contains a list of BMCEventSubscriptions +// BMCEventSubscriptionList contains a list of BMCEventSubscriptions. type BMCEventSubscriptionList struct { metav1.TypeMeta `json:",inline"` metav1.ListMeta `json:"metadata,omitempty"` diff --git a/apis/metal3.io/v1alpha1/bmceventsubscription_validation.go b/apis/metal3.io/v1alpha1/bmceventsubscription_validation.go index 96ba7544f3..1aefae1b32 100644 --- a/apis/metal3.io/v1alpha1/bmceventsubscription_validation.go +++ b/apis/metal3.io/v1alpha1/bmceventsubscription_validation.go @@ -21,7 +21,7 @@ import ( "net/url" ) -// validateSubscription validates BMCEventSubscription resource for creation +// validateSubscription validates BMCEventSubscription resource for creation. func (s *BMCEventSubscription) validateSubscription() []error { var errs []error @@ -32,16 +32,13 @@ func (s *BMCEventSubscription) validateSubscription() []error { if s.Spec.Destination == "" { errs = append(errs, errors.New("destination cannot be empty")) } else { - destinationUrl, err := url.ParseRequestURI(s.Spec.Destination) + destinationURL, err := url.ParseRequestURI(s.Spec.Destination) if err != nil { errs = append(errs, fmt.Errorf("destination is invalid: %w", err)) - } else { - if destinationUrl.Path == "" { - errs = append(errs, errors.New("hostname-only destination must have a trailing slash")) - } + } else if destinationURL.Path == "" { + errs = append(errs, errors.New("hostname-only destination must have a trailing slash")) } } - return errs } diff --git a/apis/metal3.io/v1alpha1/bmceventsubscription_webhook.go b/apis/metal3.io/v1alpha1/bmceventsubscription_webhook.go index 43a06a4c01..3c3870bc61 100644 --- a/apis/metal3.io/v1alpha1/bmceventsubscription_webhook.go +++ b/apis/metal3.io/v1alpha1/bmceventsubscription_webhook.go @@ -15,7 +15,7 @@ package v1alpha1 import ( "fmt" - "k8s.io/apimachinery/pkg/util/errors" + kerrors "k8s.io/apimachinery/pkg/util/errors" "k8s.io/apimachinery/pkg/runtime" logf "sigs.k8s.io/controller-runtime/pkg/log" @@ -27,10 +27,10 @@ var bmcsubscriptionlog = logf.Log.WithName("webhooks").WithName("BMCEventSubscri //+kubebuilder:webhook:verbs=create;update,path=/validate-metal3-io-v1alpha1-bmceventsubscription,mutating=false,failurePolicy=fail,sideEffects=none,admissionReviewVersions=v1;v1beta,groups=metal3.io,resources=bmceventsubscriptions,versions=v1alpha1,name=bmceventsubscription.metal3.io -// ValidateCreate implements webhook.Validator so a webhook will be registered for the type +// ValidateCreate implements webhook.Validator so a webhook will be registered for the type. func (s *BMCEventSubscription) ValidateCreate() (admission.Warnings, error) { bmcsubscriptionlog.Info("validate create", "namespace", s.Namespace, "name", s.Name) - return nil, errors.NewAggregate(s.validateSubscription()) + return nil, kerrors.NewAggregate(s.validateSubscription()) } // ValidateUpdate implements webhook.Validator so a webhook will be registered for the type @@ -52,7 +52,7 @@ func (s *BMCEventSubscription) ValidateUpdate(old runtime.Object) (admission.War return nil, nil } -// ValidateDelete implements webhook.Validator so a webhook will be registered for the type +// ValidateDelete implements webhook.Validator so a webhook will be registered for the type. func (s *BMCEventSubscription) ValidateDelete() (admission.Warnings, error) { return nil, nil } diff --git a/apis/metal3.io/v1alpha1/firmwareschema_types.go b/apis/metal3.io/v1alpha1/firmwareschema_types.go index 8c7fc8527c..9e9f4f5ca9 100644 --- a/apis/metal3.io/v1alpha1/firmwareschema_types.go +++ b/apis/metal3.io/v1alpha1/firmwareschema_types.go @@ -25,7 +25,7 @@ import ( "k8s.io/apimachinery/pkg/util/intstr" ) -// Additional data describing the firmware setting +// Additional data describing the firmware setting. type SettingSchema struct { // The type of setting. @@ -65,8 +65,7 @@ func (e SchemaSettingError) Error() string { } func (schema *SettingSchema) Validate(name string, value intstr.IntOrString) error { - - if schema.ReadOnly != nil && *schema.ReadOnly == true { + if schema.ReadOnly != nil && *schema.ReadOnly { return SchemaSettingError{name: name, message: "it is ReadOnly"} } @@ -128,7 +127,7 @@ func (schema *SettingSchema) Validate(name string, value intstr.IntOrString) err } } -// FirmwareSchemaSpec defines the desired state of FirmwareSchema +// FirmwareSchemaSpec defines the desired state of FirmwareSchema. type FirmwareSchemaSpec struct { // The hardware vendor associated with this schema @@ -145,7 +144,7 @@ type FirmwareSchemaSpec struct { //+kubebuilder:object:root=true -// FirmwareSchema is the Schema for the firmwareschemas API +// FirmwareSchema is the Schema for the firmwareschemas API. type FirmwareSchema struct { metav1.TypeMeta `json:",inline"` metav1.ObjectMeta `json:"metadata,omitempty"` @@ -153,9 +152,8 @@ type FirmwareSchema struct { Spec FirmwareSchemaSpec `json:"spec,omitempty"` } -// Check whether the setting's name and value is valid using the schema +// Check whether the setting's name and value is valid using the schema. func (host *FirmwareSchema) ValidateSetting(name string, value intstr.IntOrString, schemas map[string]SettingSchema) error { - schema, ok := schemas[name] if !ok { return SchemaSettingError{name: name, message: "it is not in the associated schema"} @@ -166,7 +164,7 @@ func (host *FirmwareSchema) ValidateSetting(name string, value intstr.IntOrStrin //+kubebuilder:object:root=true -// FirmwareSchemaList contains a list of FirmwareSchema +// FirmwareSchemaList contains a list of FirmwareSchema. type FirmwareSchemaList struct { metav1.TypeMeta `json:",inline"` metav1.ListMeta `json:"metadata,omitempty"` diff --git a/apis/metal3.io/v1alpha1/groupversion_info.go b/apis/metal3.io/v1alpha1/groupversion_info.go index 0a66d9fe8e..8b39c89213 100644 --- a/apis/metal3.io/v1alpha1/groupversion_info.go +++ b/apis/metal3.io/v1alpha1/groupversion_info.go @@ -24,10 +24,10 @@ import ( ) var ( - // GroupVersion is group version used to register these objects + // GroupVersion is group version used to register these objects. GroupVersion = schema.GroupVersion{Group: "metal3.io", Version: "v1alpha1"} - // SchemeBuilder is used to add go types to the GroupVersionKind scheme + // SchemeBuilder is used to add go types to the GroupVersionKind scheme. SchemeBuilder = &scheme.Builder{GroupVersion: GroupVersion} // AddToScheme adds the types in this group-version to the given scheme. diff --git a/apis/metal3.io/v1alpha1/hardwaredata_types.go b/apis/metal3.io/v1alpha1/hardwaredata_types.go index 82dc3ad653..a8cdb97b10 100644 --- a/apis/metal3.io/v1alpha1/hardwaredata_types.go +++ b/apis/metal3.io/v1alpha1/hardwaredata_types.go @@ -20,7 +20,7 @@ import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" ) -// HardwareDataSpec defines the desired state of HardwareData +// HardwareDataSpec defines the desired state of HardwareData. type HardwareDataSpec struct { // The hardware discovered on the host during its inspection. @@ -31,7 +31,7 @@ type HardwareDataSpec struct { // +kubebuilder:resource:path=hardwaredata,scope=Namespaced,shortName=hd // +kubebuilder:printcolumn:name="Age",type="date",JSONPath=".metadata.creationTimestamp",description="Time duration since creation of HardwareData" -// HardwareData is the Schema for the hardwaredata API +// HardwareData is the Schema for the hardwaredata API. type HardwareData struct { metav1.TypeMeta `json:",inline"` metav1.ObjectMeta `json:"metadata,omitempty"` @@ -41,7 +41,7 @@ type HardwareData struct { //+kubebuilder:object:root=true -// HardwareDataList contains a list of HardwareData +// HardwareDataList contains a list of HardwareData. type HardwareDataList struct { metav1.TypeMeta `json:",inline"` metav1.ListMeta `json:"metadata,omitempty"` diff --git a/apis/metal3.io/v1alpha1/hostfirmwarecomponents_types.go b/apis/metal3.io/v1alpha1/hostfirmwarecomponents_types.go index 763168f4be..c4d3ad5f9a 100644 --- a/apis/metal3.io/v1alpha1/hostfirmwarecomponents_types.go +++ b/apis/metal3.io/v1alpha1/hostfirmwarecomponents_types.go @@ -42,19 +42,19 @@ type FirmwareComponentStatus struct { type UpdatesConditionType string const ( - // Indicates that the updates in the Spec are different than Status + // Indicates that the updates in the Spec are different than Status. HostFirmwareComponentsChangeDetected UpdatesConditionType = "ChangeDetected" - // Indicates if the updates are valid and can be configured on the host + // Indicates if the updates are valid and can be configured on the host. HostFirmwareComponentsValid UpdatesConditionType = "Valid" ) -// HostFirmwareComponentsSpec defines the desired state of HostFirmwareComponents +// HostFirmwareComponentsSpec defines the desired state of HostFirmwareComponents. type HostFirmwareComponentsSpec struct { Updates []FirmwareUpdate `json:"updates"` } -// HostFirmwareComponentsStatus defines the observed state of HostFirmwareComponents +// HostFirmwareComponentsStatus defines the observed state of HostFirmwareComponents. type HostFirmwareComponentsStatus struct { // Updates is the list of all firmware components that should be updated // they are specified via name and url fields. @@ -80,7 +80,7 @@ type HostFirmwareComponentsStatus struct { //+kubebuilder:resource:shortName=hfc //+kubebuilder:subresource:status -// HostFirmwareComponents is the Schema for the hostfirmwarecomponents API +// HostFirmwareComponents is the Schema for the hostfirmwarecomponents API. type HostFirmwareComponents struct { metav1.TypeMeta `json:",inline"` metav1.ObjectMeta `json:"metadata,omitempty"` @@ -91,23 +91,21 @@ type HostFirmwareComponents struct { //+kubebuilder:object:root=true -// HostFirmwareComponentsList contains a list of HostFirmwareComponents +// HostFirmwareComponentsList contains a list of HostFirmwareComponents. type HostFirmwareComponentsList struct { metav1.TypeMeta `json:",inline"` metav1.ListMeta `json:"metadata,omitempty"` Items []HostFirmwareComponents `json:"items"` } -// Check whether the updates's names are valid +// Check whether the updates's names are valid. func (host *HostFirmwareComponents) ValidateHostFirmwareComponents() error { - allowedNames := map[string]struct{}{"bmc": {}, "bios": {}} for _, update := range host.Spec.Updates { componentName := update.Component if _, ok := allowedNames[componentName]; !ok { - return fmt.Errorf("Component %s is invalid, only 'bmc' or 'bios' are allowed as update names", update.Component) + return fmt.Errorf("component %s is invalid, only 'bmc' or 'bios' are allowed as update names", update.Component) } - } return nil diff --git a/apis/metal3.io/v1alpha1/hostfirmwarecomponents_types_test.go b/apis/metal3.io/v1alpha1/hostfirmwarecomponents_types_test.go index 4b8e6ea677..e3b3ab858c 100644 --- a/apis/metal3.io/v1alpha1/hostfirmwarecomponents_types_test.go +++ b/apis/metal3.io/v1alpha1/hostfirmwarecomponents_types_test.go @@ -65,7 +65,7 @@ func TestValidateHostFirmwareComponents(t *testing.T) { LastTransitionTime: metav1.NewTime(time.Now()), }, }, - ExpectedError: "Component nic is invalid, only 'bmc' or 'bios' are allowed as update names", + ExpectedError: "component nic is invalid, only 'bmc' or 'bios' are allowed as update names", }, } { t.Run(tc.Scenario, func(t *testing.T) { diff --git a/apis/metal3.io/v1alpha1/hostfirmwaresettings_types.go b/apis/metal3.io/v1alpha1/hostfirmwaresettings_types.go index c170e967e8..ab0b823c69 100644 --- a/apis/metal3.io/v1alpha1/hostfirmwaresettings_types.go +++ b/apis/metal3.io/v1alpha1/hostfirmwaresettings_types.go @@ -36,14 +36,14 @@ type SchemaReference struct { type SettingsConditionType string const ( - // Indicates that the settings in the Spec are different than Status + // Indicates that the settings in the Spec are different than Status. FirmwareSettingsChangeDetected SettingsConditionType = "ChangeDetected" - // Indicates if the settings are valid and can be configured on the host + // Indicates if the settings are valid and can be configured on the host. FirmwareSettingsValid SettingsConditionType = "Valid" ) -// HostFirmwareSettingsSpec defines the desired state of HostFirmwareSettings +// HostFirmwareSettingsSpec defines the desired state of HostFirmwareSettings. type HostFirmwareSettingsSpec struct { // Settings are the desired firmware settings stored as name/value pairs. @@ -51,7 +51,7 @@ type HostFirmwareSettingsSpec struct { Settings DesiredSettingsMap `json:"settings" required:"true"` } -// HostFirmwareSettingsStatus defines the observed state of HostFirmwareSettings +// HostFirmwareSettingsStatus defines the observed state of HostFirmwareSettings. type HostFirmwareSettingsStatus struct { // FirmwareSchema is a reference to the Schema used to describe each // FirmwareSetting. By default, this will be a Schema in the same @@ -78,7 +78,7 @@ type HostFirmwareSettingsStatus struct { //+kubebuilder:resource:shortName=hfs //+kubebuilder:subresource:status -// HostFirmwareSettings is the Schema for the hostfirmwaresettings API +// HostFirmwareSettings is the Schema for the hostfirmwaresettings API. type HostFirmwareSettings struct { metav1.TypeMeta `json:",inline"` metav1.ObjectMeta `json:"metadata,omitempty"` @@ -89,7 +89,7 @@ type HostFirmwareSettings struct { //+kubebuilder:object:root=true -// HostFirmwareSettingsList contains a list of HostFirmwareSettings +// HostFirmwareSettingsList contains a list of HostFirmwareSettings. type HostFirmwareSettingsList struct { metav1.TypeMeta `json:",inline"` metav1.ListMeta `json:"metadata,omitempty"` diff --git a/apis/metal3.io/v1alpha1/hostfirmwaresettings_types_test.go b/apis/metal3.io/v1alpha1/hostfirmwaresettings_types_test.go index 40463267c6..fc2f78b694 100644 --- a/apis/metal3.io/v1alpha1/hostfirmwaresettings_types_test.go +++ b/apis/metal3.io/v1alpha1/hostfirmwaresettings_types_test.go @@ -10,7 +10,6 @@ import ( ) func TestValidateSetting(t *testing.T) { - lower_bound := 1 upper_bound := 20 min_length := 1 diff --git a/apis/metal3.io/v1alpha1/preprovisioningimage_types.go b/apis/metal3.io/v1alpha1/preprovisioningimage_types.go index 7345d77bc9..fd65553896 100644 --- a/apis/metal3.io/v1alpha1/preprovisioningimage_types.go +++ b/apis/metal3.io/v1alpha1/preprovisioningimage_types.go @@ -29,7 +29,7 @@ const ( ImageFormatInitRD ImageFormat = "initrd" ) -// PreprovisioningImageSpec defines the desired state of PreprovisioningImage +// PreprovisioningImageSpec defines the desired state of PreprovisioningImage. type PreprovisioningImageSpec struct { // networkDataName is the name of a Secret in the local namespace that // contains network data to build in to the image. @@ -60,15 +60,15 @@ const ( ConditionImageError ImageStatusConditionType = "Error" ) -// PreprovisioningImageStatus defines the observed state of PreprovisioningImage +// PreprovisioningImageStatus defines the observed state of PreprovisioningImage. type PreprovisioningImageStatus struct { // imageUrl is the URL from which the built image can be downloaded. - ImageUrl string `json:"imageUrl,omitempty"` + ImageUrl string `json:"imageUrl,omitempty"` //nolint:revive,stylecheck // kernelUrl is the URL from which the kernel of the image can be downloaded. // Only makes sense for initrd images. // +optional - KernelUrl string `json:"kernelUrl,omitempty"` + KernelUrl string `json:"kernelUrl,omitempty"` //nolint:revive,stylecheck // extraKernelParams is a string with extra parameters to pass to the // kernel when booting the image over network. Only makes sense for initrd images. @@ -103,7 +103,7 @@ type PreprovisioningImageStatus struct { // +kubebuilder:printcolumn:name="Reason",type="string",JSONPath=".status.conditions[?(@.type=='Ready')].reason",description="The reason for the image readiness status" // +kubebuilder:subresource:status -// PreprovisioningImage is the Schema for the preprovisioningimages API +// PreprovisioningImage is the Schema for the preprovisioningimages API. type PreprovisioningImage struct { metav1.TypeMeta `json:",inline"` metav1.ObjectMeta `json:"metadata,omitempty"` @@ -114,7 +114,7 @@ type PreprovisioningImage struct { // +kubebuilder:object:root=true -// PreprovisioningImageList contains a list of PreprovisioningImage +// PreprovisioningImageList contains a list of PreprovisioningImage. type PreprovisioningImageList struct { metav1.TypeMeta `json:",inline"` metav1.ListMeta `json:"metadata,omitempty"` diff --git a/apis/metal3.io/v1alpha1/profile/profile.go b/apis/metal3.io/v1alpha1/profile/profile.go index e0029c7606..03ee2a8774 100644 --- a/apis/metal3.io/v1alpha1/profile/profile.go +++ b/apis/metal3.io/v1alpha1/profile/profile.go @@ -3,7 +3,7 @@ package profile import ( "fmt" - metal3v1alpha1 "github.com/metal3-io/baremetal-operator/apis/metal3.io/v1alpha1" + metal3api "github.com/metal3-io/baremetal-operator/apis/metal3.io/v1alpha1" ) const ( @@ -22,7 +22,7 @@ type Profile struct { // RootDeviceHints holds the suggestions for placing the storage // for the root filesystem. - RootDeviceHints metal3v1alpha1.RootDeviceHints + RootDeviceHints metal3api.RootDeviceHints } var profiles = make(map[string]Profile) @@ -30,35 +30,35 @@ var profiles = make(map[string]Profile) func init() { profiles[DefaultProfileName] = Profile{ Name: DefaultProfileName, - RootDeviceHints: metal3v1alpha1.RootDeviceHints{ + RootDeviceHints: metal3api.RootDeviceHints{ DeviceName: "/dev/sda", }, } profiles["libvirt"] = Profile{ Name: "libvirt", - RootDeviceHints: metal3v1alpha1.RootDeviceHints{ + RootDeviceHints: metal3api.RootDeviceHints{ DeviceName: "/dev/vda", }, } profiles["dell"] = Profile{ Name: "dell", - RootDeviceHints: metal3v1alpha1.RootDeviceHints{ + RootDeviceHints: metal3api.RootDeviceHints{ HCTL: "0:0:0:0", }, } profiles["dell-raid"] = Profile{ Name: "dell-raid", - RootDeviceHints: metal3v1alpha1.RootDeviceHints{ + RootDeviceHints: metal3api.RootDeviceHints{ HCTL: "0:2:0:0", }, } profiles["openstack"] = Profile{ Name: "openstack", - RootDeviceHints: metal3v1alpha1.RootDeviceHints{ + RootDeviceHints: metal3api.RootDeviceHints{ DeviceName: "/dev/vdb", }, } @@ -68,11 +68,11 @@ func init() { } } -// GetProfile returns the named profile +// GetProfile returns the named profile. func GetProfile(name string) (Profile, error) { profile, ok := profiles[name] if !ok { - return Profile{}, fmt.Errorf("No hardware profile named %q", name) + return Profile{}, fmt.Errorf("no hardware profile named %q", name) } return profile, nil } diff --git a/cmd/make-virt-host/main.go b/cmd/make-virt-host/main.go index b5130665c7..9b94c7265c 100644 --- a/cmd/make-virt-host/main.go +++ b/cmd/make-virt-host/main.go @@ -156,7 +156,7 @@ func main() { } domainResult := Domain{} - xml.Unmarshal([]byte(virshOut), &domainResult) + xml.Unmarshal(virshOut, &domainResult) if *verbose { fmt.Printf("%v\n", domainResult) } @@ -192,7 +192,7 @@ func main() { } var vbmcResult []VBMC - json.Unmarshal([]byte(vbmcOut), &vbmcResult) + json.Unmarshal(vbmcOut, &vbmcResult) nameToPort := make(map[string]int) for _, vbmc := range vbmcResult { if *verbose { diff --git a/config/base/crds/bases/metal3.io_baremetalhosts.yaml b/config/base/crds/bases/metal3.io_baremetalhosts.yaml index d2aa212167..007f1e7a8f 100644 --- a/config/base/crds/bases/metal3.io_baremetalhosts.yaml +++ b/config/base/crds/bases/metal3.io_baremetalhosts.yaml @@ -71,7 +71,7 @@ spec: metadata: type: object spec: - description: BareMetalHostSpec defines the desired state of BareMetalHost + description: BareMetalHostSpec defines the desired state of BareMetalHost. properties: architecture: description: CPU architecture of the host, e.g. "x86_64" or "aarch64". @@ -298,7 +298,7 @@ spec: of this field to `[]` to clear all the hardware RAID configurations. items: description: HardwareRAIDVolume defines the desired configuration - of volume in hardware RAID + of volume in hardware RAID. properties: controller: description: The name of the RAID controller to use @@ -363,7 +363,7 @@ spec: will always be deleted. items: description: SoftwareRAIDVolume defines the desired configuration - of volume in software RAID + of volume in software RAID. properties: level: description: 'RAID level for the logical disk. The following @@ -533,7 +533,7 @@ spec: - online type: object status: - description: BareMetalHostStatus defines the observed state of BareMetalHost + description: BareMetalHostStatus defines the observed state of BareMetalHost. properties: errorCount: default: 0 @@ -650,7 +650,7 @@ spec: vlans: description: The VLANs available items: - description: VLAN represents the name and ID of a VLAN + description: VLAN represents the name and ID of a VLAN. properties: id: description: VLANID is a 12-bit 802.1Q VLAN identifier @@ -913,7 +913,7 @@ spec: the hardware RAID configurations. items: description: HardwareRAIDVolume defines the desired configuration - of volume in hardware RAID + of volume in hardware RAID. properties: controller: description: The name of the RAID controller to use @@ -979,7 +979,7 @@ spec: RAID will always be deleted. items: description: SoftwareRAIDVolume defines the desired configuration - of volume in software RAID + of volume in software RAID. properties: level: description: 'RAID level for the logical disk. The following diff --git a/config/base/crds/bases/metal3.io_firmwareschemas.yaml b/config/base/crds/bases/metal3.io_firmwareschemas.yaml index 4f25a90d64..b95f5d3c93 100644 --- a/config/base/crds/bases/metal3.io_firmwareschemas.yaml +++ b/config/base/crds/bases/metal3.io_firmwareschemas.yaml @@ -17,7 +17,7 @@ spec: - name: v1alpha1 schema: openAPIV3Schema: - description: FirmwareSchema is the Schema for the firmwareschemas API + description: FirmwareSchema is the Schema for the firmwareschemas API. properties: apiVersion: description: 'APIVersion defines the versioned schema of this representation @@ -32,7 +32,7 @@ spec: metadata: type: object spec: - description: FirmwareSchemaSpec defines the desired state of FirmwareSchema + description: FirmwareSchemaSpec defines the desired state of FirmwareSchema. properties: hardwareModel: description: The hardware model associated with this schema @@ -42,7 +42,7 @@ spec: type: string schema: additionalProperties: - description: Additional data describing the firmware setting + description: Additional data describing the firmware setting. properties: allowable_values: description: The allowable value for an Enumeration type setting. diff --git a/config/base/crds/bases/metal3.io_hardwaredata.yaml b/config/base/crds/bases/metal3.io_hardwaredata.yaml index 0f78fcc8ca..890ba63930 100644 --- a/config/base/crds/bases/metal3.io_hardwaredata.yaml +++ b/config/base/crds/bases/metal3.io_hardwaredata.yaml @@ -24,7 +24,7 @@ spec: name: v1alpha1 schema: openAPIV3Schema: - description: HardwareData is the Schema for the hardwaredata API + description: HardwareData is the Schema for the hardwaredata API. properties: apiVersion: description: 'APIVersion defines the versioned schema of this representation @@ -39,7 +39,7 @@ spec: metadata: type: object spec: - description: HardwareDataSpec defines the desired state of HardwareData + description: HardwareDataSpec defines the desired state of HardwareData. properties: hardware: description: The hardware discovered on the host during its inspection. @@ -117,7 +117,7 @@ spec: vlans: description: The VLANs available items: - description: VLAN represents the name and ID of a VLAN + description: VLAN represents the name and ID of a VLAN. properties: id: description: VLANID is a 12-bit 802.1Q VLAN identifier diff --git a/config/base/crds/bases/metal3.io_hostfirmwarecomponents.yaml b/config/base/crds/bases/metal3.io_hostfirmwarecomponents.yaml index f9bb70083e..292348e573 100644 --- a/config/base/crds/bases/metal3.io_hostfirmwarecomponents.yaml +++ b/config/base/crds/bases/metal3.io_hostfirmwarecomponents.yaml @@ -20,7 +20,7 @@ spec: schema: openAPIV3Schema: description: HostFirmwareComponents is the Schema for the hostfirmwarecomponents - API + API. properties: apiVersion: description: 'APIVersion defines the versioned schema of this representation @@ -35,7 +35,7 @@ spec: metadata: type: object spec: - description: HostFirmwareComponentsSpec defines the desired state of HostFirmwareComponents + description: HostFirmwareComponentsSpec defines the desired state of HostFirmwareComponents. properties: updates: items: @@ -55,7 +55,7 @@ spec: type: object status: description: HostFirmwareComponentsStatus defines the observed state of - HostFirmwareComponents + HostFirmwareComponents. properties: components: description: Components is the list of all available firmware components diff --git a/config/base/crds/bases/metal3.io_hostfirmwaresettings.yaml b/config/base/crds/bases/metal3.io_hostfirmwaresettings.yaml index f6f799e713..b079db0453 100644 --- a/config/base/crds/bases/metal3.io_hostfirmwaresettings.yaml +++ b/config/base/crds/bases/metal3.io_hostfirmwaresettings.yaml @@ -20,7 +20,7 @@ spec: schema: openAPIV3Schema: description: HostFirmwareSettings is the Schema for the hostfirmwaresettings - API + API. properties: apiVersion: description: 'APIVersion defines the versioned schema of this representation @@ -35,7 +35,7 @@ spec: metadata: type: object spec: - description: HostFirmwareSettingsSpec defines the desired state of HostFirmwareSettings + description: HostFirmwareSettingsSpec defines the desired state of HostFirmwareSettings. properties: settings: additionalProperties: @@ -51,7 +51,7 @@ spec: type: object status: description: HostFirmwareSettingsStatus defines the observed state of - HostFirmwareSettings + HostFirmwareSettings. properties: conditions: description: Track whether settings stored in the spec are valid based diff --git a/config/base/crds/bases/metal3.io_preprovisioningimages.yaml b/config/base/crds/bases/metal3.io_preprovisioningimages.yaml index dac8d3b66a..127d97fc17 100644 --- a/config/base/crds/bases/metal3.io_preprovisioningimages.yaml +++ b/config/base/crds/bases/metal3.io_preprovisioningimages.yaml @@ -29,7 +29,7 @@ spec: schema: openAPIV3Schema: description: PreprovisioningImage is the Schema for the preprovisioningimages - API + API. properties: apiVersion: description: 'APIVersion defines the versioned schema of this representation @@ -44,7 +44,7 @@ spec: metadata: type: object spec: - description: PreprovisioningImageSpec defines the desired state of PreprovisioningImage + description: PreprovisioningImageSpec defines the desired state of PreprovisioningImage. properties: acceptFormats: description: acceptFormats is a list of acceptable image formats. @@ -66,7 +66,7 @@ spec: type: object status: description: PreprovisioningImageStatus defines the observed state of - PreprovisioningImage + PreprovisioningImage. properties: architecture: description: architecture is the processor architecture for which diff --git a/config/render/capm3.yaml b/config/render/capm3.yaml index f013ce5051..d7e1140690 100644 --- a/config/render/capm3.yaml +++ b/config/render/capm3.yaml @@ -71,7 +71,7 @@ spec: metadata: type: object spec: - description: BareMetalHostSpec defines the desired state of BareMetalHost + description: BareMetalHostSpec defines the desired state of BareMetalHost. properties: architecture: description: CPU architecture of the host, e.g. "x86_64" or "aarch64". @@ -298,7 +298,7 @@ spec: of this field to `[]` to clear all the hardware RAID configurations. items: description: HardwareRAIDVolume defines the desired configuration - of volume in hardware RAID + of volume in hardware RAID. properties: controller: description: The name of the RAID controller to use @@ -363,7 +363,7 @@ spec: will always be deleted. items: description: SoftwareRAIDVolume defines the desired configuration - of volume in software RAID + of volume in software RAID. properties: level: description: 'RAID level for the logical disk. The following @@ -533,7 +533,7 @@ spec: - online type: object status: - description: BareMetalHostStatus defines the observed state of BareMetalHost + description: BareMetalHostStatus defines the observed state of BareMetalHost. properties: errorCount: default: 0 @@ -650,7 +650,7 @@ spec: vlans: description: The VLANs available items: - description: VLAN represents the name and ID of a VLAN + description: VLAN represents the name and ID of a VLAN. properties: id: description: VLANID is a 12-bit 802.1Q VLAN identifier @@ -913,7 +913,7 @@ spec: the hardware RAID configurations. items: description: HardwareRAIDVolume defines the desired configuration - of volume in hardware RAID + of volume in hardware RAID. properties: controller: description: The name of the RAID controller to use @@ -979,7 +979,7 @@ spec: RAID will always be deleted. items: description: SoftwareRAIDVolume defines the desired configuration - of volume in software RAID + of volume in software RAID. properties: level: description: 'RAID level for the logical disk. The following @@ -1245,7 +1245,7 @@ spec: - name: v1alpha1 schema: openAPIV3Schema: - description: FirmwareSchema is the Schema for the firmwareschemas API + description: FirmwareSchema is the Schema for the firmwareschemas API. properties: apiVersion: description: 'APIVersion defines the versioned schema of this representation @@ -1260,7 +1260,7 @@ spec: metadata: type: object spec: - description: FirmwareSchemaSpec defines the desired state of FirmwareSchema + description: FirmwareSchemaSpec defines the desired state of FirmwareSchema. properties: hardwareModel: description: The hardware model associated with this schema @@ -1270,7 +1270,7 @@ spec: type: string schema: additionalProperties: - description: Additional data describing the firmware setting + description: Additional data describing the firmware setting. properties: allowable_values: description: The allowable value for an Enumeration type setting. @@ -1340,7 +1340,7 @@ spec: name: v1alpha1 schema: openAPIV3Schema: - description: HardwareData is the Schema for the hardwaredata API + description: HardwareData is the Schema for the hardwaredata API. properties: apiVersion: description: 'APIVersion defines the versioned schema of this representation @@ -1355,7 +1355,7 @@ spec: metadata: type: object spec: - description: HardwareDataSpec defines the desired state of HardwareData + description: HardwareDataSpec defines the desired state of HardwareData. properties: hardware: description: The hardware discovered on the host during its inspection. @@ -1433,7 +1433,7 @@ spec: vlans: description: The VLANs available items: - description: VLAN represents the name and ID of a VLAN + description: VLAN represents the name and ID of a VLAN. properties: id: description: VLANID is a 12-bit 802.1Q VLAN identifier @@ -1545,7 +1545,7 @@ spec: schema: openAPIV3Schema: description: HostFirmwareSettings is the Schema for the hostfirmwaresettings - API + API. properties: apiVersion: description: 'APIVersion defines the versioned schema of this representation @@ -1560,7 +1560,7 @@ spec: metadata: type: object spec: - description: HostFirmwareSettingsSpec defines the desired state of HostFirmwareSettings + description: HostFirmwareSettingsSpec defines the desired state of HostFirmwareSettings. properties: settings: additionalProperties: @@ -1576,7 +1576,7 @@ spec: type: object status: description: HostFirmwareSettingsStatus defines the observed state of - HostFirmwareSettings + HostFirmwareSettings. properties: conditions: description: Track whether settings stored in the spec are valid based @@ -1716,7 +1716,7 @@ spec: schema: openAPIV3Schema: description: PreprovisioningImage is the Schema for the preprovisioningimages - API + API. properties: apiVersion: description: 'APIVersion defines the versioned schema of this representation @@ -1731,7 +1731,7 @@ spec: metadata: type: object spec: - description: PreprovisioningImageSpec defines the desired state of PreprovisioningImage + description: PreprovisioningImageSpec defines the desired state of PreprovisioningImage. properties: acceptFormats: description: acceptFormats is a list of acceptable image formats. @@ -1753,7 +1753,7 @@ spec: type: object status: description: PreprovisioningImageStatus defines the observed state of - PreprovisioningImage + PreprovisioningImage. properties: architecture: description: architecture is the processor architecture for which diff --git a/controllers/metal3.io/action_result.go b/controllers/metal3.io/action_result.go index eb1d7fed92..903a7f122d 100644 --- a/controllers/metal3.io/action_result.go +++ b/controllers/metal3.io/action_result.go @@ -85,7 +85,7 @@ func (r actionComplete) Dirty() bool { // deleteComplete is a result indicating that the deletion action has // completed, and that the resource has now been deleted. type deleteComplete struct { - actionComplete + actionComplete //nolint:unused } func (r deleteComplete) Result() (result reconcile.Result, err error) { diff --git a/controllers/metal3.io/baremetalhost_controller.go b/controllers/metal3.io/baremetalhost_controller.go index 6b68f7f4b5..e22726a2d7 100644 --- a/controllers/metal3.io/baremetalhost_controller.go +++ b/controllers/metal3.io/baremetalhost_controller.go @@ -75,7 +75,6 @@ type reconcileInfo struct { request ctrl.Request bmcCredsSecret *corev1.Secret events []corev1.Event - errorMessage string postSaveCallbacks []func() } @@ -438,7 +437,7 @@ func clearRebootAnnotations(host *metal3api.BareMetalHost) (dirty bool) { // which means we don't inspect even in Inspecting state. func inspectionDisabled(host *metal3api.BareMetalHost) bool { annotations := host.GetAnnotations() - return annotations[metal3api.InspectAnnotationPrefix] == "disabled" + return annotations[metal3api.InspectAnnotationPrefix] == metal3api.InspectAnnotationValueDisabled } // hasInspectAnnotation checks for existence of inspect.metal3.io annotation @@ -446,7 +445,7 @@ func inspectionDisabled(host *metal3api.BareMetalHost) bool { func hasInspectAnnotation(host *metal3api.BareMetalHost) bool { annotations := host.GetAnnotations() if annotations != nil { - if expect, ok := annotations[metal3api.InspectAnnotationPrefix]; ok && expect != "disabled" { + if expect, ok := annotations[metal3api.InspectAnnotationPrefix]; ok && expect != metal3api.InspectAnnotationValueDisabled { return true } } diff --git a/controllers/metal3.io/bmceventsubscription_controller.go b/controllers/metal3.io/bmceventsubscription_controller.go index 1fe3c27314..89311557bc 100644 --- a/controllers/metal3.io/bmceventsubscription_controller.go +++ b/controllers/metal3.io/bmceventsubscription_controller.go @@ -37,7 +37,6 @@ import ( metal3api "github.com/metal3-io/baremetal-operator/apis/metal3.io/v1alpha1" "github.com/metal3-io/baremetal-operator/pkg/provisioner" - "github.com/metal3-io/baremetal-operator/pkg/secretutils" "github.com/metal3-io/baremetal-operator/pkg/utils" ) @@ -88,7 +87,7 @@ func (r *BMCEventSubscriptionReconciler) Reconcile(ctx context.Context, request if k8serrors.IsNotFound(err) { reqLogger.Error(err, "baremetalhost not found", "host", subscription.Spec.HostName) - message := fmt.Sprintf("baremetal host \"%s\"", subscription.Status.Error) + message := fmt.Sprintf("baremetal host %q", subscription.Status.Error) return r.handleError(ctx, subscription, err, message, true) } // Error reading the object - requeue the request. @@ -235,10 +234,6 @@ func (r *BMCEventSubscriptionReconciler) getProvisioner(request ctrl.Request, ho return prov, ready, nil } -func (r *BMCEventSubscriptionReconciler) secretManager(log logr.Logger) secretutils.SecretManager { - return secretutils.NewSecretManager(log, r.Client, r.APIReader) -} - func (r *BMCEventSubscriptionReconciler) getHTTPHeaders(subscription metal3api.BMCEventSubscription) ([]map[string]string, error) { headers := []map[string]string{} diff --git a/controllers/metal3.io/host_config_data.go b/controllers/metal3.io/host_config_data.go index 8b66856510..0a298e24d9 100644 --- a/controllers/metal3.io/host_config_data.go +++ b/controllers/metal3.io/host_config_data.go @@ -93,7 +93,7 @@ func (hcd *hostConfigData) NetworkData() (string, error) { return networkDataRaw, err } -// PreprovisioningNetworkData get preprovisioning network configuration +// PreprovisioningNetworkData get preprovisioning network configuration. func (hcd *hostConfigData) PreprovisioningNetworkData() (string, error) { if hcd.host.Spec.PreprovisioningNetworkDataName == "" { return "", nil @@ -113,7 +113,7 @@ func (hcd *hostConfigData) PreprovisioningNetworkData() (string, error) { return networkDataRaw, err } -// MetaData get host metatdata +// MetaData get host metatdata. func (hcd *hostConfigData) MetaData() (string, error) { if hcd.host.Spec.MetaData == nil { hcd.log.Info("MetaData is not set returning empty(nil) data") diff --git a/controllers/metal3.io/host_config_data_test.go b/controllers/metal3.io/host_config_data_test.go index b80d3e1b0c..f763a6e8a7 100644 --- a/controllers/metal3.io/host_config_data_test.go +++ b/controllers/metal3.io/host_config_data_test.go @@ -2,7 +2,6 @@ package controllers import ( "context" - goctx "context" "encoding/base64" "fmt" "testing" @@ -336,10 +335,10 @@ func TestProvisionWithHostConfig(t *testing.T) { tc.Host.Spec.Online = true c := fakeclient.NewClientBuilder().WithObjects(tc.Host).Build() - c.Create(goctx.TODO(), testBMCSecret) - c.Create(goctx.TODO(), tc.UserDataSecret) - c.Create(goctx.TODO(), tc.NetworkDataSecret) - c.Create(goctx.TODO(), tc.PreprovNetworkDataSecret) + c.Create(context.TODO(), testBMCSecret) + c.Create(context.TODO(), tc.UserDataSecret) + c.Create(context.TODO(), tc.NetworkDataSecret) + c.Create(context.TODO(), tc.PreprovNetworkDataSecret) baselog := ctrl.Log.WithName("controllers").WithName("BareMetalHost") hcd := &hostConfigData{ host: tc.Host, diff --git a/pkg/hardwareutils/bmc/access.go b/pkg/hardwareutils/bmc/access.go index f00770f6c9..73eaa7c721 100644 --- a/pkg/hardwareutils/bmc/access.go +++ b/pkg/hardwareutils/bmc/access.go @@ -20,7 +20,7 @@ var factories = map[string]AccessDetailsFactory{} // with optional scheme extensions. // // RegisterFactory("bmcname", theFunc, []string{"http", "https"}) -// maps "bmcname", "bmcname+http", and "bmcname+https" to theFunc +// maps "bmcname", "bmcname+http", and "bmcname+https" to theFunc. func RegisterFactory(name string, factory AccessDetailsFactory, schemes []string) { factories[name] = factory @@ -91,7 +91,6 @@ type AccessDetails interface { } func GetParsedURL(address string) (parsedURL *url.URL, err error) { - parsedURL, err = url.Parse(address) if err != nil { // We failed to parse the URL, but it may just be a host or @@ -117,14 +116,13 @@ func GetParsedURL(address string) (parsedURL *url.URL, err error) { parsedURL, err = url.Parse(strings.Replace(address, ":", "://", 1)) if err != nil { return nil, errors.Wrap(err, "failed to parse BMC address information") - } } if parsedURL.Scheme == "" { if parsedURL.Hostname() == "" { // If there was no scheme at all, the hostname was // interpreted as a path. - parsedURL, err = url.Parse(strings.Join([]string{"ipmi://", address}, "")) + parsedURL, err = url.Parse("ipmi://" + address) if err != nil { return nil, errors.Wrap(err, "failed to parse BMC address information") } @@ -143,7 +141,6 @@ func GetParsedURL(address string) (parsedURL *url.URL, err error) { // NewAccessDetails creates an AccessDetails structure from the URL // for a BMC. func NewAccessDetails(address string, disableCertificateVerification bool) (AccessDetails, error) { - if address == "" { return nil, errors.New("missing BMC address") } @@ -162,7 +159,6 @@ func NewAccessDetails(address string, disableCertificateVerification bool) (Acce } func checkDNSValid(address string) error { - // Allowing empty BMC address if address == "" { return nil diff --git a/pkg/hardwareutils/bmc/access_test.go b/pkg/hardwareutils/bmc/access_test.go index 2ed2a31947..420b57c627 100644 --- a/pkg/hardwareutils/bmc/access_test.go +++ b/pkg/hardwareutils/bmc/access_test.go @@ -1185,7 +1185,7 @@ func TestDriverInfo(t *testing.T) { t.Fatalf("unexpected parse error: %v", err) } di := acc.DriverInfo(Credentials{}) - //If a key is present when it should not, this will catch it + // If a key is present when it should not, this will catch it if len(di) != len(tc.expects) { t.Fatalf("Number of items do not match: %v and %v, %#v", len(di), len(tc.expects), di) diff --git a/pkg/hardwareutils/bmc/credentials.go b/pkg/hardwareutils/bmc/credentials.go index cbf28a50f2..da97fe3d64 100644 --- a/pkg/hardwareutils/bmc/credentials.go +++ b/pkg/hardwareutils/bmc/credentials.go @@ -6,7 +6,7 @@ type Credentials struct { Password string } -// Validate returns an error if the credentials are invalid +// Validate returns an error if the credentials are invalid. func (creds Credentials) Validate() error { if creds.Username == "" { return &CredentialsValidationError{message: "Missing BMC connection detail 'username' in credentials"} diff --git a/pkg/hardwareutils/bmc/errors.go b/pkg/hardwareutils/bmc/errors.go index e018fa66b6..a1d96ff92a 100644 --- a/pkg/hardwareutils/bmc/errors.go +++ b/pkg/hardwareutils/bmc/errors.go @@ -17,7 +17,7 @@ func (e UnknownBMCTypeError) Error() string { } // CredentialsValidationError is returned when the provided BMC credentials -// are invalid (e.g. null) +// are invalid (e.g. null). type CredentialsValidationError struct { message string } diff --git a/pkg/hardwareutils/bmc/ibmc.go b/pkg/hardwareutils/bmc/ibmc.go index 01e85d8dda..24227b3959 100644 --- a/pkg/hardwareutils/bmc/ibmc.go +++ b/pkg/hardwareutils/bmc/ibmc.go @@ -6,8 +6,14 @@ import ( "strings" ) +const ( + noRaid = "no-raid" + ibmc = "ibmc" + ipxe = "ipxe" +) + func init() { - RegisterFactory("ibmc", newIbmcAccessDetails, []string{"http", "https"}) + RegisterFactory(ibmc, newIbmcAccessDetails, []string{"http", "https"}) } func newIbmcAccessDetails(parsedURL *url.URL, disableCertificateVerification bool) (AccessDetails, error) { @@ -39,7 +45,7 @@ func (a *ibmcAccessDetails) NeedsMAC() bool { } func (a *ibmcAccessDetails) Driver() string { - return "ibmc" + return ibmc } func (a *ibmcAccessDetails) DisableCertificateVerification() bool { @@ -54,7 +60,6 @@ const ibmcDefaultScheme = "https" // expected to add any other information that might be needed (such as // the kernel and ramdisk locations). func (a *ibmcAccessDetails) DriverInfo(bmcCreds Credentials) map[string]interface{} { - ibmcAddress := []string{} schemes := strings.Split(a.bmcType, "+") if len(schemes) > 1 { @@ -84,7 +89,7 @@ func (a *ibmcAccessDetails) BIOSInterface() string { } func (a *ibmcAccessDetails) BootInterface() string { - return "ipxe" + return ipxe } func (a *ibmcAccessDetails) FirmwareInterface() string { @@ -92,15 +97,15 @@ func (a *ibmcAccessDetails) FirmwareInterface() string { } func (a *ibmcAccessDetails) ManagementInterface() string { - return "ibmc" + return ibmc } func (a *ibmcAccessDetails) PowerInterface() string { - return "ibmc" + return ibmc } func (a *ibmcAccessDetails) RAIDInterface() string { - return "no-raid" + return noRaid } func (a *ibmcAccessDetails) VendorInterface() string { diff --git a/pkg/hardwareutils/bmc/idrac.go b/pkg/hardwareutils/bmc/idrac.go index bddc02677e..3744c44a47 100644 --- a/pkg/hardwareutils/bmc/idrac.go +++ b/pkg/hardwareutils/bmc/idrac.go @@ -5,8 +5,14 @@ import ( "strings" ) +const ( + enabled = "Enabled" + disabled = "Disabled" + idrac = "idrac" +) + func init() { - RegisterFactory("idrac", newIDRACAccessDetails, []string{"http", "https"}) + RegisterFactory(idrac, newIDRACAccessDetails, []string{"http", "https"}) } func newIDRACAccessDetails(parsedURL *url.URL, disableCertificateVerification bool) (AccessDetails, error) { @@ -38,7 +44,7 @@ func (a *iDracAccessDetails) NeedsMAC() bool { } func (a *iDracAccessDetails) Driver() string { - return "idrac" + return idrac } func (a *iDracAccessDetails) DisableCertificateVerification() bool { @@ -79,7 +85,7 @@ func (a *iDracAccessDetails) BIOSInterface() string { } func (a *iDracAccessDetails) BootInterface() string { - return "ipxe" + return ipxe } func (a *iDracAccessDetails) FirmwareInterface() string { @@ -124,9 +130,9 @@ func (a *iDracAccessDetails) BuildBIOSSettings(firmwareConfig *FirmwareConfig) ( var value string if firmwareConfig.VirtualizationEnabled != nil { - value = "Disabled" + value = disabled if *firmwareConfig.VirtualizationEnabled { - value = "Enabled" + value = enabled } settings = append(settings, map[string]string{ @@ -137,9 +143,9 @@ func (a *iDracAccessDetails) BuildBIOSSettings(firmwareConfig *FirmwareConfig) ( } if firmwareConfig.SimultaneousMultithreadingEnabled != nil { - value = "Disabled" + value = disabled if *firmwareConfig.SimultaneousMultithreadingEnabled { - value = "Enabled" + value = enabled } settings = append(settings, map[string]string{ @@ -150,9 +156,9 @@ func (a *iDracAccessDetails) BuildBIOSSettings(firmwareConfig *FirmwareConfig) ( } if firmwareConfig.SriovEnabled != nil { - value = "Disabled" + value = disabled if *firmwareConfig.SriovEnabled { - value = "Enabled" + value = enabled } settings = append(settings, map[string]string{ diff --git a/pkg/hardwareutils/bmc/idrac_virtualmedia.go b/pkg/hardwareutils/bmc/idrac_virtualmedia.go index 79ffa57ed9..8f6f48875f 100644 --- a/pkg/hardwareutils/bmc/idrac_virtualmedia.go +++ b/pkg/hardwareutils/bmc/idrac_virtualmedia.go @@ -5,6 +5,11 @@ import ( "net/url" ) +const ( + idracRedfish = "idrac-redfish" + redfish = "redfish" +) + func init() { schemes := []string{"http", "https"} RegisterFactory("idrac-virtualmedia", newRedfishiDracVirtualMediaAccessDetails, schemes) @@ -65,11 +70,11 @@ func (a *redfishiDracVirtualMediaAccessDetails) DriverInfo(bmcCreds Credentials) // iDrac Virtual Media Overrides func (a *redfishiDracVirtualMediaAccessDetails) Driver() string { - return "idrac" + return idrac } func (a *redfishiDracVirtualMediaAccessDetails) BIOSInterface() string { - return "idrac-redfish" + return idracRedfish } func (a *redfishiDracVirtualMediaAccessDetails) BootInterface() string { @@ -77,24 +82,24 @@ func (a *redfishiDracVirtualMediaAccessDetails) BootInterface() string { } func (a *redfishiDracVirtualMediaAccessDetails) FirmwareInterface() string { - return "redfish" + return redfish } func (a *redfishiDracVirtualMediaAccessDetails) ManagementInterface() string { - return "idrac-redfish" + return idracRedfish } func (a *redfishiDracVirtualMediaAccessDetails) PowerInterface() string { - return "idrac-redfish" + return idracRedfish } func (a *redfishiDracVirtualMediaAccessDetails) RAIDInterface() string { - return "idrac-redfish" + return idracRedfish } func (a *redfishiDracVirtualMediaAccessDetails) VendorInterface() string { // NOTE(dtantsur): the idrac hardware type defaults to WSMAN vendor, we need to use the Redfish implementation. - return "idrac-redfish" + return idracRedfish } func (a *redfishiDracVirtualMediaAccessDetails) SupportsSecureBoot() bool { diff --git a/pkg/hardwareutils/bmc/ilo4.go b/pkg/hardwareutils/bmc/ilo4.go index 6ccc68b1ac..993ee08aa2 100644 --- a/pkg/hardwareutils/bmc/ilo4.go +++ b/pkg/hardwareutils/bmc/ilo4.go @@ -64,7 +64,6 @@ func (a *iLOAccessDetails) DisableCertificateVerification() bool { // expected to add any other information that might be needed (such as // the kernel and ramdisk locations). func (a *iLOAccessDetails) DriverInfo(bmcCreds Credentials) map[string]interface{} { - result := map[string]interface{}{ "ilo_username": bmcCreds.Username, "ilo_password": bmcCreds.Password, @@ -89,9 +88,8 @@ func (a *iLOAccessDetails) BIOSInterface() string { func (a *iLOAccessDetails) BootInterface() string { if a.useVirtualMedia { return "ilo-virtual-media" - } else { - return "ilo-ipxe" } + return "ilo-ipxe" } func (a *iLOAccessDetails) FirmwareInterface() string { @@ -107,7 +105,7 @@ func (a *iLOAccessDetails) PowerInterface() string { } func (a *iLOAccessDetails) RAIDInterface() string { - return "no-raid" + return noRaid } func (a *iLOAccessDetails) VendorInterface() string { @@ -134,9 +132,9 @@ func (a *iLOAccessDetails) BuildBIOSSettings(firmwareConfig *FirmwareConfig) (se var value string if firmwareConfig.VirtualizationEnabled != nil { - value = "Disabled" + value = disabled if *firmwareConfig.VirtualizationEnabled { - value = "Enabled" + value = enabled } settings = append(settings, map[string]string{ @@ -147,9 +145,9 @@ func (a *iLOAccessDetails) BuildBIOSSettings(firmwareConfig *FirmwareConfig) (se } if firmwareConfig.SimultaneousMultithreadingEnabled != nil { - value = "Disabled" + value = disabled if *firmwareConfig.SimultaneousMultithreadingEnabled { - value = "Enabled" + value = enabled } settings = append(settings, map[string]string{ @@ -160,9 +158,9 @@ func (a *iLOAccessDetails) BuildBIOSSettings(firmwareConfig *FirmwareConfig) (se } if firmwareConfig.SriovEnabled != nil { - value = "Disabled" + value = disabled if *firmwareConfig.SriovEnabled { - value = "Enabled" + value = enabled } settings = append(settings, map[string]string{ diff --git a/pkg/hardwareutils/bmc/ilo5.go b/pkg/hardwareutils/bmc/ilo5.go index e79bf44223..5bb8de769a 100644 --- a/pkg/hardwareutils/bmc/ilo5.go +++ b/pkg/hardwareutils/bmc/ilo5.go @@ -52,7 +52,6 @@ func (a *iLO5AccessDetails) DisableCertificateVerification() bool { // expected to add any other information that might be needed (such as // the kernel and ramdisk locations). func (a *iLO5AccessDetails) DriverInfo(bmcCreds Credentials) map[string]interface{} { - result := map[string]interface{}{ "ilo_username": bmcCreds.Username, "ilo_password": bmcCreds.Password, @@ -118,9 +117,9 @@ func (a *iLO5AccessDetails) BuildBIOSSettings(firmwareConfig *FirmwareConfig) (s var value string if firmwareConfig.VirtualizationEnabled != nil { - value = "Disabled" + value = disabled if *firmwareConfig.VirtualizationEnabled { - value = "Enabled" + value = enabled } settings = append(settings, map[string]string{ @@ -131,9 +130,9 @@ func (a *iLO5AccessDetails) BuildBIOSSettings(firmwareConfig *FirmwareConfig) (s } if firmwareConfig.SimultaneousMultithreadingEnabled != nil { - value = "Disabled" + value = disabled if *firmwareConfig.SimultaneousMultithreadingEnabled { - value = "Enabled" + value = enabled } settings = append(settings, map[string]string{ @@ -144,9 +143,9 @@ func (a *iLO5AccessDetails) BuildBIOSSettings(firmwareConfig *FirmwareConfig) (s } if firmwareConfig.SriovEnabled != nil { - value = "Disabled" + value = disabled if *firmwareConfig.SriovEnabled { - value = "Enabled" + value = enabled } settings = append(settings, map[string]string{ diff --git a/pkg/hardwareutils/bmc/ipmi.go b/pkg/hardwareutils/bmc/ipmi.go index eb30a35fd9..1d66551793 100644 --- a/pkg/hardwareutils/bmc/ipmi.go +++ b/pkg/hardwareutils/bmc/ipmi.go @@ -94,7 +94,7 @@ func (a *ipmiAccessDetails) BIOSInterface() string { } func (a *ipmiAccessDetails) BootInterface() string { - return "ipxe" + return ipxe } func (a *ipmiAccessDetails) FirmwareInterface() string { @@ -110,7 +110,7 @@ func (a *ipmiAccessDetails) PowerInterface() string { } func (a *ipmiAccessDetails) RAIDInterface() string { - return "no-raid" + return noRaid } func (a *ipmiAccessDetails) VendorInterface() string { diff --git a/pkg/hardwareutils/bmc/irmc.go b/pkg/hardwareutils/bmc/irmc.go index f87c71472c..a3368d8952 100644 --- a/pkg/hardwareutils/bmc/irmc.go +++ b/pkg/hardwareutils/bmc/irmc.go @@ -4,6 +4,11 @@ import ( "net/url" ) +const ( + FalseStr = "False" + TrueStr = "True" +) + func init() { RegisterFactory("irmc", newIRMCAccessDetails, []string{}) } @@ -75,7 +80,7 @@ func (a *iRMCAccessDetails) BIOSInterface() string { } func (a *iRMCAccessDetails) BootInterface() string { - return "ipxe" + return ipxe } func (a *iRMCAccessDetails) FirmwareInterface() string { @@ -118,9 +123,9 @@ func (a *iRMCAccessDetails) BuildBIOSSettings(firmwareConfig *FirmwareConfig) (s var value string if firmwareConfig.VirtualizationEnabled != nil { - value = "False" + value = FalseStr if *firmwareConfig.VirtualizationEnabled { - value = "True" + value = TrueStr } settings = append(settings, map[string]string{ @@ -131,9 +136,9 @@ func (a *iRMCAccessDetails) BuildBIOSSettings(firmwareConfig *FirmwareConfig) (s } if firmwareConfig.SimultaneousMultithreadingEnabled != nil { - value = "False" + value = FalseStr if *firmwareConfig.SimultaneousMultithreadingEnabled { - value = "True" + value = TrueStr } settings = append(settings, map[string]string{ @@ -144,9 +149,9 @@ func (a *iRMCAccessDetails) BuildBIOSSettings(firmwareConfig *FirmwareConfig) (s } if firmwareConfig.SriovEnabled != nil { - value = "False" + value = FalseStr if *firmwareConfig.SriovEnabled { - value = "True" + value = TrueStr } settings = append(settings, map[string]string{ diff --git a/pkg/hardwareutils/bmc/redfish.go b/pkg/hardwareutils/bmc/redfish.go index 7fccbf712b..411d4157d0 100644 --- a/pkg/hardwareutils/bmc/redfish.go +++ b/pkg/hardwareutils/bmc/redfish.go @@ -8,7 +8,7 @@ import ( func init() { schemes := []string{"http", "https"} - RegisterFactory("redfish", newRedfishAccessDetails, schemes) + RegisterFactory(redfish, newRedfishAccessDetails, schemes) RegisterFactory("ilo5-redfish", newRedfishAccessDetails, schemes) RegisterFactory("idrac-redfish", newRedfishiDracAccessDetails, schemes) } @@ -58,7 +58,7 @@ func (a *redfishAccessDetails) NeedsMAC() bool { } func (a *redfishAccessDetails) Driver() string { - return "redfish" + return redfish } func (a *redfishAccessDetails) DisableCertificateVerification() bool { @@ -102,13 +102,13 @@ func (a *redfishAccessDetails) BIOSInterface() string { return "" } -// That can be either pxe or redfish-virtual-media +// That can be either pxe or redfish-virtual-media. func (a *redfishAccessDetails) BootInterface() string { - return "ipxe" + return ipxe } func (a *redfishAccessDetails) FirmwareInterface() string { - return "redfish" + return redfish } func (a *redfishAccessDetails) ManagementInterface() string { @@ -120,7 +120,7 @@ func (a *redfishAccessDetails) PowerInterface() string { } func (a *redfishAccessDetails) RAIDInterface() string { - return "redfish" + return redfish } func (a *redfishAccessDetails) VendorInterface() string { @@ -146,38 +146,38 @@ func (a *redfishAccessDetails) BuildBIOSSettings(firmwareConfig *FirmwareConfig) return nil, nil } -// iDrac Redfish Overrides +// iDrac Redfish Overrides. func (a *redfishiDracAccessDetails) Driver() string { - return "idrac" + return idrac } func (a *redfishiDracAccessDetails) BIOSInterface() string { - return "idrac-redfish" + return idracRedfish } func (a *redfishiDracAccessDetails) BootInterface() string { - return "ipxe" + return ipxe } func (a *redfishiDracAccessDetails) FirmwareInterface() string { - return "redfish" + return redfish } func (a *redfishiDracAccessDetails) ManagementInterface() string { - return "idrac-redfish" + return ipxe } func (a *redfishiDracAccessDetails) PowerInterface() string { - return "idrac-redfish" + return idracRedfish } func (a *redfishiDracAccessDetails) RAIDInterface() string { - return "idrac-redfish" + return idracRedfish } func (a *redfishiDracAccessDetails) VendorInterface() string { // NOTE(dtantsur): the idrac hardware type defaults to WSMAN vendor, we need to use the Redfish implementation. - return "idrac-redfish" + return idracRedfish } func (a *redfishiDracAccessDetails) BuildBIOSSettings(firmwareConfig *FirmwareConfig) (settings []map[string]string, err error) { diff --git a/pkg/hardwareutils/bmc/redfish_virtualmedia.go b/pkg/hardwareutils/bmc/redfish_virtualmedia.go index 41a5f4b918..3e46626eb6 100644 --- a/pkg/hardwareutils/bmc/redfish_virtualmedia.go +++ b/pkg/hardwareutils/bmc/redfish_virtualmedia.go @@ -40,7 +40,7 @@ func (a *redfishVirtualMediaAccessDetails) NeedsMAC() bool { } func (a *redfishVirtualMediaAccessDetails) Driver() string { - return "redfish" + return redfish } func (a *redfishVirtualMediaAccessDetails) DisableCertificateVerification() bool { @@ -76,7 +76,7 @@ func (a *redfishVirtualMediaAccessDetails) BootInterface() string { } func (a *redfishVirtualMediaAccessDetails) FirmwareInterface() string { - return "redfish" + return redfish } func (a *redfishVirtualMediaAccessDetails) ManagementInterface() string { @@ -88,7 +88,7 @@ func (a *redfishVirtualMediaAccessDetails) PowerInterface() string { } func (a *redfishVirtualMediaAccessDetails) RAIDInterface() string { - return "redfish" + return redfish } func (a *redfishVirtualMediaAccessDetails) VendorInterface() string { diff --git a/pkg/provisioner/demo/demo.go b/pkg/provisioner/demo/demo.go index edc5a91e0b..cf82e8794e 100644 --- a/pkg/provisioner/demo/demo.go +++ b/pkg/provisioner/demo/demo.go @@ -14,8 +14,6 @@ import ( ) var log = logz.New().WithName("provisioner").WithName("demo") -var deprovisionRequeueDelay = time.Second * 10 -var provisionRequeueDelay = time.Second * 10 const ( // RegistrationErrorHost is a host that fails the registration @@ -250,38 +248,8 @@ func (p *demoProvisioner) Provision(_ provisioner.ProvisionData, _ bool) (result // multiple times, and should return true for its dirty flag until the // deprovisioning operation is completed. func (p *demoProvisioner) Deprovision(_ bool) (result provisioner.Result, err error) { - hostName := p.objectMeta.Name - switch hostName { - default: - return result, nil - } - - // p.log.Info("ensuring host is removed") - - // result.RequeueAfter = deprovisionRequeueDelay - - // // NOTE(dhellmann): In order to simulate a multi-step process, - // // modify some of the status data structures. This is likely not - // // necessary once we really have Demo doing the deprovisioning - // // and we can monitor it's status. - - // if p.host.Status.HardwareDetails != nil { - // p.publisher("DeprovisionStarted", "Image deprovisioning started") - // p.log.Info("clearing hardware details") - // p.host.Status.HardwareDetails = nil - // result.Dirty = true - // return result, nil - // } - - // if p.host.Status.Provisioning.ID != "" { - // p.log.Info("clearing provisioning id") - // p.host.Status.Provisioning.ID = "" - // result.Dirty = true - // return result, nil - // } - - // p.publisher("DeprovisionComplete", "Image deprovisioning completed") - // return result, nil + p.log.Info("deprovisioning host") + return result, nil } // Delete removes the host from the provisioning system. It may be @@ -305,44 +273,18 @@ func (p *demoProvisioner) Detach() (result provisioner.Result, err error) { // PowerOn ensures the server is powered on independently of any image // provisioning operation. func (p *demoProvisioner) PowerOn(_ bool) (result provisioner.Result, err error) { - hostName := p.objectMeta.Name - switch hostName { - default: - return result, nil - } - - // p.log.Info("ensuring host is powered on") - - // if !p.host.Status.PoweredOn { - // p.host.Status.PoweredOn = true - // result.Dirty = true - // return result, nil - // } - - // return result, nil + p.log.Info("powering on host") + return result, nil } // PowerOff ensures the server is powered off independently of any image // provisioning operation. func (p *demoProvisioner) PowerOff(_ metal3api.RebootMode, _ bool) (result provisioner.Result, err error) { - hostName := p.objectMeta.Name - switch hostName { - default: - return result, nil - } - - // p.log.Info("ensuring host is powered off") - - // if p.host.Status.PoweredOn { - // p.host.Status.PoweredOn = false - // result.Dirty = true - // return result, nil - // } - - // return result, nil + p.log.Info("powering off host") + return result, nil } -// TryInit always returns true for the demo provisioner +// TryInit always returns true for the demo provisioner. func (p *demoProvisioner) TryInit() (result bool, err error) { return true, nil } diff --git a/pkg/provisioner/fixture/fixture.go b/pkg/provisioner/fixture/fixture.go index 1d43c6bca6..693c993da7 100644 --- a/pkg/provisioner/fixture/fixture.go +++ b/pkg/provisioner/fixture/fixture.go @@ -325,7 +325,7 @@ func (p *fixtureProvisioner) PowerOff(_ metal3api.RebootMode, _ bool) (result pr return result, nil } -// TryInit returns the current availability status of the provisioner +// TryInit returns the current availability status of the provisioner. func (p *fixtureProvisioner) TryInit() (result bool, err error) { p.log.Info("checking provisioner status") diff --git a/pkg/provisioner/ironic/clients/features.go b/pkg/provisioner/ironic/clients/features.go index b98cc65c97..888c7a2130 100644 --- a/pkg/provisioner/ironic/clients/features.go +++ b/pkg/provisioner/ironic/clients/features.go @@ -18,7 +18,7 @@ type AvailableFeatures struct { // conservative when updating this value since doing so unconditionally breaks // operators of older Ironic, even if the feature we need is optional. // Update docs/configuration.md when updating the version. -// Version 1.81 allows retrival of Node inventory +// Version 1.81 allows retrival of Node inventory. const baseline = "1.81" func GetAvailableFeatures(client *gophercloud.ServiceClient) (features AvailableFeatures, err error) { @@ -28,7 +28,7 @@ func GetAvailableFeatures(client *gophercloud.ServiceClient) (features Available } if mvs.MaxMajor != 1 || mvs.MaxMinor < 81 { - err = fmt.Errorf("Ironic API 1.81 or newer is required, got %d.%d", mvs.MaxMajor, mvs.MaxMinor) + err = fmt.Errorf("ironic API 1.81 or newer is required, got %d.%d", mvs.MaxMajor, mvs.MaxMinor) return } diff --git a/pkg/provisioner/ironic/dependencies.go b/pkg/provisioner/ironic/dependencies.go index 72643a8e20..c1c62e9099 100644 --- a/pkg/provisioner/ironic/dependencies.go +++ b/pkg/provisioner/ironic/dependencies.go @@ -7,7 +7,7 @@ import ( "github.com/metal3-io/baremetal-operator/pkg/provisioner/ironic/clients" ) -// TryInit checks if the provisioning backend is available +// TryInit checks if the provisioning backend is available. func (p *ironicProvisioner) TryInit() (ready bool, err error) { p.debugLog.Info("verifying ironic provisioner dependencies") diff --git a/pkg/provisioner/ironic/devicehints/devicehints.go b/pkg/provisioner/ironic/devicehints/devicehints.go index e1f68960bb..db575c2d1e 100644 --- a/pkg/provisioner/ironic/devicehints/devicehints.go +++ b/pkg/provisioner/ironic/devicehints/devicehints.go @@ -49,9 +49,9 @@ func MakeHintMap(source *metal3api.RootDeviceHints) map[string]string { } switch { case source.Rotational == nil: - case *source.Rotational == true: + case *source.Rotational: hints["rotational"] = "true" - case *source.Rotational == false: + case !*source.Rotational: hints["rotational"] = "false" } diff --git a/pkg/provisioner/ironic/ironic.go b/pkg/provisioner/ironic/ironic.go index 75aaed4b6c..190e54f5c2 100644 --- a/pkg/provisioner/ironic/ironic.go +++ b/pkg/provisioner/ironic/ironic.go @@ -506,10 +506,7 @@ func (p *ironicProvisioner) ValidateManagementAccess(data provisioner.Management if !success { return } - // ironicNode, err = nodes.Get(p.client, p.status.ID).Extract() - // if err != nil { - // return result, errors.Wrap(err, "failed to get provisioning state in ironic") - // } + p.log.Info("current provision state", "lastError", ironicNode.LastError, "current", ironicNode.ProvisionState, diff --git a/pkg/provisioner/ironic/testserver/ironic.go b/pkg/provisioner/ironic/testserver/ironic.go index 597d775662..da1f4650e4 100644 --- a/pkg/provisioner/ironic/testserver/ironic.go +++ b/pkg/provisioner/ironic/testserver/ironic.go @@ -13,6 +13,8 @@ import ( ) // IronicMock is a test server that implements Ironic's semantics. +const v1node = "/v1/nodes/" + type IronicMock struct { *MockServer CreatedNodes int @@ -20,6 +22,7 @@ type IronicMock struct { // NewIronic builds an ironic mock server. func NewIronic(t *testing.T) *IronicMock { + t.Helper() server := New(t, "ironic").AddDefaultResponse("/v1/?", "", http.StatusOK, versionedRootResult) return &IronicMock{ MockServer: server, @@ -28,6 +31,7 @@ func NewIronic(t *testing.T) *IronicMock { } const validateResult = `{"boot": {"result": true}, "deploy": {"result": true}, "power": {"result": true}}` +const maintenance = "/maintenance" // NOTE(dtantsur): the actual result is much longer, but we only potentially care about versions. const versionedRootResult = ` @@ -42,7 +46,7 @@ const versionedRootResult = ` } }` -// WithDefaultResponses sets a valid answer for all the API calls +// WithDefaultResponses sets a valid answer for all the API calls. func (m *IronicMock) WithDefaultResponses() *IronicMock { m.AddDefaultResponseJSON("/v1/nodes/{id}", "", http.StatusOK, nodes.Node{ UUID: "{id}", @@ -64,7 +68,7 @@ func (m *IronicMock) Endpoint() string { return m.MockServer.Endpoint() } -// NotReady configures the server with an error response for /v1/ overriding the default response +// NotReady configures the server with an error response for /v1/ overriding the default response. func (m *IronicMock) NotReady(errorCode int) *IronicMock { m.ErrorResponse("/v1/", errorCode) return m @@ -108,30 +112,30 @@ func (m *IronicMock) buildURL(url string, method string) string { // Delete configures the server with a valid response for [DELETE] /v1/nodes/ on the // specific node id. func (m *IronicMock) Delete(id string) *IronicMock { - m.ResponseWithCode(m.buildURL("/v1/nodes/"+id, http.MethodDelete), "", http.StatusAccepted) + m.ResponseWithCode(m.buildURL(v1node+id, http.MethodDelete), "", http.StatusAccepted) return m } // DeleteError configures the server with an error response for [DELETE] /v1/nodes/. func (m *IronicMock) DeleteError(id string, errorCode int) *IronicMock { - m.ResponseWithCode(m.buildURL("/v1/nodes/"+id, http.MethodDelete), "", errorCode) + m.ResponseWithCode(m.buildURL(v1node+id, http.MethodDelete), "", errorCode) return m } // Node configures the server with a valid response for /v1/nodes/{name,uuid}. func (m *IronicMock) Node(node nodes.Node) *IronicMock { if node.UUID != "" { - m.ResponseJSON(m.buildURL("/v1/nodes/"+node.UUID, http.MethodGet), node) + m.ResponseJSON(m.buildURL(v1node+node.UUID, http.MethodGet), node) } if node.Name != "" { - m.ResponseJSON(m.buildURL("/v1/nodes/"+node.Name, http.MethodGet), node) + m.ResponseJSON(m.buildURL(v1node+node.Name, http.MethodGet), node) } return m } // NodeUpdateError configures configures the server with an error response for [PATCH] /v1/nodes/{id}. func (m *IronicMock) NodeUpdateError(id string, errorCode int) *IronicMock { - m.ResponseWithCode(m.buildURL("/v1/nodes/"+id, http.MethodPatch), "", errorCode) + m.ResponseWithCode(m.buildURL(v1node+id, http.MethodPatch), "", errorCode) return m } @@ -139,17 +143,17 @@ func (m *IronicMock) NodeUpdateError(id string, errorCode int) *IronicMock { // for /v1/nodes/{name,uuid}. func (m *IronicMock) NodeUpdate(node nodes.Node) *IronicMock { if node.UUID != "" { - m.ResponseJSON(m.buildURL("/v1/nodes/"+node.UUID, http.MethodPatch), node) + m.ResponseJSON(m.buildURL(v1node+node.UUID, http.MethodPatch), node) } if node.Name != "" { - m.ResponseJSON(m.buildURL("/v1/nodes/"+node.Name, http.MethodPatch), node) + m.ResponseJSON(m.buildURL(v1node+node.Name, http.MethodPatch), node) } return m } // GetLastNodeUpdateRequestFor returns the content of the last update request for the specified node. func (m *IronicMock) GetLastNodeUpdateRequestFor(id string) (updates []nodes.UpdateOperation) { - if bodyRaw, ok := m.GetLastRequestFor("/v1/nodes/"+id, http.MethodPatch); ok { + if bodyRaw, ok := m.GetLastRequestFor(v1node+id, http.MethodPatch); ok { json.Unmarshal([]byte(bodyRaw), &updates) } @@ -158,7 +162,7 @@ func (m *IronicMock) GetLastNodeUpdateRequestFor(id string) (updates []nodes.Upd // GetLastNodeStatesProvisionUpdateRequestFor returns the content of the last provisioning request for the specified node. func (m *IronicMock) GetLastNodeStatesProvisionUpdateRequestFor(id string) (update nodes.ProvisionStateOpts) { - if bodyRaw, ok := m.GetLastRequestFor("/v1/nodes/"+id+"/states/provision", http.MethodPut); ok { + if bodyRaw, ok := m.GetLastRequestFor(v1node+id+"/states/provision", http.MethodPut); ok { json.Unmarshal([]byte(bodyRaw), &update) } @@ -167,7 +171,7 @@ func (m *IronicMock) GetLastNodeStatesProvisionUpdateRequestFor(id string) (upda // NodeMaintenanceError configures configures the server with an error response for [PUT] /v1/nodes/{id}/maintenance. func (m *IronicMock) NodeMaintenanceError(id string, errorCode int) *IronicMock { - m.ResponseWithCode(m.buildURL("/v1/nodes/"+id+"/maintenance", http.MethodPut), "", errorCode) + m.ResponseWithCode(m.buildURL(v1node+id+maintenance, http.MethodPut), "", errorCode) return m } @@ -183,9 +187,9 @@ func (m *IronicMock) NodeMaintenance(node nodes.Node, expected bool) *IronicMock } if node.Name != "" { - url = m.buildURL("/v1/nodes/"+node.Name+"/maintenance", method) + url = m.buildURL(v1node+node.Name+maintenance, method) } else { - url = m.buildURL("/v1/nodes/"+node.UUID+"/maintenance", method) + url = m.buildURL(v1node+node.UUID+maintenance, method) } m.ResponseWithCode(url, "{}", http.StatusAccepted) @@ -193,7 +197,7 @@ func (m *IronicMock) NodeMaintenance(node nodes.Node, expected bool) *IronicMock } func (m *IronicMock) withNodeStatesProvision(nodeUUID string, method string) *IronicMock { - m.ResponseWithCode(m.buildURL("/v1/nodes/"+nodeUUID+"/states/provision", method), "{}", http.StatusAccepted) + m.ResponseWithCode(m.buildURL(v1node+nodeUUID+"/states/provision", method), "{}", http.StatusAccepted) return m } @@ -227,6 +231,7 @@ func (m *IronicMock) CreateNodes(callback NodeCreateCallback) *IronicMock { if r.Method != http.MethodPost { http.Error(w, fmt.Sprintf("%s not handled for %s", r.Method, r.URL), http.StatusNotImplemented) + return } bodyRaw, err := io.ReadAll(r.Body) @@ -265,7 +270,7 @@ func (m *IronicMock) CreateNodes(callback NodeCreateCallback) *IronicMock { } func (m *IronicMock) withNodeStatesPower(nodeUUID string, code int, method string) *IronicMock { - m.ResponseWithCode(m.buildURL("/v1/nodes/"+nodeUUID+"/states/power", method), "{}", code) + m.ResponseWithCode(m.buildURL(v1node+nodeUUID+"/states/power", method), "{}", code) return m } @@ -281,7 +286,7 @@ func (m *IronicMock) WithNodeStatesPowerUpdate(nodeUUID string, code int) *Ironi // WithNodeValidate configures the server with a valid response for /v1/nodes//validate. func (m *IronicMock) WithNodeValidate(nodeUUID string) *IronicMock { - m.ResponseWithCode("/v1/nodes/"+nodeUUID+"/validate", validateResult, http.StatusOK) + m.ResponseWithCode(v1node+nodeUUID+"/validate", validateResult, http.StatusOK) return m } @@ -302,7 +307,7 @@ func (m *IronicMock) Port(port ports.Port) *IronicMock { address := url.QueryEscape(port.Address) - m.ResponseJSON(m.buildURL("/v1/nodes/"+port.NodeUUID+"/ports", http.MethodGet), resp) + m.ResponseJSON(m.buildURL(v1node+port.NodeUUID+"/ports", http.MethodGet), resp) m.ResponseJSON(m.buildURL("/v1/ports", http.MethodGet), resp) m.ResponseJSON(m.buildURL("/v1/ports?address="+address, http.MethodGet), resp) m.ResponseJSON(m.buildURL("/v1/ports?address="+address+"&fields=node_uuid", http.MethodGet), resp) @@ -380,8 +385,8 @@ func (m *IronicMock) BIOSSettings(nodeUUID string) *IronicMock { Settings: settings, } - m.ResponseJSON(m.buildURL("/v1/nodes/"+nodeUUID+"/bios", http.MethodGet), resp) - m.AddDefaultResponseJSON("/v1/nodes/"+nodeUUID, "", http.StatusOK, nodes.Node{ + m.ResponseJSON(m.buildURL(v1node+nodeUUID+"/bios", http.MethodGet), resp) + m.AddDefaultResponseJSON(v1node+nodeUUID, "", http.StatusOK, nodes.Node{ UUID: nodeUUID, }) return m @@ -444,8 +449,8 @@ func (m *IronicMock) BIOSDetailSettings(nodeUUID string) *IronicMock { Settings: settings, } - m.ResponseJSON(m.buildURL("/v1/nodes/"+nodeUUID+"/bios", http.MethodGet), resp) - m.AddDefaultResponseJSON("/v1/nodes/"+nodeUUID, "", http.StatusOK, nodes.Node{ + m.ResponseJSON(m.buildURL(v1node+nodeUUID+"/bios", http.MethodGet), resp) + m.AddDefaultResponseJSON(v1node+nodeUUID, "", http.StatusOK, nodes.Node{ UUID: nodeUUID, }) return m @@ -458,12 +463,12 @@ func (m *IronicMock) NoBIOS(nodeUUID string) *IronicMock { // WithInventory configures the server with a valid response for /v1/nodes//inventory. func (m *IronicMock) WithInventory(nodeUUID string, data nodes.InventoryData) *IronicMock { - m.ResponseJSON("/v1/nodes/"+nodeUUID+"/inventory", data) + m.ResponseJSON(v1node+nodeUUID+"/inventory", data) return m } // WithInventoryFailed configures the server with an error response for /v1/nodes//inventory. func (m *IronicMock) WithInventoryFailed(nodeUUID string, errorCode int) *IronicMock { - m.ErrorResponse("/v1/nodes/"+nodeUUID+"/inventory", errorCode) + m.ErrorResponse(v1node+nodeUUID+"/inventory", errorCode) return m } diff --git a/pkg/provisioner/ironic/testserver/server.go b/pkg/provisioner/ironic/testserver/server.go index d885281a4e..01f2309106 100644 --- a/pkg/provisioner/ironic/testserver/server.go +++ b/pkg/provisioner/ironic/testserver/server.go @@ -45,14 +45,12 @@ type simpleRequest struct { // MockServer is a simple http testing server. type MockServer struct { - t *testing.T - mux *http.ServeMux - name string - Requests string - FullRequests []simpleRequest - server *httptest.Server - errorCode int - + t *testing.T + mux *http.ServeMux + name string + Requests string + FullRequests []simpleRequest + server *httptest.Server responsesByMethod map[string]map[string]response defaultResponses []defaultResponse } @@ -223,23 +221,24 @@ func (m *MockServer) defaultHandler(w http.ResponseWriter, r *http.Request) { method := r.Method for _, response := range m.defaultResponses { - if response.method == "" || response.method == method { - match := response.re.FindStringSubmatch(url) - if match == nil { - continue - } + if response.method != "" && response.method != method { + continue + } + match := response.re.FindStringSubmatch(url) + if match == nil { + continue + } - m.t.Logf("%s: found default response for %s: {%d, %s}", m.name, url, response.code, response.payload) - payload := response.payload - for i, name := range response.re.SubexpNames() { - if i != 0 && name != "" { - payload = strings.ReplaceAll(payload, "{"+name+"}", match[i]) - } + m.t.Logf("%s: found default response for %s: {%d, %s}", m.name, url, response.code, response.payload) + payload := response.payload + for i, name := range response.re.SubexpNames() { + if i != 0 && name != "" { + payload = strings.ReplaceAll(payload, "{"+name+"}", match[i]) } - - m.sendData(w, r, response.code, payload) - return } + + m.sendData(w, r, response.code, payload) + return } m.t.Logf("%s: Cannot find any default response for [%s] %s", m.name, method, url) diff --git a/test/e2e/bmc.go b/test/e2e/bmc.go index d872eb2d96..6bea16b5a4 100644 --- a/test/e2e/bmc.go +++ b/test/e2e/bmc.go @@ -7,7 +7,7 @@ import ( "gopkg.in/yaml.v2" ) -// BMC defines a BMH to use in the tests +// BMC defines a BMH to use in the tests. type BMC struct { // BMC initial username User string `yaml:"user,omitempty"` @@ -22,7 +22,7 @@ type BMC struct { // The IP address of the node // Optional. Only needed if e2eConfig variable // SSH_CHECK_PROVISIONED is true - IpAddress string `yaml:"ipAddress,omitempty"` + IPAddress string `yaml:"ipAddress,omitempty"` // Optional. Only needed if e2eConfig variable // SSH_CHECK_PROVISIONED is true SSHPort string `yaml:"sshPort,omitempty"` diff --git a/test/e2e/common.go b/test/e2e/common.go index cc5c520a1e..af84df27b6 100644 --- a/test/e2e/common.go +++ b/test/e2e/common.go @@ -17,7 +17,7 @@ import ( v1 "k8s.io/api/apps/v1" corev1 "k8s.io/api/core/v1" - apierrors "k8s.io/apimachinery/pkg/api/errors" + k8serrors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" metal3api "github.com/metal3-io/baremetal-operator/apis/metal3.io/v1alpha1" @@ -98,7 +98,6 @@ func (c *Config) Defaults() { // - Image should have name and loadBehavior be one of [mustload, tryload]. // - Intervals should be valid ginkgo intervals. func (c *Config) Validate() error { - // Image should have name and loadBehavior be one of [mustload, tryload]. for i, containerImage := range c.Images { if containerImage.Name == "" { @@ -212,7 +211,7 @@ func WaitForBmhDeleted(ctx context.Context, input WaitForBmhDeletedInput, interv err := input.Client.Get(ctx, key, bmh) // If BMH is not found, it's considered deleted, which is the desired outcome. - if apierrors.IsNotFound(err) { + if k8serrors.IsNotFound(err) { return true } g.Expect(err).NotTo(HaveOccurred()) @@ -241,7 +240,7 @@ func WaitForNamespaceDeleted(ctx context.Context, input WaitForNamespaceDeletedI key := client.ObjectKey{ Name: input.Namespace.Name, } - return apierrors.IsNotFound(input.Getter.Get(ctx, key, namespace)) + return k8serrors.IsNotFound(input.Getter.Get(ctx, key, namespace)) }, intervals...).Should(BeTrue()) } @@ -456,7 +455,7 @@ func (input *BuildAndApplyKustomizeInput) validate() error { } // BuildAndApplyKustomize takes input from BuildAndApplyKustomizeInput. It builds the provided kustomization -// and apply it to the cluster provided by clusterProxy +// and apply it to the cluster provided by clusterProxy. func BuildAndApplyKustomize(ctx context.Context, input *BuildAndApplyKustomizeInput) error { Expect(input.validate()).To(BeNil()) var err error diff --git a/test/e2e/e2e_suite_test.go b/test/e2e/e2e_suite_test.go index af80191fef..dfeb7777f2 100644 --- a/test/e2e/e2e_suite_test.go +++ b/test/e2e/e2e_suite_test.go @@ -27,7 +27,7 @@ var ( // configPath is the path to the e2e config file. configPath string - // bmcConfigPath is the path to the file whose content is the list of bmcs used in the test + // bmcConfigPath is the path to the file whose content is the list of bmcs used in the test. bmcConfigPath string // useExistingCluster instructs the test to use the current cluster instead of creating a new one (default discovery rules apply). @@ -36,7 +36,7 @@ var ( // e2eConfig to be used for this test, read from configPath. e2eConfig *Config - // bmcs to be used for this test, read from bmcConfigPath + // bmcs to be used for this test, read from bmcConfigPath. bmcs *[]BMC // artifactFolder is the folder to store e2e test artifacts. @@ -52,7 +52,7 @@ var ( // Please note that provisioning will be skipped if e2e.use-existing-cluster is provided. clusterProvider bootstrap.ClusterProvider - // the BMC instance to use in a parallel test + // the BMC instance to use in a parallel test. bmc BMC ) @@ -69,7 +69,7 @@ func TestE2e(t *testing.T) { ctrl.SetLogger(klog.Background()) // ensure the artifacts folder exists - g.Expect(os.MkdirAll(artifactFolder, 0755)).To(Succeed(), "Invalid test suite argument. Can't create e2e.artifacts-folder %q", artifactFolder) //nolint:gosec + g.Expect(os.MkdirAll(artifactFolder, 0755)).To(Succeed(), "Invalid test suite argument. Can't create e2e.artifacts-folder %q", artifactFolder) RegisterFailHandler(Fail) RunSpecs(t, "E2e Suite") diff --git a/test/e2e/live_iso_test.go b/test/e2e/live_iso_test.go index 09f307f7c0..51f8b3d32d 100644 --- a/test/e2e/live_iso_test.go +++ b/test/e2e/live_iso_test.go @@ -94,7 +94,7 @@ var _ = Describe("Live-ISO", func() { By("Verifying the node booted from live ISO image") password := e2eConfig.GetVariable("CIRROS_PASSWORD") auth := ssh.Password(password) - PerformSSHBootCheck(e2eConfig, "memory", auth, fmt.Sprintf("%s:%s", bmc.IpAddress, bmc.SSHPort)) + PerformSSHBootCheck(e2eConfig, "memory", auth, fmt.Sprintf("%s:%s", bmc.IPAddress, bmc.SSHPort)) } else { capm3_e2e.Logf("WARNING: Skipping SSH check since SSH_CHECK_PROVISIONED != true") } diff --git a/test/e2e/provisioning_and_annotation_test.go b/test/e2e/provisioning_and_annotation_test.go index dc79a0dac6..aba7ecf6f8 100644 --- a/test/e2e/provisioning_and_annotation_test.go +++ b/test/e2e/provisioning_and_annotation_test.go @@ -12,7 +12,7 @@ import ( . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" corev1 "k8s.io/api/core/v1" - apierrors "k8s.io/apimachinery/pkg/api/errors" + k8serrors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/types" "sigs.k8s.io/cluster-api/test/framework" @@ -128,7 +128,7 @@ var _ = Describe("BMH Provisioning and Annotation Management", func() { Expect(err).NotTo(HaveOccurred(), "unable to parse private key") auth := ssh.PublicKeys(signer) - PerformSSHBootCheck(e2eConfig, "disk", auth, fmt.Sprintf("%s:%s", bmc.IpAddress, bmc.SSHPort)) + PerformSSHBootCheck(e2eConfig, "disk", auth, fmt.Sprintf("%s:%s", bmc.IPAddress, bmc.SSHPort)) } else { capm3_e2e.Logf("WARNING: Skipping SSH check since SSH_CHECK_PROVISIONED != true") } @@ -180,7 +180,7 @@ var _ = Describe("BMH Provisioning and Annotation Management", func() { Name: "bmc-credentials", Namespace: namespace.Name, }, &corev1.Secret{}) - return apierrors.IsNotFound(err) + return k8serrors.IsNotFound(err) }, e2eConfig.GetIntervals(specName, "wait-secret-deletion")...).Should(BeTrue()) By("Creating a secret with BMH credentials")