Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor(hss): refactor webtamper_hosts data source code style #6281

Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,14 @@ package hss
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"

hssv5model "github.com/huaweicloud/huaweicloud-sdk-go-v3/services/hss/v5/model"
"github.com/chnsz/golangsdk"

"github.com/huaweicloud/terraform-provider-huaweicloud/huaweicloud/config"
"github.com/huaweicloud/terraform-provider-huaweicloud/huaweicloud/utils"
Expand Down Expand Up @@ -118,106 +119,129 @@ func DataSourceWebTamperHosts() *schema.Resource {
}
}

func buildWebTamperHostsQueryParams(d *schema.ResourceData, epsId string) string {
queryParams := "?limit=20"
queryParams = fmt.Sprintf("%s&enterprise_project_id=%v", queryParams, epsId)
if v, ok := d.GetOk("name"); ok {
queryParams = fmt.Sprintf("%s&host_name=%v", queryParams, v)
}
if v, ok := d.GetOk("host_id"); ok {
queryParams = fmt.Sprintf("%s&host_id=%v", queryParams, v)
}
if v, ok := d.GetOk("public_ip"); ok {
queryParams = fmt.Sprintf("%s&public_ip=%v", queryParams, v)
}
if v, ok := d.GetOk("private_ip"); ok {
queryParams = fmt.Sprintf("%s&private_ip=%v", queryParams, v)
}
if v, ok := d.GetOk("group_name"); ok {
queryParams = fmt.Sprintf("%s&group_name=%v", queryParams, v)
}
if v, ok := d.GetOk("os_type"); ok {
queryParams = fmt.Sprintf("%s&os_type=%v", queryParams, v)
}
if v, ok := d.GetOk("protect_status"); ok {
queryParams = fmt.Sprintf("%s&protect_status=%v", queryParams, v)
}

return queryParams
}

