Skip to content

Commit

Permalink
refactor(cdn/cache_preheat): refactor the cache_preheat resource code…
Browse files Browse the repository at this point in the history
… style
  • Loading branch information
jinyangyang222 committed Jan 8, 2025
1 parent 14b3a8f commit 7ae68a1
Show file tree
Hide file tree
Showing 3 changed files with 98 additions and 84 deletions.
10 changes: 8 additions & 2 deletions docs/resources/cdn_cache_preheat.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,8 +33,8 @@ The following arguments are supported:
Changing this parameter will create a new resource.

* `enterprise_project_id` - (Optional, String, ForceNew) Specifies the enterprise project ID to which the accelerated
domain name belongs. This parameter is mandatory when you use an IAM user to call this API.
For enterprise users, if omitted, default enterprise project will be used.
domain name belongs. This parameter is only valid for enterprise users and is required when using Sub-account.
The value **all** represents all enterprise projects.

Changing this parameter will create a new resource.

Expand All @@ -61,3 +61,9 @@ In addition to all arguments above, the following attributes are exported:
* `failed` - The number of URLs that failed to be processed.

* `total` - The total number of URLs in historical tasks.

## Timeouts

This resource provides the following timeouts configuration options:

* `create` - Default is 3 minutes.
Original file line number Diff line number Diff line change
Expand Up @@ -7,52 +7,50 @@ import (
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/v2/terraform"

"github.com/huaweicloud/huaweicloud-sdk-go-v3/services/cdn/v2/model"

"github.com/huaweicloud/terraform-provider-huaweicloud/huaweicloud/config"
"github.com/huaweicloud/terraform-provider-huaweicloud/huaweicloud/services/acceptance"
"github.com/huaweicloud/terraform-provider-huaweicloud/huaweicloud/utils"
"github.com/huaweicloud/terraform-provider-huaweicloud/huaweicloud/services/cdn"
)

func getCachePreheatResourceFunc(cfg *config.Config, state *terraform.ResourceState) (interface{}, error) {
region := acceptance.HW_REGION_NAME
hcCdnClient, err := cfg.HcCdnV2Client(region)
var (
region = acceptance.HW_REGION_NAME
product = "cdn"
)
client, err := cfg.NewServiceClient(product, region)
if err != nil {
return nil, fmt.Errorf("error creating CDN v2 client: %s", err)
}

request := &model.ShowHistoryTaskDetailsRequest{
EnterpriseProjectId: utils.StringIgnoreEmpty(state.Primary.Attributes["enterprise_project_id"]),
HistoryTasksId: state.Primary.ID,
return nil, fmt.Errorf("error creating CDN client: %s", err)
}

resp, err := hcCdnClient.ShowHistoryTaskDetails(request)
getRespBody, err := cdn.GetCacheDetailById(client, state.Primary.ID)
if err != nil {
return nil, fmt.Errorf("error retrieving CDN cache preheat: %s", err)
return nil, err
}

if resp == nil {
return nil, fmt.Errorf("error retrieving CDN cache preheat: Task is not found in API response")
}
return resp, nil
return getRespBody, nil
}

