Skip to content

Commit

Permalink
Merge pull request #112 from dell/su-res
Browse files Browse the repository at this point in the history
Simple update resource migration to Terraform Plugin Framework
  • Loading branch information
Krishnan-Priyanshu authored Oct 30, 2023
2 parents 98ceacd + e07dddc commit 6d7873c
Show file tree
Hide file tree
Showing 13 changed files with 845 additions and 472 deletions.
10 changes: 9 additions & 1 deletion .golangci.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,14 @@ run:
# If it's not please let us know.
# "/" will be replaced by current OS file path separator to properly work on Windows.
skip-files:
- "redfish/provider/data_source_redfish_bios.go"
- "redfish/provider/data_source_redfish_firmware_inventory.go"
- "redfish/provider/data_source_redfish_storage.go"
- "redfish/provider/data_source_redfish_system_boot.go"
- "redfish/provider/data_source_redfish_virtual_media.go"
- "redfish/provider/resource_redfish_storage_volume.go"
- "redfish/provider/resource_redfish_storage_volume.go"
- "redfish/provider/resource_redfish_bios.go"
# - ".*\\.my\\.go$"
# If set we pass it to "go list -mod={option}". From "go help modules":
# If invoked with -mod=readonly, the go command is disallowed from the implicit
Expand Down Expand Up @@ -164,7 +172,7 @@ linters-settings:
- name: cyclomatic
severity: warning
disabled: false
arguments: [10] # TBD
arguments: [20] # TBD 10
# https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#datarace
- name: datarace
severity: warning
Expand Down
4 changes: 2 additions & 2 deletions common/job_management.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ const (
// - jobURI -> URI for the job to check.
// - timeBetweenAttempts -> time to wait between attempts. I.e. 30 means 30 seconds.
// - timeout -> maximun time to wait until job is considered failed.
func WaitForJobToFinish(service *gofish.Service, jobURI string, timeBetweenAttempts int, timeout int) error {
func WaitForJobToFinish(service *gofish.Service, jobURI string, timeBetweenAttempts int64, timeout int64) error {
// Create tickers
attemptTick := time.NewTicker(time.Duration(timeBetweenAttempts) * time.Second)
timeoutTick := time.NewTicker(time.Duration(timeout) * time.Second)
Expand All @@ -44,7 +44,7 @@ func WaitForJobToFinish(service *gofish.Service, jobURI string, timeBetweenAttem
}
case <-timeoutTick.C:
log.Printf("[DEBUG] - Error. Timeout reached\n")
return fmt.Errorf("Timeout waiting for the job to finish")
return fmt.Errorf("timeout waiting for the job to finish")
}
}
}
Expand Down
202 changes: 202 additions & 0 deletions docs/resources/simple_update.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,202 @@
---
# Copyright (c) 2023 Dell Inc., or its subsidiaries. All Rights Reserved.
#
# Licensed under the Mozilla Public License Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://mozilla.org/MPL/2.0/
#
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

title: "redfish_simple_update resource"
linkTitle: "redfish_simple_update"
page_title: "redfish_simple_update Resource - terraform-provider-redfish"
subcategory: ""
description: |-
Resource for managing power.
---

# redfish_simple_update (Resource)

Resource for managing power.
This Terraform resource is used to Update the iDRAC Server. We can Read the existing version or update the same using this resource.

## Example Usage

variables.tf
```terraform
/*
Copyright (c) 2023 Dell Inc., or its subsidiaries. All Rights Reserved.
Licensed under the Mozilla Public License Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://mozilla.org/MPL/2.0/
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
variable "rack1" {
type = map(object({
user = string
password = string
endpoint = string
ssl_insecure = bool
}))
}
```

terraform.tfvars
```terraform
/*
Copyright (c) 2023 Dell Inc., or its subsidiaries. All Rights Reserved.
Licensed under the Mozilla Public License Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://mozilla.org/MPL/2.0/
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
rack1 = {
"my-server-1" = {
user = "admin"
password = "passw0rd"
endpoint = "https://my-server-1.myawesomecompany.org"
ssl_insecure = true
},
"my-server-2" = {
user = "admin"
password = "passw0rd"
endpoint = "https://my-server-2.myawesomecompany.org"
ssl_insecure = true
},
}
```

provider.tf
```terraform
/*
Copyright (c) 2023 Dell Inc., or its subsidiaries. All Rights Reserved.
Licensed under the Mozilla Public License Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://mozilla.org/MPL/2.0/
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
terraform {
required_providers {
redfish = {
version = "1.0.0"
source = "registry.terraform.io/dell/redfish"
}
}
}
```

