From 670c70c09ab22c2b917ad9b27a16a7f2ae9ba1eb Mon Sep 17 00:00:00 2001 From: Lance52259 Date: Mon, 17 May 2021 11:01:24 +0800 Subject: [PATCH 1/2] extract the instance status detection method --- .../resource_huaweicloud_compute_instance.go | 71 +++++++++---------- 1 file changed, 32 insertions(+), 39 deletions(-) diff --git a/huaweicloud/resource_huaweicloud_compute_instance.go b/huaweicloud/resource_huaweicloud_compute_instance.go index fd764e59ff..482bb94629 100644 --- a/huaweicloud/resource_huaweicloud_compute_instance.go +++ b/huaweicloud/resource_huaweicloud_compute_instance.go @@ -604,20 +604,11 @@ func resourceComputeInstanceV2Create(d *schema.ResourceData, meta interface{}) e // Wait for the instance to become running so we can get some attributes // that aren't available until later. log.Printf("[DEBUG] Waiting for instance (%s) to become running", server.ID) - stateConf := &resource.StateChangeConf{ - Pending: []string{"BUILD"}, - Target: []string{"ACTIVE"}, - Refresh: ServerV2StateRefreshFunc(computeClient, server.ID), - Timeout: d.Timeout(schema.TimeoutCreate), - Delay: 10 * time.Second, - MinTimeout: 3 * time.Second, - } - - _, err = stateConf.WaitForState() - if err != nil { - return fmt.Errorf( - "Error waiting for instance (%s) to become ready: %s", - server.ID, err) + pending := []string{"BUILD"} + target := []string{"ACTIVE"} + timeout := d.Timeout(schema.TimeoutCreate) + if err := watiForServerTargetState(computeClient, d.Id(), pending, target, timeout); err != nil { + return fmt.Errorf("State waiting timeout: %s", err) } } @@ -979,18 +970,12 @@ func resourceComputeInstanceV2Delete(d *schema.ResourceData, meta interface{}) e if err != nil { log.Printf("[WARN] Error stopping HuaweiCloud instance: %s", err) } else { - stopStateConf := &resource.StateChangeConf{ - Pending: []string{"ACTIVE"}, - Target: []string{"SHUTOFF"}, - Refresh: ServerV2StateRefreshFunc(computeClient, d.Id()), - Timeout: 3 * time.Minute, - Delay: 10 * time.Second, - MinTimeout: 3 * time.Second, - } log.Printf("[DEBUG] Waiting for instance (%s) to stop", d.Id()) - _, err = stopStateConf.WaitForState() - if err != nil { - log.Printf("[WARN] Error waiting for instance (%s) to stop: %s, proceeding to delete", d.Id(), err) + pending := []string{"ACTIVE"} + target := []string{"SHUTOFF"} + timeout := d.Timeout(schema.TimeoutCreate) + if err := watiForServerTargetState(computeClient, d.Id(), pending, target, timeout); err != nil { + return fmt.Errorf("State waiting timeout: %s", err) } } } @@ -1022,20 +1007,11 @@ func resourceComputeInstanceV2Delete(d *schema.ResourceData, meta interface{}) e } // Instance may still exist after Order/Job succeed. - stateConf := &resource.StateChangeConf{ - Pending: []string{"ACTIVE", "SHUTOFF"}, - Target: []string{"DELETED", "SOFT_DELETED"}, - Refresh: ServerV2StateRefreshFunc(computeClient, d.Id()), - Timeout: d.Timeout(schema.TimeoutDelete), - Delay: 10 * time.Second, - MinTimeout: 3 * time.Second, - } - - _, err = stateConf.WaitForState() - if err != nil { - return fmt.Errorf( - "Error waiting for instance (%s) to delete: %s", - d.Id(), err) + pending := []string{"ACTIVE", "SHUTOFF"} + target := []string{"DELETED", "SOFT_DELETED"} + deleteTimeout := d.Timeout(schema.TimeoutDelete) + if err := watiForServerTargetState(computeClient, d.Id(), pending, target, deleteTimeout); err != nil { + return fmt.Errorf("State waiting timeout: %s", err) } d.SetId("") @@ -1370,3 +1346,20 @@ func checkBlockDeviceConfig(d *schema.ResourceData) error { return nil } + +func watiForServerTargetState(client *golangsdk.ServiceClient, ID string, pending, target []string, timeout time.Duration) error { + stateConf := &resource.StateChangeConf{ + Pending: pending, + Target: target, + Refresh: ServerV2StateRefreshFunc(client, ID), + Timeout: timeout, + Delay: 5 * time.Second, + PollInterval: 5 * time.Second, + } + + _, err := stateConf.WaitForState() + if err != nil { + return fmt.Errorf("Error waiting for instance (%s) to become target state (%v): %s", ID, target, err) + } + return nil +} From 0a8e7420b30df65b23559765c23069ebd1833ed7 Mon Sep 17 00:00:00 2001 From: Lance52259 Date: Mon, 17 May 2021 11:19:43 +0800 Subject: [PATCH 2/2] feat: instacne power on/off supported --- docs/resources/compute_instance.md | 9 +- .../resource_huaweicloud_compute_instance.go | 73 ++++++++++++++- ...ource_huaweicloud_compute_instance_test.go | 88 +++++++++++++++++++ .../openstack/ecs/v1/powers/requests.go | 39 ++++++++ .../golangsdk/openstack/ecs/v1/powers/urls.go | 9 ++ vendor/modules.txt | 1 + 6 files changed, 216 insertions(+), 3 deletions(-) create mode 100644 vendor/github.com/huaweicloud/golangsdk/openstack/ecs/v1/powers/requests.go create mode 100644 vendor/github.com/huaweicloud/golangsdk/openstack/ecs/v1/powers/urls.go diff --git a/docs/resources/compute_instance.md b/docs/resources/compute_instance.md index 9ce67c1e84..5ebce18fe5 100644 --- a/docs/resources/compute_instance.md +++ b/docs/resources/compute_instance.md @@ -283,6 +283,10 @@ The following arguments are supported: * `agency_name` - (Optional, String, ForceNew) Specifies the IAM agency name which is created on IAM to provide temporary credentials for ECS to access cloud services. Changing this creates a new instance. +* `power_action` - (Optional, String) Specifies the power action to be done for the instance. + The valid values are *ON*, *OFF*, *REBOOT*, *FORCE-OFF* and *FORCE-REBOOT*. + + -> **NOTE:** The `power_action` is a one-time action. The `network` block supports: @@ -346,8 +350,9 @@ terraform import huaweicloud_compute_instance.my_instance b11b407c-e604-4e8d-8bc Note that the imported state may not be identical to your resource definition, due to some attrubutes missing from the API response, security or some other reason. The missing attributes include: `admin_pass`, `user_data`, `data_disks`, `scheduler_hints`, `stop_before_destroy`, `delete_disks_on_termination`, -`network/access_network` and arguments for pre-paid. It is generally recommended running `terraform plan` after -importing an instance. You can then decide if changes should be applied to the instance, or the resource definition +`network/access_network`, `power_action` and arguments for pre-paid. +It is generally recommended running `terraform plan` after importing an instance. +You can then decide if changes should be applied to the instance, or the resource definition should be updated to align with the instance. Also you can ignore changes as below. ``` resource "huaweicloud_compute_instance" "myinstance" { diff --git a/huaweicloud/resource_huaweicloud_compute_instance.go b/huaweicloud/resource_huaweicloud_compute_instance.go index 482bb94629..884956acb3 100644 --- a/huaweicloud/resource_huaweicloud_compute_instance.go +++ b/huaweicloud/resource_huaweicloud_compute_instance.go @@ -6,6 +6,7 @@ import ( "encoding/hex" "fmt" "log" + "strings" "time" "github.com/hashicorp/terraform-plugin-sdk/helper/hashcode" @@ -26,13 +27,21 @@ import ( "github.com/huaweicloud/golangsdk/openstack/compute/v2/servers" "github.com/huaweicloud/golangsdk/openstack/ecs/v1/block_devices" "github.com/huaweicloud/golangsdk/openstack/ecs/v1/cloudservers" + "github.com/huaweicloud/golangsdk/openstack/ecs/v1/powers" "github.com/huaweicloud/golangsdk/openstack/networking/v1/subnets" "github.com/huaweicloud/golangsdk/openstack/networking/v2/extensions/security/groups" "github.com/huaweicloud/terraform-provider-huaweicloud/huaweicloud/config" "github.com/huaweicloud/terraform-provider-huaweicloud/huaweicloud/utils" ) -var novaConflicts = []string{"block_device", "metadata"} +var ( + novaConflicts = []string{"block_device", "metadata"} + powerActionMap = map[string]string{ + "ON": "os-start", + "OFF": "os-stop", + "REBOOT": "reboot", + } +) func ResourceComputeInstanceV2() *schema.Resource { return &schema.Resource{ @@ -286,6 +295,14 @@ func ResourceComputeInstanceV2() *schema.Resource { ValidateFunc: utils.ValidateECSTagValue, Elem: &schema.Schema{Type: schema.TypeString}, }, + "power_action": { + Type: schema.TypeString, + Optional: true, + // If you want to support more actions, please update powerActionMap simultaneously. + ValidateFunc: validation.StringInSlice([]string{ + "ON", "OFF", "REBOOT", "FORCE-OFF", "FORCE-REBOOT", + }, false), + }, "volume_attached": { Type: schema.TypeList, Computed: true, @@ -622,6 +639,18 @@ func resourceComputeInstanceV2Create(d *schema.ResourceData, meta interface{}) e } } + // Create an instance in the shutdown state. + if action, ok := d.GetOk("power_action"); ok { + action := action.(string) + if action == "OFF" || action == "FORCE-OFF" { + if err = doPowerAction(ecsClient, d, action); err != nil { + return fmt.Errorf("Doing power action (%s) for instance (%s) failed: %s", action, d.Id(), err) + } + } else { + log.Printf("[WARN] The power action (%s) is invalid after instance created", action) + } + } + return resourceComputeInstanceV2Read(d, meta) } @@ -954,6 +983,14 @@ func resourceComputeInstanceV2Update(d *schema.ResourceData, meta interface{}) e } } + // The instance power status update needs to be done at the end + if d.HasChange("power_action") { + action := d.Get("power_action").(string) + if err = doPowerAction(ecsClient, d, action); err != nil { + return fmt.Errorf("Doing power action (%s) for instance (%s) failed: %s", action, d.Id(), err) + } + } + return resourceComputeInstanceV2Read(d, meta) } @@ -1363,3 +1400,37 @@ func watiForServerTargetState(client *golangsdk.ServiceClient, ID string, pendin } return nil } + +// doPowerAction is a method for instance power doing shutdown, startup and reboot actions. +func doPowerAction(client *golangsdk.ServiceClient, d *schema.ResourceData, action string) error { + var jobResp *cloudservers.JobResponse + powerOpts := powers.PowerOpts{ + Servers: []powers.ServerInfo{ + {ID: d.Id()}, + }, + } + // In the reboot structure, Type is a required option. + // Since the type of power off and reboot is 'SOFT' by default, setting this value has solved the power structural + // compatibility problem between optional and required. + if action != "ON" { + powerOpts.Type = "SOFT" + } + if strings.HasPrefix(action, "FORCE-") { + powerOpts.Type = "HARD" + action = strings.TrimPrefix(action, "FORCE-") + } + op, ok := powerActionMap[action] + if !ok { + return fmt.Errorf("The powerMap does not contain option (%s)", action) + } + jobResp, err := powers.PowerAction(client, powerOpts, op).ExtractJobResponse() + if err != nil { + return fmt.Errorf("Doing power action (%s) for instance (%s) failed: %s", action, d.Id(), err) + } + // The time of the power on/off and reboot is usually between 15 and 35 seconds. + timeout := 3 * time.Minute + if err := cloudservers.WaitForJobSuccess(client, int(timeout/time.Second), jobResp.JobID); err != nil { + return err + } + return nil +} diff --git a/huaweicloud/resource_huaweicloud_compute_instance_test.go b/huaweicloud/resource_huaweicloud_compute_instance_test.go index ff73e30f3b..46091097df 100644 --- a/huaweicloud/resource_huaweicloud_compute_instance_test.go +++ b/huaweicloud/resource_huaweicloud_compute_instance_test.go @@ -138,6 +138,75 @@ func TestAccComputeV2Instance_tags(t *testing.T) { }) } +func TestAccComputeV2Instance_powerAction(t *testing.T) { + var instance servers.Server + + rName := fmt.Sprintf("tf-acc-test-%s", acctest.RandString(5)) + resourceName := "huaweicloud_compute_instance.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckComputeV2InstanceDestroy, + Steps: []resource.TestStep{ + { + Config: testAccComputeV2Instance_powerAction(rName, "OFF"), + Check: resource.ComposeTestCheckFunc( + testAccCheckComputeV2InstanceExists(resourceName, &instance), + resource.TestCheckResourceAttr(resourceName, "name", rName), + resource.TestCheckResourceAttr(resourceName, "power_action", "OFF"), + resource.TestCheckResourceAttr(resourceName, "status", "SHUTOFF"), + ), + }, + { + Config: testAccComputeV2Instance_powerAction(rName, "ON"), + Check: resource.ComposeTestCheckFunc( + testAccCheckComputeV2InstanceExists(resourceName, &instance), + resource.TestCheckResourceAttr(resourceName, "name", rName), + resource.TestCheckResourceAttr(resourceName, "power_action", "ON"), + resource.TestCheckResourceAttr(resourceName, "status", "ACTIVE"), + ), + }, + { + Config: testAccComputeV2Instance_powerAction(rName, "REBOOT"), + Check: resource.ComposeTestCheckFunc( + testAccCheckComputeV2InstanceExists(resourceName, &instance), + resource.TestCheckResourceAttr(resourceName, "name", rName), + resource.TestCheckResourceAttr(resourceName, "power_action", "REBOOT"), + resource.TestCheckResourceAttr(resourceName, "status", "ACTIVE"), + ), + }, + { + Config: testAccComputeV2Instance_powerAction(rName, "FORCE-REBOOT"), + Check: resource.ComposeTestCheckFunc( + testAccCheckComputeV2InstanceExists(resourceName, &instance), + resource.TestCheckResourceAttr(resourceName, "name", rName), + resource.TestCheckResourceAttr(resourceName, "power_action", "FORCE-REBOOT"), + resource.TestCheckResourceAttr(resourceName, "status", "ACTIVE"), + ), + }, + { + Config: testAccComputeV2Instance_powerAction(rName, "FORCE-OFF"), + Check: resource.ComposeTestCheckFunc( + testAccCheckComputeV2InstanceExists(resourceName, &instance), + resource.TestCheckResourceAttr(resourceName, "name", rName), + resource.TestCheckResourceAttr(resourceName, "power_action", "FORCE-OFF"), + resource.TestCheckResourceAttr(resourceName, "status", "SHUTOFF"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{ + "stop_before_destroy", + "power_action", + }, + }, + }, + }) +} + func testAccCheckComputeV2InstanceDestroy(s *terraform.State) error { config := testAccProvider.Meta().(*config.Config) computeClient, err := config.ComputeV2Client(HW_REGION_NAME) @@ -391,3 +460,22 @@ resource "huaweicloud_compute_instance" "test" { } `, testAccCompute_data, rName) } + +func testAccComputeV2Instance_powerAction(rName, powerAction string) string { + return fmt.Sprintf(` +%s + +resource "huaweicloud_compute_instance" "test" { + name = "%s" + image_id = data.huaweicloud_images_image.test.id + flavor_id = data.huaweicloud_compute_flavors.test.ids[0] + security_groups = ["default"] + availability_zone = data.huaweicloud_availability_zones.test.names[0] + power_action = "%s" + + network { + uuid = data.huaweicloud_vpc_subnet.test.id + } +} +`, testAccCompute_data, rName, powerAction) +} diff --git a/vendor/github.com/huaweicloud/golangsdk/openstack/ecs/v1/powers/requests.go b/vendor/github.com/huaweicloud/golangsdk/openstack/ecs/v1/powers/requests.go new file mode 100644 index 0000000000..30d8d1e2d8 --- /dev/null +++ b/vendor/github.com/huaweicloud/golangsdk/openstack/ecs/v1/powers/requests.go @@ -0,0 +1,39 @@ +package powers + +import ( + "github.com/huaweicloud/golangsdk" + "github.com/huaweicloud/golangsdk/openstack/ecs/v1/cloudservers" +) + +// PowerOpts allows batch update of the ECS instances power state through the API. +// Parameter 'Type' supports two methods of 'SOFT' and 'HARD' to shut down and reboot the machine's power. +type PowerOpts struct { + Servers []ServerInfo `json:"servers" required:"true"` + Type string `json:"type,omitempty"` +} + +type ServerInfo struct { + ID string `json:"id" required:"true"` +} + +// PowerOptsBuilder allows extensions to add additional parameters to the PowerAction(power on/off and reboot) request. +type PowerOptsBuilder interface { + ToPowerActionMap(option string) (map[string]interface{}, error) +} + +// ToPowerActionMap assembles a request body based on the contents of a PowerOpts and the power option parameter. +func (opts PowerOpts) ToPowerActionMap(option string) (map[string]interface{}, error) { + return golangsdk.BuildRequestBody(opts, option) +} + +// PowerAction uses a option parameter to control the power state of the ECS instance. +// The option only supports 'os-start' (power on), 'os-stop' (power off) and 'reboot'. +func PowerAction(client *golangsdk.ServiceClient, opts PowerOptsBuilder, option string) (r cloudservers.JobResult) { + reqBody, err := opts.ToPowerActionMap(option) + if err != nil { + r.Err = err + return + } + _, r.Err = client.Post(actionURL(client), reqBody, &r.Body, &golangsdk.RequestOpts{OkCodes: []int{200}}) + return +} diff --git a/vendor/github.com/huaweicloud/golangsdk/openstack/ecs/v1/powers/urls.go b/vendor/github.com/huaweicloud/golangsdk/openstack/ecs/v1/powers/urls.go new file mode 100644 index 0000000000..08aa01f170 --- /dev/null +++ b/vendor/github.com/huaweicloud/golangsdk/openstack/ecs/v1/powers/urls.go @@ -0,0 +1,9 @@ +package powers + +import "github.com/huaweicloud/golangsdk" + +const rootURL = "cloudservers" + +func actionURL(client *golangsdk.ServiceClient) string { + return client.ServiceURL(rootURL, "action") +} diff --git a/vendor/modules.txt b/vendor/modules.txt index 3f26015651..0bcee7f980 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -326,6 +326,7 @@ github.com/huaweicloud/golangsdk/openstack/ecs/v1/auto_recovery github.com/huaweicloud/golangsdk/openstack/ecs/v1/block_devices github.com/huaweicloud/golangsdk/openstack/ecs/v1/cloudservers github.com/huaweicloud/golangsdk/openstack/ecs/v1/flavors +github.com/huaweicloud/golangsdk/openstack/ecs/v1/powers github.com/huaweicloud/golangsdk/openstack/elb/v2/loadbalancers github.com/huaweicloud/golangsdk/openstack/elb/v3/flavors github.com/huaweicloud/golangsdk/openstack/elb/v3/listeners