Skip to content

Commit

Permalink
refactor(eg/channel): using auto-gen style to instead the old codes
Browse files Browse the repository at this point in the history
  • Loading branch information
Lance52259 committed Aug 15, 2024
1 parent e4f511b commit e46a3f9
Show file tree
Hide file tree
Showing 2 changed files with 79 additions and 51 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,6 @@ import (
"github.com/hashicorp/go-uuid"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource"

"github.com/chnsz/golangsdk/openstack/eg/v1/channel/custom"

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

Expand All @@ -18,7 +16,7 @@ func TestAccDataCustomEventChannels_basic(t *testing.T) {
byName = "data.huaweicloud_eg_custom_event_channels.filter_by_name"
nameNotFound = "data.huaweicloud_eg_custom_event_channels.name_not_found"

obj custom.Channel
obj interface{}
rc = acceptance.InitResourceCheck(baseRes, &obj, getCustomEventChannelFunc)
dcByName = acceptance.InitDataSourceCheck(byName)
dcNameNotFound = acceptance.InitDataSourceCheck(nameNotFound)
Expand Down Expand Up @@ -96,7 +94,7 @@ func TestAccDataCustomEventChannels_filterById(t *testing.T) {
byId = "data.huaweicloud_eg_custom_event_channels.filter_by_id"
idNotFound = "data.huaweicloud_eg_custom_event_channels.id_not_found"

obj custom.Channel
obj interface{}
rc = acceptance.InitResourceCheck(baseRes, &obj, getCustomEventChannelFunc)
dcById = acceptance.InitDataSourceCheck(byId)
dcIdNotFound = acceptance.InitDataSourceCheck(idNotFound)
Expand Down Expand Up @@ -162,7 +160,7 @@ func TestAccDataCustomEventChannels_filterByEpsId(t *testing.T) {
byChannelId = "data.huaweicloud_eg_custom_event_channels.filter_by_eps_id"
channelIdNotFound = "data.huaweicloud_eg_custom_event_channels.eps_id_not_found"

obj custom.Channel
obj interface{}
rc = acceptance.InitResourceCheck(baseRes, &obj, getCustomEventChannelFunc)
dcByEpsId = acceptance.InitDataSourceCheck(byChannelId)
dcEpsIdNotFound = acceptance.InitDataSourceCheck(channelIdNotFound)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,14 @@ package eg
import (
"context"
"fmt"
"strings"

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

"github.com/chnsz/golangsdk/openstack/eg/v1/channel/custom"
"github.com/chnsz/golangsdk"

"github.com/huaweicloud/terraform-provider-huaweicloud/huaweicloud/config"
"github.com/huaweicloud/terraform-provider-huaweicloud/huaweicloud/utils"
Expand All @@ -28,13 +29,13 @@ func DataSourceCustomEventChannels() *schema.Resource {
"region": {
Type: schema.TypeString,
Optional: true,
Description: "The region where the custom event channels are located.",
Description: `The region where the custom event channels are located.`,
},
"channel_id": {
Type: schema.TypeString,
Optional: true,
Description: utils.SchemaDesc(
"The channel ID used to query specified custom event channel.",
`The channel ID used to query specified custom event channel.`,
utils.SchemaDescInput{
Deprecated: true,
},
Expand All @@ -43,12 +44,12 @@ func DataSourceCustomEventChannels() *schema.Resource {
"name": {
Type: schema.TypeString,
Optional: true,
Description: "The channel name used to query specified custom event channel.",
Description: `The channel name used to query specified custom event channel.`,
},
"enterprise_project_id": {
Type: schema.TypeString,
Optional: true,
Description: "The ID of the enterprise project to which the custom event channels belong.",
Description: `The ID of the enterprise project to which the custom event channels belong.`,
},
"channels": {
Type: schema.TypeList,
Expand All @@ -58,43 +59,43 @@ func DataSourceCustomEventChannels() *schema.Resource {
"id": {
Type: schema.TypeString,
Computed: true,
Description: "The ID of the custom event channel.",
Description: `The ID of the custom event channel.`,
},
"name": {
Type: schema.TypeString,
Computed: true,
Description: "The name of the custom event channel.",
Description: `The name of the custom event channel.`,
},
"description": {
Type: schema.TypeString,
Computed: true,
Description: "The description of the custom event channel.",
Description: `The description of the custom event channel.`,
},
"provider_type": {
Type: schema.TypeString,
Computed: true,
Description: "The type of the custom event channel.",
Description: `The type of the custom event channel.`,
},
"enterprise_project_id": {
Type: schema.TypeString,
Computed: true,
Description: "The ID of the enterprise project to which the custom event channel belongs.",
Description: `The ID of the enterprise project to which the custom event channel belongs.`,
},
"cross_account_ids": {
Type: schema.TypeSet,
Computed: true,
Description: "The list of domain IDs (other tenants) for the cross-account policy.",
Description: `The list of domain IDs (other tenants) for the cross-account policy.`,
Elem: &schema.Schema{Type: schema.TypeString},
},
"created_at": {
Type: schema.TypeString,
Computed: true,
Description: "The creation time of the custom event channel.",
Description: `The creation time of the custom event channel.`,
},
"updated_at": {
Type: schema.TypeString,
Computed: true,
Description: "The latest update time of the custom event channel.",
Description: `The latest update time of the custom event channel.`,
},
},
},
Expand All @@ -103,62 +104,91 @@ func DataSourceCustomEventChannels() *schema.Resource {
}
}

func filterEventChannels(channels []custom.Channel, epsId string) ([]interface{}, error) {
filter := map[string]interface{}{
"EnterpriseProjectId": epsId,
func buildEventChannelsQueryParams(d *schema.ResourceData) string {
res := ""
if apiName, ok := d.GetOk("name"); ok {
res = fmt.Sprintf("%s&name=%v", res, apiName)
}

filterResult, err := utils.FilterSliceWithField(channels, filter)
if err != nil {
return nil, fmt.Errorf("error filting list of event channels: %s", err)
if epsId, ok := d.GetOk("enterprise_project_id"); ok {
res = fmt.Sprintf("%s&eps_id=%v", res, epsId)
}
if channelId, ok := d.GetOk("channel_id"); ok {
res = fmt.Sprintf("%s&channel_id=%v", res, channelId)
}
return filterResult, nil
return res
}

func flattenEventChannels(channels []interface{}) []map[string]interface{} {
if len(channels) < 1 {
return nil
func queryEventChannels(client *golangsdk.ServiceClient, d *schema.ResourceData, providerType string) ([]interface{}, error) {
var (
httpUrl = "v1/{project_id}/channels?provider_type={provider_type}&limit=100"
offset = 0
result = make([]interface{}, 0)
)
listPath := client.Endpoint + httpUrl
listPath = strings.ReplaceAll(listPath, "{project_id}", client.ProjectID)
listPath = strings.ReplaceAll(listPath, "{provider_type}", providerType)
listPath += buildEventChannelsQueryParams(d)

opt := golangsdk.RequestOpts{
KeepResponseBody: true,
MoreHeaders: map[string]string{
"Content-Type": "application/json",
},
}

result := make([]map[string]interface{}, len(channels))
for i, val := range channels {
channel := val.(custom.Channel)
result[i] = map[string]interface{}{
"id": channel.ID,
"name": channel.Name,
"provider_type": channel.ProviderType,
"enterprise_project_id": channel.EnterpriseProjectId,
"cross_account_ids": channel.Policy.Principal.IAM,
"created_at": channel.CreatedTime,
"updated_at": channel.UpdatedTime,
for {
listPathWithOffset := listPath + fmt.Sprintf("&offset=%d", offset)
requestResp, err := client.Request("GET", listPathWithOffset, &opt)
if err != nil {
return nil, err
}
respBody, err := utils.FlattenResponse(requestResp)
if err != nil {
return nil, err
}
channels := utils.PathSearch("items", respBody, make([]interface{}, 0)).([]interface{})
if len(channels) < 1 {
break
}
result = append(result, channels...)
offset += len(channels)
}

return result, nil
}

func flattenEventChannels(channels []interface{}) []interface{} {
result := make([]interface{}, 0, len(channels))

for _, channel := range channels {
result = append(result, map[string]interface{}{
"id": utils.PathSearch("id", channel, nil),
"name": utils.PathSearch("name", channel, nil),
"provider_type": utils.PathSearch("provider_type", channel, nil),
"enterprise_project_id": utils.PathSearch("enterprise_project_id", channel, nil),
"cross_account_ids": utils.PathSearch("policy.Principal.IAM", channel, make([]interface{}, 0)),
"created_at": utils.PathSearch("created_time", channel, nil),
"updated_at": utils.PathSearch("updated_time", channel, nil),
})
}

return result
}

func dataSourceCustomEventChannelsRead(_ context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
var (
cfg = meta.(*config.Config)
region = cfg.GetRegion(d)
opts = custom.ListOpts{
ChannelId: d.Get("channel_id").(string),
ProviderType: "CUSTOM",
Name: d.Get("name").(string),
}
)
client, err := cfg.EgV1Client(region)
if err != nil {
return diag.Errorf("error creating EG v1 client: %s", err)
}

resp, err := custom.List(client, opts)
channaels, err := queryEventChannels(client, d, "CUSTOM")
if err != nil {
return diag.Errorf("error querying custom event channels: %s", err)
}
filterResult, err := filterEventChannels(resp, cfg.GetEnterpriseProjectID(d))
if err != nil {
return diag.FromErr(err)
}

uuid, err := uuid.GenerateUUID()
if err != nil {
Expand All @@ -168,7 +198,7 @@ func dataSourceCustomEventChannelsRead(_ context.Context, d *schema.ResourceData

mErr := multierror.Append(nil,
d.Set("region", region),
d.Set("channels", flattenEventChannels(filterResult)),
d.Set("channels", flattenEventChannels(channaels)),
)
if err := mErr.ErrorOrNil(); err != nil {
return diag.Errorf("error saving data source fields of EG custom event channels: %s", err)
Expand Down

0 comments on commit e46a3f9

Please sign in to comment.