func dataSourceWebTamperHostsRead(_ context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
var (
cfg = meta.(*config.Config)
region = cfg.GetRegion(d)
epsId = cfg.GetEnterpriseProjectID(d, "all_granted_eps")
limit = int32(20)
offset int32
allWtpHosts []hssv5model.WtpProtectHostResponseInfo
cfg = meta.(*config.Config)
region = cfg.GetRegion(d)
epsId = cfg.GetEnterpriseProjectID(d, QueryAllEpsValue)
product = "hss"
httpUrl = "v5/{project_id}/webtamper/hosts"
offset = 0
result = make([]interface{}, 0)
)

client, err := cfg.HcHssV5Client(region)
client, err := cfg.NewServiceClient(product, region)
if err != nil {
return diag.Errorf("error creating HSS v5 client: %s", err)
return diag.Errorf("error creating HSS client: %s", err)
}

getPath := client.Endpoint + httpUrl
getPath = strings.ReplaceAll(getPath, "{project_id}", client.ProjectID)
getPath += buildWebTamperHostsQueryParams(d, epsId)
getOpt := golangsdk.RequestOpts{
KeepResponseBody: true,
MoreHeaders: map[string]string{"region": region},
}

for {
request := hssv5model.ListWtpProtectHostRequest{
Region: region,
EnterpriseProjectId: utils.String(epsId),
HostName: utils.StringIgnoreEmpty(d.Get("name").(string)),
HostId: utils.StringIgnoreEmpty(d.Get("host_id").(string)),
PublicIp: utils.StringIgnoreEmpty(d.Get("public_ip").(string)),
PrivateIp: utils.StringIgnoreEmpty(d.Get("private_ip").(string)),
GroupName: utils.StringIgnoreEmpty(d.Get("group_name").(string)),
OsType: utils.StringIgnoreEmpty(d.Get("os_type").(string)),
ProtectStatus: utils.StringIgnoreEmpty(d.Get("protect_status").(string)),
Limit: utils.Int32(limit),
Offset: utils.Int32(offset),
currentPath := fmt.Sprintf("%s&offset=%v", getPath, offset)
getResp, err := client.Request("GET", currentPath, &getOpt)
if err != nil {
return diag.Errorf("error retrieving HSS web tamper hosts: %s", err)
}

listResp, listErr := client.ListWtpProtectHost(&request)
if listErr != nil {
return diag.Errorf("error querying HSS web tamper hosts: %s", listErr)
getRespBody, err := utils.FlattenResponse(getResp)
if err != nil {
return diag.FromErr(err)
}

if listResp == nil || listResp.DataList == nil || listResp.TotalNum == nil {
break
}
if len(*listResp.DataList) == 0 {
hostsResp := utils.PathSearch("data_list", getRespBody, make([]interface{}, 0)).([]interface{})
if len(hostsResp) == 0 {
break
}
allWtpHosts = append(allWtpHosts, *listResp.DataList...)

if int(*listResp.TotalNum) == len(allWtpHosts) {
result = append(result, hostsResp...)

totalNum := utils.PathSearch("total_num", getRespBody, float64(0)).(float64)
if int(totalNum) == len(result) {
break
}

offset += limit
offset += len(hostsResp)
}

uuId, err := uuid.GenerateUUID()
generateUUID, err := uuid.GenerateUUID()
if err != nil {
return diag.Errorf("unable to generate ID: %s", err)
}

d.SetId(uuId)
d.SetId(generateUUID)

mErr := multierror.Append(nil,
d.Set("region", region),
d.Set("hosts", flattenWebTamperHosts(filterWebTamperHosts(allWtpHosts, d))),
d.Set("hosts", flattenWebTamperHosts(filterWebTamperHosts(result, d))),
)

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

func filterWebTamperHosts(wtpHosts []hssv5model.WtpProtectHostResponseInfo, d *schema.ResourceData) []hssv5model.WtpProtectHostResponseInfo {
if len(wtpHosts) == 0 {
return nil
}

rst := make([]hssv5model.WtpProtectHostResponseInfo, 0, len(wtpHosts))
for _, v := range wtpHosts {
func filterWebTamperHosts(hostsResp []interface{}, d *schema.ResourceData) []interface{} {
rst := make([]interface{}, 0, len(hostsResp))
for _, v := range hostsResp {
if raspProtectStatus, ok := d.GetOk("rasp_protect_status"); ok &&
fmt.Sprint(raspProtectStatus) != utils.StringValue(v.RaspProtectStatus) {
fmt.Sprint(raspProtectStatus) != utils.PathSearch("rasp_protect_status", v, "").(string) {
continue
}

rst = append(rst, v)
}

return rst
}

func flattenWebTamperHosts(wtpHosts []hssv5model.WtpProtectHostResponseInfo) []interface{} {
if len(wtpHosts) == 0 {
return nil
}

rst := make([]interface{}, 0, len(wtpHosts))
for _, v := range wtpHosts {
func flattenWebTamperHosts(hostsResp []interface{}) []interface{} {
rst := make([]interface{}, 0, len(hostsResp))
for _, v := range hostsResp {
rst = append(rst, map[string]interface{}{
"id": v.HostId,
"name": v.HostName,
"public_ip": v.PublicIp,
"private_ip": v.PrivateIp,
"group_name": v.GroupName,
"os_bit": v.OsBit,
"os_type": v.OsType,
"protect_status": v.ProtectStatus,
"rasp_protect_status": v.RaspProtectStatus,
"anti_tampering_times": v.AntiTamperingTimes,
"detect_tampering_times": v.DetectTamperingTimes,
"id": utils.PathSearch("host_id", v, nil),
"name": utils.PathSearch("host_name", v, nil),
"public_ip": utils.PathSearch("public_ip", v, nil),
"private_ip": utils.PathSearch("private_ip", v, nil),
"group_name": utils.PathSearch("group_name", v, nil),
"os_bit": utils.PathSearch("os_bit", v, nil),
"os_type": utils.PathSearch("os_type", v, nil),
"protect_status": utils.PathSearch("protect_status", v, nil),
"rasp_protect_status": utils.PathSearch("rasp_protect_status", v, nil),
"anti_tampering_times": utils.PathSearch("anti_tampering_times", v, nil),
"detect_tampering_times": utils.PathSearch("detect_tampering_times", v, nil),
})
}

Expand Down
Loading