func TestAccCachePreheat_basic(t *testing.T) {
var obj interface{}

rName := "huaweicloud_cdn_cache_preheat.test"
var (
obj interface{}
rName = "huaweicloud_cdn_cache_preheat.test"
)

rc := acceptance.InitResourceCheck(
rName,
&obj,
getCachePreheatResourceFunc,
)

// Avoid CheckDestroy, because there is nothing in the resource destroy method.
// lintignore:AT001
resource.ParallelTest(t, resource.TestCase{
PreCheck: func() {
acceptance.TestAccPreCheck(t)
acceptance.TestAccPreCheckCDNURL(t)
// The value of the enterprise project ID must be consistent with the enterprise project to which the
// domain belongs.
acceptance.TestAccPreCheckEpsID(t)
},
ProviderFactories: acceptance.TestAccProviderFactories,
Steps: []resource.TestStep{
Expand All @@ -61,6 +59,7 @@ func TestAccCachePreheat_basic(t *testing.T) {
Check: resource.ComposeTestCheckFunc(
rc.CheckResourceExists(),
resource.TestCheckResourceAttr(rName, "urls.0", acceptance.HW_CDN_DOMAIN_URL),
resource.TestCheckResourceAttr(rName, "enterprise_project_id", acceptance.HW_ENTERPRISE_PROJECT_ID_TEST),
resource.TestCheckResourceAttr(rName, "zh_url_encode", "true"),
resource.TestCheckResourceAttrSet(rName, "status"),
resource.TestCheckResourceAttrSet(rName, "created_at"),
Expand All @@ -77,8 +76,9 @@ func TestAccCachePreheat_basic(t *testing.T) {
func testCachePreheat_basic() string {
return fmt.Sprintf(`
resource "huaweicloud_cdn_cache_preheat" "test" {
urls = ["%s"]
zh_url_encode = true
urls = ["%[1]s"]
enterprise_project_id = "%[2]s"
zh_url_encode = true
}
`, acceptance.HW_CDN_DOMAIN_URL)
`, acceptance.HW_CDN_DOMAIN_URL, acceptance.HW_ENTERPRISE_PROJECT_ID_TEST)
}
126 changes: 67 additions & 59 deletions huaweicloud/services/cdn/resource_huaweicloud_cdn_cache_preheat.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,15 @@ package cdn

import (
"context"
"time"

"github.com/hashicorp/go-multierror"
"github.com/hashicorp/terraform-plugin-sdk/v2/diag"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"

"github.com/huaweicloud/huaweicloud-sdk-go-v3/services/cdn/v2/model"
"github.com/chnsz/golangsdk"

"github.com/huaweicloud/terraform-provider-huaweicloud/huaweicloud/common"
"github.com/huaweicloud/terraform-provider-huaweicloud/huaweicloud/config"
"github.com/huaweicloud/terraform-provider-huaweicloud/huaweicloud/utils"
)
Expand All @@ -26,6 +28,10 @@ func ResourceCachePreheat() *schema.Resource {
ReadContext: resourceCachePreheatRead,
DeleteContext: resourceCachePreheatDelete,

Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(3 * time.Minute),
},

Schema: map[string]*schema.Schema{
"urls": {
Type: schema.TypeSet,
Expand Down Expand Up @@ -80,93 +86,95 @@ func ResourceCachePreheat() *schema.Resource {
}
}

func buildCachePreheatBodyParams(d *schema.ResourceData) interface{} {
refreshTaskMap := map[string]interface{}{
"urls": utils.ExpandToStringList(d.Get("urls").(*schema.Set).List()),
}
if v, ok := d.GetOk("zh_url_encode"); ok {
refreshTaskMap["zh_url_encode"] = v
}
bodyParams := map[string]interface{}{
"preheating_task": refreshTaskMap,
}

return bodyParams
}

func resourceCachePreheatCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
cfg := meta.(*config.Config)
region := cfg.GetRegion(d)
hcCdnClient, err := cfg.HcCdnV2Client(region)
var (
cfg = meta.(*config.Config)
region = cfg.GetRegion(d)
product = "cdn"
createHttpUrl = "v1.0/cdn/content/preheating-tasks"
)
client, err := cfg.NewServiceClient(product, region)
if err != nil {
return diag.Errorf("error creating CDN v2 client: %s", err)
return diag.Errorf("error creating CDN client: %s", err)
}

request := &model.CreatePreheatingTasksRequest{
EnterpriseProjectId: utils.StringIgnoreEmpty(cfg.GetEnterpriseProjectID(d)),
Body: &model.PreheatingTaskRequest{
PreheatingTask: &model.PreheatingTaskRequestBody{
ZhUrlEncode: utils.Bool(d.Get("zh_url_encode").(bool)),
Urls: utils.ExpandToStringList(d.Get("urls").(*schema.Set).List()),
},
},
createPath := client.Endpoint + createHttpUrl
createPath += buildCacheQueryParams(d)
createOpt := golangsdk.RequestOpts{
KeepResponseBody: true,
MoreHeaders: map[string]string{"Content-Type": "application/json"},
JSONBody: buildCachePreheatBodyParams(d),
}

resp, err := hcCdnClient.CreatePreheatingTasks(request)
createResp, err := client.Request("POST", createPath, &createOpt)
if err != nil {
return diag.Errorf("error creating CDN cache preheat: %s", err)
}

if resp == nil || resp.PreheatingTask == nil || len(*resp.PreheatingTask) == 0 {
createRespBody, err := utils.FlattenResponse(createResp)
if err != nil {
return diag.FromErr(err)
}

preheatingTask := utils.PathSearch("preheating_task", createRespBody, "").(string)
if preheatingTask == "" {
return diag.Errorf("error creating CDN cache preheat: ID is not found in API response")
}
d.SetId(*resp.PreheatingTask)

d.SetId(preheatingTask)

if err = waitingForCacheCreateCompleted(ctx, client, preheatingTask, d.Timeout(schema.TimeoutCreate)); err != nil {
return diag.Errorf("error waiting for CDN cache preheat (%s) creation to completed: %s", preheatingTask, err)
}

return resourceCachePreheatRead(ctx, d, meta)
}

func resourceCachePreheatRead(_ context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
cfg := meta.(*config.Config)
region := cfg.GetRegion(d)
hcCdnClient, err := cfg.HcCdnV2Client(region)
var (
cfg = meta.(*config.Config)
region = cfg.GetRegion(d)
product = "cdn"
mErr *multierror.Error
)
client, err := cfg.NewServiceClient(product, region)
if err != nil {
return diag.Errorf("error creating CDN v2 client: %s", err)
return diag.Errorf("error creating CDN client: %s", err)
}

request := &model.ShowHistoryTaskDetailsRequest{
EnterpriseProjectId: utils.StringIgnoreEmpty(cfg.GetEnterpriseProjectID(d)),
HistoryTasksId: d.Id(),
}

resp, err := hcCdnClient.ShowHistoryTaskDetails(request)
getRespBody, err := GetCacheDetailById(client, d.Id())
if err != nil {
return diag.Errorf("error retrieving CDN cache preheat: %s", err)
}

if resp == nil {
return diag.Errorf("error retrieving CDN cache preheat: Task is not found in API response")
return common.CheckDeletedDiag(d, err, "CDN cache preheat")
}

var mErr *multierror.Error
mErr = multierror.Append(
mErr,
d.Set("urls", flattenUrls(resp.Urls)),
d.Set("status", resp.Status),
d.Set("created_at", flattenCreatedAt(resp.CreateTime)),
d.Set("processing", resp.Processing),
d.Set("succeed", resp.Succeed),
d.Set("failed", resp.Failed),
d.Set("total", resp.Total),
d.Set("urls", flattenCacheUrls(utils.PathSearch("urls", getRespBody, make([]interface{}, 0)).([]interface{}))),
d.Set("status", utils.PathSearch("status", getRespBody, nil)),
d.Set("created_at", flattenCacheCreatedAt(getRespBody)),
d.Set("processing", utils.PathSearch("processing", getRespBody, float64(0)).(float64)),
d.Set("succeed", utils.PathSearch("succeed", getRespBody, float64(0)).(float64)),
d.Set("failed", utils.PathSearch("failed", getRespBody, float64(0)).(float64)),
d.Set("total", utils.PathSearch("total", getRespBody, float64(0)).(float64)),
)

return diag.FromErr(mErr.ErrorOrNil())
}

func flattenUrls(urlObjects *[]model.UrlObject) []string {
if urlObjects == nil || len(*urlObjects) == 0 {
return nil
}
urls := make([]string, 0, len(*urlObjects))
for _, obj := range *urlObjects {
if obj.Url != nil {
urls = append(urls, *obj.Url)
}
}
return urls
}

func flattenCreatedAt(createTime *int64) string {
if createTime == nil {
return ""
}
return utils.FormatTimeStampRFC3339(*createTime/1000, false)
}

func resourceCachePreheatDelete(_ context.Context, _ *schema.ResourceData, _ interface{}) diag.Diagnostics {
return nil
}

0 comments on commit 7ae68a1

Please sign in to comment.