main.tf
```terraform
/*
Copyright (c) 2023 Dell Inc., or its subsidiaries. All Rights Reserved.
Licensed under the Mozilla Public License Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://mozilla.org/MPL/2.0/
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
resource "redfish_simple_update" "update" {
for_each = var.rack1
redfish_server {
user = each.value.user
password = each.value.password
endpoint = each.value.endpoint
ssl_insecure = each.value.ssl_insecure
}
// The network protocols and image for firmware update
transfer_protocol = "HTTP"
target_firmware_image = "/home/mikeletux/Downloads/BIOS_FXC54_WN64_1.15.0.EXE"
// Reset parameters to be applied when upgrade is completed
reset_type = "ForceRestart"
reset_timeout = 120 // If not set, by default will be 120s
// The maximum amount of time to wait for the simple update job to be completed
simple_update_job_timeout = 1200 // If not set, by default will be 1200s
}
```

After the successful execution of the above resource block, firmware would have got updated. It can be verified through state file.

<!-- schema generated by tfplugindocs -->
## Schema

### Required

- `redfish_server` (Attributes) Redfish Server (see [below for nested schema](#nestedatt--redfish_server))
- `reset_type` (String) Reset type allows to choose the type of restart to apply when firmware upgrade is scheduled. Possible values are: "ForceRestart", "GracefulRestart" or "PowerCycle"
- `target_firmware_image` (String) Target firmware image used for firmware update on the redfish instance. Make sure you place your firmware packages in the same folder as the module and set it as follows: "${path.module}/BIOS_FXC54_WN64_1.15.0.EXE"
- `transfer_protocol` (String) The network protocol that the Update Service uses to retrieve the software image file located at the URI provided in ImageURI, if the URI does not contain a scheme. Accepted values: CIFS, FTP, SFTP, HTTP, HTTPS, NSF, SCP, TFTP, OEM, NFS. Currently only HTTP, HTTPS and NFS are supported with local file path or HTTP(s)/NFS link.

### Optional

- `reset_timeout` (Number) Time in seconds that the provider waits for the server to be reset before timing out.
- `simple_update_job_timeout` (Number) Time in seconds that the provider waits for the simple update job to be completed before timing out.

### Read-Only

- `id` (String) ID of the simple update resource
- `software_id` (String) Software ID from the firmware package uploaded
- `version` (String) Software version from the firmware package uploaded

<a id="nestedatt--redfish_server"></a>
### Nested Schema for `redfish_server`

Required:

- `endpoint` (String) Server BMC IP address or hostname

Optional:

- `password` (String, Sensitive) User password for login
- `user` (String) User name for login
- `validate_cert` (Boolean) This field indicates whether the SSL/TLS certificate must be verified or not



3 changes: 2 additions & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ require (
github.com/stmcginnis/gofish v0.14.1-0.20230828052805-4738a5dd9470
)

require github.com/apparentlymart/go-textseg/v15 v15.0.0 // indirect

require (
github.com/hashicorp/terraform-plugin-framework-validators v0.12.0
github.com/hashicorp/terraform-plugin-go v0.19.0
Expand All @@ -22,7 +24,6 @@ require (
github.com/Masterminds/sprig/v3 v3.2.2 // indirect
github.com/ProtonMail/go-crypto v0.0.0-20230717121422-5aa5874ade95 // indirect
github.com/agext/levenshtein v1.2.2 // indirect
github.com/apparentlymart/go-textseg/v15 v15.0.0 // indirect
github.com/armon/go-radix v1.0.0 // indirect
github.com/bgentry/speakeasy v0.1.0 // indirect
github.com/cloudflare/circl v1.3.3 // indirect
Expand Down
18 changes: 18 additions & 0 deletions redfish/models/simpleUpdate.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
package models

import (
"github.com/hashicorp/terraform-plugin-framework/types"
)

// SimpleUpdateRes is struct for simple update resource
type SimpleUpdateRes struct {
Id types.String `tfsdk:"id"`
RedfishServer RedfishServer `tfsdk:"redfish_server"`
Protocol types.String `tfsdk:"transfer_protocol"`
Image types.String `tfsdk:"target_firmware_image"`
ResetType types.String `tfsdk:"reset_type"`
ResetTimeout types.Int64 `tfsdk:"reset_timeout"`
JobTimeout types.Int64 `tfsdk:"simple_update_job_timeout"`
SoftwareId types.String `tfsdk:"software_id"`
Version types.String `tfsdk:"version"`
}
52 changes: 27 additions & 25 deletions redfish/provider/common.go
Original file line number Diff line number Diff line change
@@ -1,15 +1,16 @@
package provider

import (
"context"
"errors"
"fmt"
"log"
"terraform-provider-redfish/redfish/models"
"time"

datasourceSchema "github.com/hashicorp/terraform-plugin-framework/datasource/schema"
"github.com/hashicorp/terraform-plugin-framework/diag"
resourceSchema "github.com/hashicorp/terraform-plugin-framework/resource/schema"
"github.com/hashicorp/terraform-plugin-log/tflog"
"github.com/stmcginnis/gofish"
"github.com/stmcginnis/gofish/redfish"
)
Expand Down Expand Up @@ -114,38 +115,41 @@ func NewConfig(pconfig *redfishProvider, rserver *models.RedfishServer) (*gofish
return api.Service, nil
}

type powerOperator struct {
ctx context.Context
service *gofish.Service
}

// PowerOperation Executes a power operation against the target server. It takes four arguments. The first is the reset
// type. See the struct "ResetType" at https://github.com/stmcginnis/gofish/blob/main/redfish/computersystem.go for all
// possible options. The second is maximumWaitTime which is the maximum amount of time to wait for the server to reach
// the expected power state before considering it a failure. The third is checkInterval which is how often to check the
// server's power state for updates. The last is a pointer to a gofish.Service object with which the function can
// interact with the server. It will return a tuple consisting of the server's power state at time of return and
// diagnostics
func PowerOperation(resetType string, maximumWaitTime int, checkInterval int, service *gofish.Service) (redfish.PowerState, diag.Diagnostics) { //nolint:revive
var diags diag.Diagnostics
func (p powerOperator) PowerOperation(resetType string, maximumWaitTime int64, checkInterval int64) (redfish.PowerState, error) {
const powerON redfish.PowerState = "On"
const powerOFF redfish.PowerState = "Off"
system, err := getSystemResource(service)
system, err := getSystemResource(p.service)
if err != nil {
log.Printf("[ERROR]: Failed to identify system: %s", err)
diags.AddError("error", err.Error())
return "", diags
tflog.Error(p.ctx, fmt.Sprintf("Failed to identify system: %s", err))
return "", fmt.Errorf("failed to identify system: %w", err)
}

var targetPowerState redfish.PowerState

if resetType == "ForceOff" || resetType == "GracefulShutdown" {
if system.PowerState == powerOFF {
log.Printf("[TRACE]: Server already powered off. No action required.")
return redfish.OffPowerState, diags
tflog.Trace(p.ctx, "Server already powered off. No action required.")
return redfish.OffPowerState, nil
}
targetPowerState = powerOFF
}

if resetType == "On" || resetType == "ForceOn" {
if system.PowerState == powerON {
log.Printf("[TRACE]: Server already powered on. No action required.")
return redfish.OnPowerState, diags
tflog.Trace(p.ctx, "Server already powered on. No action required")
return redfish.OnPowerState, nil
}
targetPowerState = powerON
}
Expand All @@ -169,35 +173,33 @@ func PowerOperation(resetType string, maximumWaitTime int, checkInterval int, se
}

// Run the power operation against the target server
log.Printf("[TRACE]: Performing system.Reset(%s)", resetType)
tflog.Trace(p.ctx, fmt.Sprintf("Performing system.Reset(%s)", resetType))
if err = system.Reset(redfish.ResetType(resetType)); err != nil {
log.Printf("[WARN]: system.Reset returned an error: %s", err)
diags.AddError("error", err.Error())
return system.PowerState, diags
tflog.Warn(p.ctx, fmt.Sprintf("system.Reset returned an error: %s", err))
return system.PowerState, err
}

// Wait for the server to be in the correct power state
totalTime := 0
var totalTime int64
for totalTime < maximumWaitTime {
time.Sleep(time.Duration(checkInterval) * time.Second)
totalTime += checkInterval
log.Printf("[TRACE]: Total time is %d seconds. Checking power state now.", totalTime)
tflog.Trace(p.ctx, fmt.Sprintf("Total time is %d seconds. Checking power state now.", totalTime))

system, err := getSystemResource(service)
system, err := getSystemResource(p.service)
if err != nil {
log.Printf("[ERROR]: Failed to identify system: %s", err)
diags.AddError("error", err.Error())
return targetPowerState, diags
tflog.Error(p.ctx, fmt.Sprintf("Failed to identify system: %s", err))
return targetPowerState, err
}
if system.PowerState == targetPowerState {
log.Printf("[TRACE]: system.Reset successful")
return system.PowerState, diags
tflog.Debug(p.ctx, "system.Reset successful")
return system.PowerState, nil
}
}

// If we've reached here it means the system never reached the appropriate target state
// We will instead set the power state to whatever the current state is and return
// TODO : Change to warning when updated to plugin framework
log.Printf("[ERROR]: The system failed to update the server's power status within the maximum wait time specified!")
return system.PowerState, diags
tflog.Warn(p.ctx, "The system failed to update the server's power status within the maximum wait time specified!")
return system.PowerState, nil
}
Loading

0 comments on commit 6d7873c

Please sign in to comment.