diff --git a/baiducloud/connectivity/client.go b/baiducloud/connectivity/client.go index 467be718..74851bba 100644 --- a/baiducloud/connectivity/client.go +++ b/baiducloud/connectivity/client.go @@ -13,6 +13,7 @@ import ( "github.com/baidubce/bce-sdk-go/services/cce" ccev2 "github.com/baidubce/bce-sdk-go/services/cce/v2" "github.com/baidubce/bce-sdk-go/services/cdn" + "github.com/baidubce/bce-sdk-go/services/cdn/abroad" "github.com/baidubce/bce-sdk-go/services/cert" "github.com/baidubce/bce-sdk-go/services/cfc" "github.com/baidubce/bce-sdk-go/services/cfs" @@ -63,6 +64,7 @@ type BaiduClient struct { dtsConn *dts.Client iamConn *iam.Client cdnConn *cdn.Client + abroadCdnConn *abroad.Client localDNSConn *localDns.Client smsConn *sms.Client bbcConn *bbc.Client @@ -83,7 +85,7 @@ type ApiVersion string var goSdkMutex = sync.RWMutex{} // The Go SDK is not thread-safe -var providerVersion = "1.20.6" +var providerVersion = "1.13.0" // Client for BaiduCloudClient func (c *Config) Client() (*BaiduClient, error) { @@ -471,6 +473,23 @@ func (client *BaiduClient) WithCdnClient(do func(*cdn.Client) (interface{}, erro return do(client.cdnConn) } +func (client *BaiduClient) WithAbroadCdnClient(do func(*abroad.Client) (interface{}, error)) (interface{}, error) { + goSdkMutex.Lock() + defer goSdkMutex.Unlock() + + // Initialize the abroad CDN client if necessary + if client.abroadCdnConn == nil { + client.WithCommonClient(AbroadCDNCode) + abroadCDNClient, err := abroad.NewClient(client.Credentials.AccessKeyId, client.Credentials.SecretAccessKey, client.Endpoint) + if err != nil { + return nil, err + } + abroadCDNClient.Config.UserAgent = buildUserAgent() + client.abroadCdnConn = abroadCDNClient + } + return do(client.abroadCdnConn) +} + func (client *BaiduClient) WithLocalDnsClient(do func(*localDns.Client) (interface{}, error)) (interface{}, error) { goSdkMutex.Lock() defer goSdkMutex.Unlock() @@ -603,7 +622,7 @@ func (client *BaiduClient) WithBLSClient(do func(*bls.Client) (interface{}, erro goSdkMutex.Lock() defer goSdkMutex.Unlock() - // Initialize the BLS client if necessary + // Initialize the LOCALDNS client if necessary if client.blsConn == nil { client.WithCommonClient(BLSCode) blsClient, err := bls.NewClient(client.Credentials.AccessKeyId, client.Credentials.SecretAccessKey, client.Endpoint) @@ -674,7 +693,7 @@ func (client *BaiduClient) WithEtClient(do func(*et.Client) (interface{}, error) func (client *BaiduClient) WithDNSClient(do func(*dns.Client) (interface{}, error)) (interface{}, error) { goSdkMutex.Lock() - // Initialize the VPN client if necessary + // Initialize the DNS client if necessary if client.dnsConn == nil { client.WithCommonClient(DNSCode) dnsClient, err := dns.NewClient(client.Credentials.AccessKeyId, client.Credentials.SecretAccessKey, client.Endpoint) diff --git a/baiducloud/connectivity/endpoint.go b/baiducloud/connectivity/endpoint.go index b873eb40..a1d6f0b8 100644 --- a/baiducloud/connectivity/endpoint.go +++ b/baiducloud/connectivity/endpoint.go @@ -28,6 +28,7 @@ const ( DTSCode = ServiceCode("DTS") IAMCode = ServiceCode("IAM") CDNCode = ServiceCode("CDN") + AbroadCDNCode = ServiceCode("ABROADCDN") LOCALDNSCode = ServiceCode("LOCALDNS") BBCCode = ServiceCode("BBC") VPNCode = ServiceCode("VPN") @@ -133,10 +134,11 @@ const ( DefaultSINRegionVPNEndPoint = "bcc.sin.baidubce.com" DefaultSINRegionEniEndPoint = "bcc.sin.baidubce.com" - DefaultCERTEndPoint = "certificate.baidubce.com" - DefaultIAMEndPoint = "iam.bj.baidubce.com" - DefaultCDNEndPoint = "cdn.baidubce.com" - DefaultDNSEndPoint = "dns.baidubce.com" + DefaultCERTEndPoint = "certificate.baidubce.com" + DefaultIAMEndPoint = "iam.bj.baidubce.com" + DefaultCDNEndPoint = "cdn.baidubce.com" + DefaultAbroadCDNEndPoint = "cdn.baidubce.com" + DefaultDNSEndPoint = "dns.baidubce.com" ) var ( @@ -154,10 +156,11 @@ var ( // Region BJ Service Endpoints RegionBJEndpoints = map[ServiceCode]string{ - CERTCode: DefaultCERTEndPoint, - IAMCode: DefaultIAMEndPoint, - CDNCode: DefaultCDNEndPoint, - DNSCode: DefaultDNSEndPoint, + CERTCode: DefaultCERTEndPoint, + IAMCode: DefaultIAMEndPoint, + CDNCode: DefaultCDNEndPoint, + AbroadCDNCode: DefaultAbroadCDNEndPoint, + DNSCode: DefaultDNSEndPoint, BCCCode: DefaultBJRegionBccEndPoint, BBCCode: DefaultBJRegionBbcEndPoint, @@ -188,10 +191,11 @@ var ( // Region BD Service Endpoints RegionBDEndpoints = map[ServiceCode]string{ - CERTCode: DefaultCERTEndPoint, - IAMCode: DefaultIAMEndPoint, - CDNCode: DefaultCDNEndPoint, - DNSCode: DefaultDNSEndPoint, + CERTCode: DefaultCERTEndPoint, + IAMCode: DefaultIAMEndPoint, + CDNCode: DefaultCDNEndPoint, + AbroadCDNCode: DefaultAbroadCDNEndPoint, + DNSCode: DefaultDNSEndPoint, BCCCode: DefaultBDRegionBccEndPoint, VPCCode: DefaultBDRegionBccEndPoint, @@ -208,10 +212,11 @@ var ( // Region GZ Service Endpoints RegionGZEndpoints = map[ServiceCode]string{ - CERTCode: DefaultCERTEndPoint, - IAMCode: DefaultIAMEndPoint, - CDNCode: DefaultCDNEndPoint, - DNSCode: DefaultDNSEndPoint, + CERTCode: DefaultCERTEndPoint, + IAMCode: DefaultIAMEndPoint, + CDNCode: DefaultCDNEndPoint, + AbroadCDNCode: DefaultAbroadCDNEndPoint, + DNSCode: DefaultDNSEndPoint, BCCCode: DefaultGZRegionBccEndPoint, VPNCode: DefaultGZRegionVpnEndPoint, @@ -236,10 +241,11 @@ var ( // Region SU Service Endpoints RegionSUEndpoints = map[ServiceCode]string{ - CERTCode: DefaultCERTEndPoint, - IAMCode: DefaultIAMEndPoint, - CDNCode: DefaultCDNEndPoint, - DNSCode: DefaultDNSEndPoint, + CERTCode: DefaultCERTEndPoint, + IAMCode: DefaultIAMEndPoint, + CDNCode: DefaultCDNEndPoint, + AbroadCDNCode: DefaultAbroadCDNEndPoint, + DNSCode: DefaultDNSEndPoint, BCCCode: DefaultSURegionBccEndPoint, BBCCode: DefaultSURegionBbcEndPoint, @@ -266,10 +272,11 @@ var ( // Region FSH Service Endpoints RegionFSHEndpoints = map[ServiceCode]string{ - CERTCode: DefaultCERTEndPoint, - IAMCode: DefaultIAMEndPoint, - CDNCode: DefaultCDNEndPoint, - DNSCode: DefaultDNSEndPoint, + CERTCode: DefaultCERTEndPoint, + IAMCode: DefaultIAMEndPoint, + CDNCode: DefaultCDNEndPoint, + AbroadCDNCode: DefaultAbroadCDNEndPoint, + DNSCode: DefaultDNSEndPoint, BCCCode: DefaultFSHRegionBccEndPoint, VPNCode: DefaultFSHRegionVPNEndPoint, @@ -280,10 +287,11 @@ var ( // Region FWH Service Endpoints RegionFWHEndpoints = map[ServiceCode]string{ - CERTCode: DefaultCERTEndPoint, - IAMCode: DefaultIAMEndPoint, - CDNCode: DefaultCDNEndPoint, - DNSCode: DefaultDNSEndPoint, + CERTCode: DefaultCERTEndPoint, + IAMCode: DefaultIAMEndPoint, + CDNCode: DefaultCDNEndPoint, + AbroadCDNCode: DefaultAbroadCDNEndPoint, + DNSCode: DefaultDNSEndPoint, BCCCode: DefaultFWHRegionBccEndPoint, BBCCode: DefaultFWHRegionBbcEndPoint, @@ -308,10 +316,11 @@ var ( // Region HKG Service Endpoints RegionHKGEndpoints = map[ServiceCode]string{ - CERTCode: DefaultCERTEndPoint, - IAMCode: DefaultIAMEndPoint, - CDNCode: DefaultCDNEndPoint, - DNSCode: DefaultDNSEndPoint, + CERTCode: DefaultCERTEndPoint, + IAMCode: DefaultIAMEndPoint, + CDNCode: DefaultCDNEndPoint, + AbroadCDNCode: DefaultAbroadCDNEndPoint, + DNSCode: DefaultDNSEndPoint, BCCCode: DefaultHKGRegionBccEndPoint, BBCCode: DefaultHKGRegionBbcEndPoint, @@ -332,10 +341,11 @@ var ( // Region SIN Service Endpoints RegionSINEndpoints = map[ServiceCode]string{ - CERTCode: DefaultCERTEndPoint, - IAMCode: DefaultIAMEndPoint, - CDNCode: DefaultCDNEndPoint, - DNSCode: DefaultDNSEndPoint, + CERTCode: DefaultCERTEndPoint, + IAMCode: DefaultIAMEndPoint, + CDNCode: DefaultCDNEndPoint, + AbroadCDNCode: DefaultAbroadCDNEndPoint, + DNSCode: DefaultDNSEndPoint, BCCCode: DefaultSINRegionBccEndPoint, VPCCode: DefaultSINRegionBccEndPoint, diff --git a/baiducloud/provider.go b/baiducloud/provider.go index dc1a1081..c1ee59bd 100644 --- a/baiducloud/provider.go +++ b/baiducloud/provider.go @@ -6,116 +6,131 @@ The provider needs to be configured with the proper credentials before it can be Use the navigation to the left to read about the available resources. -Example Usage +# Example Usage ```hcl # Configure the BaiduCloud Provider -provider "baiducloud" { - access_key = "${var.access_key}" - secret_key = "${var.secret_key}" - region = "${var.region}" -} + + provider "baiducloud" { + access_key = "${var.access_key}" + secret_key = "${var.secret_key}" + region = "${var.region}" + } + ``` -Resources List +# Resources List Data Sources - baiducloud_vpcs - baiducloud_subnets - baiducloud_route_rules - baiducloud_acls - baiducloud_nat_gateways - baiducloud_peer_conns - baiducloud_bos_buckets - baiducloud_bos_bucket_objects - baiducloud_appblbs - baiducloud_appblb_listeners - baiducloud_appblb_server_groups - baiducloud_eips - baiducloud_instances - baiducloud_cdss - baiducloud_security_groups - baiducloud_security_group_rules - baiducloud_snapshots - baiducloud_auto_snapshot_policies - baiducloud_zones - baiducloud_specs - baiducloud_images - baiducloud_certs - baiducloud_cfc_function - baiducloud_scs_specs - baiducloud_scss - baiducloud_cce_versions - baiducloud_cce_container_net - baiducloud_cce_cluster_nodes - baiducloud_cce_kubeconfig - baiducloud_ccev2_container_cidr - baiducloud_ccev2_clusterip_cidr - baiducloud_ccev2_cluster_instances - baiducloud_ccev2_instance_group_instances - baiducloud_dtss + + baiducloud_vpcs + baiducloud_subnets + baiducloud_route_rules + baiducloud_acls + baiducloud_nat_gateways + baiducloud_peer_conns + baiducloud_bos_buckets + baiducloud_bos_bucket_objects + baiducloud_appblbs + baiducloud_appblb_listeners + baiducloud_appblb_server_groups + baiducloud_eips + baiducloud_instances + baiducloud_cdss + baiducloud_security_groups + baiducloud_security_group_rules + baiducloud_snapshots + baiducloud_auto_snapshot_policies + baiducloud_zones + baiducloud_specs + baiducloud_images + baiducloud_certs + baiducloud_cfc_function + baiducloud_scs_specs + baiducloud_scss + baiducloud_cce_versions + baiducloud_cce_container_net + baiducloud_cce_cluster_nodes + baiducloud_cce_kubeconfig + baiducloud_ccev2_container_cidr + baiducloud_ccev2_clusterip_cidr + baiducloud_ccev2_cluster_instances + baiducloud_ccev2_instance_group_instances + baiducloud_dtss CERT Resources - baiducloud_cert + + baiducloud_cert EIP Resources - baiducloud_eip - baiducloud_eip_association + + baiducloud_eip + baiducloud_eip_association APPBLB Resources - baiducloud_appblb - baiducloud_appblb_server_group - baiducloud_appblb_listener + + baiducloud_appblb + baiducloud_appblb_server_group + baiducloud_appblb_listener BCC Resources - baiducloud_instance - baiducloud_security_group - baiducloud_security_group_rule - baiducloud_cds - baiducloud_cds_attachment - baiducloud_snapshot - baiducloud_auto_snapshot_policy + + baiducloud_instance + baiducloud_security_group + baiducloud_security_group_rule + baiducloud_cds + baiducloud_cds_attachment + baiducloud_snapshot + baiducloud_auto_snapshot_policy VPC Resources - baiducloud_vpc - baiducloud_subnet - baiducloud_route_rule - baiducloud_acl - baiducloud_nat_gateway - baiducloud_nat_snat_rule - baiducloud_peer_conn - baiducloud_peer_conn_acceptor + + baiducloud_vpc + baiducloud_subnet + baiducloud_route_rule + baiducloud_acl + baiducloud_nat_gateway + baiducloud_nat_snat_rule + baiducloud_peer_conn + baiducloud_peer_conn_acceptor BOS Resources - baiducloud_bos_bucket - baiducloud_bos_bucket_object + + baiducloud_bos_bucket + baiducloud_bos_bucket_object CFC Resources - baiducloud_cfc_function - baiducloud_cfc_alias - baiducloud_cfc_trigger - baiducloud_cfc_version + + baiducloud_cfc_function + baiducloud_cfc_alias + baiducloud_cfc_trigger + baiducloud_cfc_version SCS Resources - baiducloud_scs + + baiducloud_scs DTS Resources - baiducloud_dts + + baiducloud_dts CCE Resources - baiducloud_cce_cluster + + baiducloud_cce_cluster CCEv2 Resources - baiducloud_ccev2_cluster - baiducloud_ccev2_instance_group + + baiducloud_ccev2_cluster + baiducloud_ccev2_instance_group IAM Resources - baiducloud_iam_user - baiducloud_iam_group - baiducloud_iam_group_membership - baiducloud_iam_policy - baiducloud_iam_user_policy_attachment - baiducloud_iam_group_policy_attachment + + baiducloud_iam_user + baiducloud_iam_group + baiducloud_iam_group_membership + baiducloud_iam_policy + baiducloud_iam_user_policy_attachment + baiducloud_iam_group_policy_attachment */ package baiducloud @@ -125,6 +140,7 @@ import ( "github.com/terraform-providers/terraform-provider-baiducloud/baiducloud/service/bcc" "github.com/terraform-providers/terraform-provider-baiducloud/baiducloud/service/bec" "github.com/terraform-providers/terraform-provider-baiducloud/baiducloud/service/cdn" + "github.com/terraform-providers/terraform-provider-baiducloud/baiducloud/service/cdn/abroad" "github.com/terraform-providers/terraform-provider-baiducloud/baiducloud/service/iam" "github.com/terraform-providers/terraform-provider-baiducloud/baiducloud/service/mongodb" "github.com/terraform-providers/terraform-provider-baiducloud/baiducloud/service/snic" @@ -302,6 +318,7 @@ func Provider() terraform.ResourceProvider { "baiducloud_iam_user_policy_attachment": resourceBaiduCloudIamUserPolicyAttachment(), "baiducloud_iam_group_policy_attachment": resourceBaiduCloudIamGroupPolicyAttachment(), "baiducloud_cdn_domain": cdn.ResourceDomain(), + "baiducloud_abroad_cdn_domain": abroad.ResourceAbroadDomain(), "baiducloud_cdn_domain_config_cache": cdn.ResourceDomainConfigCache(), "baiducloud_cdn_domain_config_acl": cdn.ResourceDomainConfigACL(), "baiducloud_cdn_domain_config_origin": cdn.ResourceDomainConfigOrigin(), @@ -380,6 +397,9 @@ func init() { "cdn_endpoint": "Use this to override the default endpoint URL constructed from the `region`. It's typically used to connect to custom CDN endpoints.", + "abroad_cdn_endpoint": "Use this to override the default endpoint URL constructed from the `region`." + + " It's typically used to connect to custom Abroad CDN endpoints.", + "bbc_endpoint": "Use this to override the default endpoint URL constructed from the `region`. It's typically used to connect to custom BBC endpoints.", "vpn_endpoint": "Use this to override the default endpoint URL constructed from the `region`. It's typically used to connect to custom VPN endpoints.", @@ -475,6 +495,12 @@ func endpointsSchema() *schema.Schema { Default: "", Description: descriptions["cdn_endpoint"], }, + "abroad_cdn": { + Type: schema.TypeString, + Optional: true, + Default: "", + Description: descriptions["abroad_cdn_endpoint"], + }, "bbc": { Type: schema.TypeString, Optional: true, @@ -521,6 +547,7 @@ func endpointsToHash(v interface{}) int { buf.WriteString(fmt.Sprintf("%s-", m["rds"].(string))) buf.WriteString(fmt.Sprintf("%s-", m["dts"].(string))) buf.WriteString(fmt.Sprintf("%s-", m["cdn"].(string))) + buf.WriteString(fmt.Sprintf("%s-", m["abroad_cdn"].(string))) buf.WriteString(fmt.Sprintf("%s-", m["bbc"].(string))) buf.WriteString(fmt.Sprintf("%s-", m["vpn"].(string))) buf.WriteString(fmt.Sprintf("%s-", m["dns"].(string))) @@ -589,6 +616,7 @@ func providerConfigure(d *schema.ResourceData) (interface{}, error) { config.ConfigEndpoints[connectivity.RDSCode] = strings.TrimSpace(endpoints["rds"].(string)) config.ConfigEndpoints[connectivity.DTSCode] = strings.TrimSpace(endpoints["dts"].(string)) config.ConfigEndpoints[connectivity.CDNCode] = strings.TrimSpace(endpoints["cdn"].(string)) + config.ConfigEndpoints[connectivity.AbroadCDNCode] = strings.TrimSpace(endpoints["abroad_cdn"].(string)) config.ConfigEndpoints[connectivity.BBCCode] = strings.TrimSpace(endpoints["bbc"].(string)) config.ConfigEndpoints[connectivity.VPNCode] = strings.TrimSpace(endpoints["vpn"].(string)) config.ConfigEndpoints[connectivity.DNSCode] = strings.TrimSpace(endpoints["dns"].(string)) diff --git a/baiducloud/service/cdn/abroad/convert.go b/baiducloud/service/cdn/abroad/convert.go new file mode 100644 index 00000000..5e0c42d8 --- /dev/null +++ b/baiducloud/service/cdn/abroad/convert.go @@ -0,0 +1,72 @@ +package abroad + +import ( + "github.com/baidubce/bce-sdk-go/services/cdn/abroad/api" + "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/terraform-providers/terraform-provider-baiducloud/baiducloud/hashcode" + + "strconv" +) + +func expandAbroadCacheTTLs(tfSet *schema.Set) []api.CacheTTL { + var list []api.CacheTTL + for _, v := range tfSet.List() { + tfMap := v.(map[string]interface{}) + list = append(list, api.CacheTTL{ + Type: tfMap["type"].(string), + Value: tfMap["value"].(string), + Weight: tfMap["weight"].(int), + TTL: tfMap["ttl"].(int), + OverrideOrigin: tfMap["override_origin"].(bool), + }) + } + return list +} + +func flattenAbroadCacheTTLs(cacheTTLs []api.CacheTTL) *schema.Set { + tfSet := schema.NewSet(cacheTTLHash, nil) + for _, v := range cacheTTLs { + tfSet.Add(map[string]interface{}{ + "type": v.Type, + "value": v.Value, + "weight": v.Weight, + "ttl": v.TTL, + "override_origin": v.OverrideOrigin, + }) + } + return tfSet +} + +func cacheTTLHash(v interface{}) int { + tfMap := v.(map[string]interface{}) + var s []string + + if v, ok := tfMap["type"]; ok { + s = append(s, v.(string)) + } + if v, ok := tfMap["value"]; ok { + s = append(s, v.(string)) + } + if v, ok := tfMap["ttl"]; ok { + s = append(s, strconv.Itoa(v.(int))) + } + if v, ok := tfMap["weight"]; ok { + s = append(s, strconv.Itoa(v.(int))) + } + if v, ok := tfMap["override_origin"]; ok { + s = append(s, v.(string)) + } + return hashcode.Strings(s) +} + +func flattenAbroadOriginPeers(originPeers []api.OriginPeer) interface{} { + var tfList []map[string]interface{} + for _, v := range originPeers { + tfList = append(tfList, map[string]interface{}{ + "type": v.Type, + "addr": v.Addr, + "backup": v.Backup, + }) + } + return tfList +} diff --git a/baiducloud/service/cdn/abroad/find.go b/baiducloud/service/cdn/abroad/find.go new file mode 100644 index 00000000..10c5d2fb --- /dev/null +++ b/baiducloud/service/cdn/abroad/find.go @@ -0,0 +1,31 @@ +package abroad + +import ( + "github.com/baidubce/bce-sdk-go/model" + "github.com/baidubce/bce-sdk-go/services/cdn/abroad" + "github.com/baidubce/bce-sdk-go/services/cdn/abroad/api" + "github.com/terraform-providers/terraform-provider-baiducloud/baiducloud/connectivity" +) + +func FindAbroadDomainConfigByName(conn *connectivity.BaiduClient, domainName string) (*api.DomainConfig, error) { + raw, err := conn.WithAbroadCdnClient(func(client *abroad.Client) (interface{}, error) { + return client.GetDomainConfig(domainName) + }) + + if err != nil { + return nil, err + } + + return raw.(*api.DomainConfig), nil +} + +func FindAbroadDomainTagsByName(conn *connectivity.BaiduClient, domainName string) ([]model.TagModel, error) { + raw, err := conn.WithAbroadCdnClient(func(client *abroad.Client) (interface{}, error) { + return client.GetTags(domainName) + }) + + if err != nil { + return nil, err + } + return raw.([]model.TagModel), nil +} diff --git a/baiducloud/service/cdn/abroad/resource_abroad_domain.go b/baiducloud/service/cdn/abroad/resource_abroad_domain.go new file mode 100644 index 00000000..4abf68dc --- /dev/null +++ b/baiducloud/service/cdn/abroad/resource_abroad_domain.go @@ -0,0 +1,180 @@ +package abroad + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/model" + "github.com/baidubce/bce-sdk-go/services/cdn/abroad" + "github.com/baidubce/bce-sdk-go/services/cdn/abroad/api" + "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/helper/validation" + "github.com/terraform-providers/terraform-provider-baiducloud/baiducloud/connectivity" + "github.com/terraform-providers/terraform-provider-baiducloud/baiducloud/flex" + + "log" +) + +func ResourceAbroadDomain() *schema.Resource { + return &schema.Resource{ + + Description: "Use this resource to manage abroad acceleration domain and its origin configuration. \n\n" + + "More information can be found in the [Developer Guide](https://cloud.baidu.com/doc/CDN-ABROAD/s/gjwvxiywx). \n\n", + + Importer: &schema.ResourceImporter{ + State: schema.ImportStatePassthrough, + }, + + Create: resourceAbroadDomainCreate, + Read: resourceAbroadDomainRead, + Update: resourceAbroadDomainUpdate, + Delete: resourceAbroadDomainDelete, + + Schema: map[string]*schema.Schema{ + "domain": { + Type: schema.TypeString, + Description: "Name of the acceleration domain.", + Required: true, + }, + "origin": { + Type: schema.TypeList, + Description: "Origin server configuration of the acceleration domain.", + Required: true, + MinItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "type": { + Type: schema.TypeString, + Description: "origin type, value is IP or DOMAIN", + Required: true, + ValidateFunc: validation.StringInSlice([]string{"IP", "DOMAIN"}, false), + }, + "backup": { + Type: schema.TypeBool, + Description: "Whether is a backup origin server. Defaults to `false`.", + Optional: true, + Default: false, + }, + "addr": { + Type: schema.TypeString, + Description: "The ip address when forwarding to origin server", + Required: true, + }, + }, + }, + }, + "tags": flex.TagsSchema(), + }, + } + +} + +func resourceAbroadDomainCreate(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*connectivity.BaiduClient) + + domain := d.Get("domain").(string) + + _, err := conn.WithAbroadCdnClient(func(abroadCdnClient *abroad.Client) (interface{}, error) { + tags := make([]model.TagModel, 0) + var origin []api.OriginPeer + if v, ok := d.GetOk("tags"); ok { + tags = flex.TranceTagMapToModel(v.(map[string]interface{})) + } + if v, ok := d.GetOk("origin"); ok { + origin = expandOriginPeers(v.([]interface{})) + } + log.Printf("[DEBUG] Create Abroad CDN Domain: %s %+v", domain, origin) + return abroadCdnClient.CreateDomainWithOptions(domain, origin, abroad.CreateDomainWithTags(tags)) + }) + + if err != nil { + return fmt.Errorf("error creating Abroad CDN Domain (%s): %w", domain, err) + } + + d.SetId(domain) + + return resourceAbroadDomainRead(d, meta) +} + +func resourceAbroadDomainRead(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*connectivity.BaiduClient) + domain := d.Id() + + log.Printf("[DEBUG] Read Abroad CDN Domain (%s)", domain) + config, err := FindAbroadDomainConfigByName(conn, domain) + if err != nil { + return fmt.Errorf("error reading Abroad CDN Domain (%s): %w", domain, err) + } + err = d.Set("domain", config.Domain) + if err != nil { + return fmt.Errorf("error setting domain for Abroad CDN Domain (%s): %w", domain, err) + } + err = d.Set("origin", flattenAbroadOriginPeers(config.Origin)) + if err != nil { + return fmt.Errorf("error setting origin for Abroad CDN Domain (%s): %w", domain, err) + } + tags, err := FindAbroadDomainTagsByName(conn, domain) + if err != nil { + return fmt.Errorf("error reading tags for Abroad CDN Domain (%s): %w", domain, err) + } + err = d.Set("tags", flex.FlattenTagsToMap(tags)) + if err != nil { + return fmt.Errorf("error setting tag for Abroad CDN Domain (%s): %w", domain, err) + } + + return nil +} + +func resourceAbroadDomainUpdate(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*connectivity.BaiduClient) + domain := d.Id() + + if err := updateAbroadOrigins(d, conn, domain); err != nil { + return err + } + return nil +} + +func resourceAbroadDomainDelete(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*connectivity.BaiduClient) + domain := d.Id() + + log.Printf("[DEBUG] Delete abroad CDN Domain: %s", domain) + + _, err := conn.WithAbroadCdnClient(func(client *abroad.Client) (interface{}, error) { + return nil, client.DeleteDomain(domain) + }) + if err != nil { + return fmt.Errorf("error deleting abroad CDN Domain (%s): %w", domain, err) + } + + return nil +} + +func expandOriginPeers(tfList []interface{}) []api.OriginPeer { + var originPeers []api.OriginPeer + for _, v := range tfList { + tfMap := v.(map[string]interface{}) + originPeers = append(originPeers, api.OriginPeer{ + Type: tfMap["type"].(string), + Addr: tfMap["addr"].(string), + Backup: tfMap["backup"].(bool), + }) + } + return originPeers +} + +func updateAbroadOrigins(d *schema.ResourceData, conn *connectivity.BaiduClient, domain string) error { + if d.HasChange("origin") { + log.Printf("[DEBUG] Update Abroad CDN Domain origins(%s)", domain) + + origins := expandOriginPeers(d.Get("origin").([]interface{})) + + _, err := conn.WithAbroadCdnClient(func(client *abroad.Client) (interface{}, error) { + return nil, client.SetDomainOrigin(domain, origins) + }) + if err != nil { + return fmt.Errorf("error updating Abroad CDN Domain (%s) origins: %w", domain, err) + } + } + return nil +} diff --git a/baiducloud/service/cdn/abroad/resource_abroad_domain_test.go b/baiducloud/service/cdn/abroad/resource_abroad_domain_test.go new file mode 100644 index 00000000..f01c0fa3 --- /dev/null +++ b/baiducloud/service/cdn/abroad/resource_abroad_domain_test.go @@ -0,0 +1,88 @@ +package abroad_test + +import ( + "fmt" + "github.com/hashicorp/terraform-plugin-sdk/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/terraform-providers/terraform-provider-baiducloud/baiducloud/acctest" + "github.com/terraform-providers/terraform-provider-baiducloud/baiducloud/connectivity" + "github.com/terraform-providers/terraform-provider-baiducloud/baiducloud/service/cdn" + "testing" +) + +const ( + testAccAbroadCdnDomainResourceType = "baiducloud_abroad_cdn_domain" +) + +func TestAbroadAccDomain(t *testing.T) { + domain := "acc.test.com" + resourceName := testAccAbroadCdnDomainResourceType + ".test" + + resource.Test(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t) }, + Providers: acctest.Providers, + CheckDestroy: testAccCheckDomainDestroy, + Steps: []resource.TestStep{ + { + Config: testAccDomainCreate(domain), + Check: resource.ComposeTestCheckFunc( + testAccCheckDomainExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "domain", domain), + resource.TestCheckResourceAttr(resourceName, "origin.0.type", "IP"), + resource.TestCheckResourceAttr(resourceName, "origin.0.addr", "1.2.3.4"), + resource.TestCheckResourceAttr(resourceName, "origin.0.backup", "false"), + ), + }, + }, + }) +} + +func testAccCheckDomainDestroy(s *terraform.State) error { + conn := acctest.Provider.Meta().(*connectivity.BaiduClient) + + for _, rs := range s.RootModule().Resources { + if rs.Type != testAccAbroadCdnDomainResourceType { + continue + } + + _, err := cdn.FindDomainStatusByName(conn, rs.Primary.ID) + if err != nil { + if _, ok := err.(*resource.NotFoundError); ok { + continue + } + return err + } + return fmt.Errorf("Abroad CDN Domain %s still exist", rs.Primary.ID) + } + + return nil +} + +func testAccCheckDomainExists(resourceName string) resource.TestCheckFunc { + return func(state *terraform.State) error { + rs, err := acctest.CheckResource(resourceName, state) + if err != nil { + return err + } + + conn := acctest.Provider.Meta().(*connectivity.BaiduClient) + _, err = cdn.FindDomainStatusByName(conn, rs.Primary.ID) + + if err != nil { + return err + } + return nil + } +} + +func testAccDomainCreate(domain string) string { + return fmt.Sprintf(` + resource "baiducloud_abroad_cdn_domain" "default" { + domain = "%s" + origin { + backup = false + type = "IP" + addr = "1.2.3.4" + } + }`, domain) +} \ No newline at end of file diff --git a/examples/resources/baiducloud_abroad_cdn_domain/import.sh b/examples/resources/baiducloud_abroad_cdn_domain/import.sh new file mode 100644 index 00000000..77f16d08 --- /dev/null +++ b/examples/resources/baiducloud_abroad_cdn_domain/import.sh @@ -0,0 +1 @@ +terraform import baiducloud_abroad_cdn_domain.example example1.domain.com diff --git a/examples/resources/baiducloud_abroad_cdn_domain/resource.tf b/examples/resources/baiducloud_abroad_cdn_domain/resource.tf new file mode 100644 index 00000000..345a80b7 --- /dev/null +++ b/examples/resources/baiducloud_abroad_cdn_domain/resource.tf @@ -0,0 +1,12 @@ +resource "baiducloud_abroad_cdn_domain" "default" { + domain = "test.cdn.cloud" + + origin { + backup = false + type = "IP" + addr = "1.2.3.4" + } + tags = { + terraform = "terraform-test2" + } +} \ No newline at end of file diff --git a/vendor/github.com/baidubce/bce-sdk-go/services/cdn/abroad/api/cache.go b/vendor/github.com/baidubce/bce-sdk-go/services/cdn/abroad/api/cache.go new file mode 100644 index 00000000..b7ed3b7c --- /dev/null +++ b/vendor/github.com/baidubce/bce-sdk-go/services/cdn/abroad/api/cache.go @@ -0,0 +1,269 @@ +package api + +import ( + "errors" + "time" + + "github.com/baidubce/bce-sdk-go/bce" + "github.com/baidubce/bce-sdk-go/util" +) + +type PurgedId string +type PrefetchId string + +// CStatusQueryData defined a struct for the query conditions about the tasks' progress +type CStatusQueryData struct { + Id string + StartTime string + EndTime string + Url string + Marker string +} + +// CRecordQueryData defined a struct for the query conditions about the operated records +type CRecordQueryData struct { + EndTime string + StartTime string + Url string + Marker string + TaskType string +} + +// PurgeTask defined a struct for purged task +type PurgeTask struct { + Url string `json:"url"` + Type string `json:"type,omitempty"` +} + +// PrefetchTask defined a struct for prefetch task +type PrefetchTask struct { + Url string `json:"url"` +} + +// CachedDetail defined a struct for task details +type CachedDetail struct { + Status string `json:"status"` + CreatedAt string `json:"createdAt"` + StartedAt string `json:"startedAt"` + FinishedAt string `json:"finishedAt"` + Progress int64 `json:"progress"` +} + +// PurgedDetail defined a struct for purged task information +type PurgedDetail struct { + *CachedDetail + Task PurgeTask `json:"task"` +} + +// PrefetchDetail defined a struct for prefetch task information +type PrefetchDetail struct { + *CachedDetail + Task PrefetchTask `json:"task"` +} + +// PurgedStatus defined a struct for purged status +type PurgedStatus struct { + Details []PurgedDetail `json:"details"` + IsTruncated bool `json:"isTruncated"` + NextMarker string `json:"nextMarker"` +} + +// PrefetchStatus defined a struct for prefetch status +type PrefetchStatus struct { + Details []PrefetchDetail `json:"details"` + IsTruncated bool `json:"isTruncated"` + NextMarker string `json:"nextMarker"` +} + +// QuotaDetail defined a struct for query quota +type QuotaDetail struct { + UrlPurgeQuota int64 `json:"urlPurgeQuota"` + UrlPurgeRemain int64 `json:"urlPurgeRemain"` + DirPurgeQuota int64 `json:"dirPurgeQuota"` + DirPurgeRemain int64 `json:"dirPurgeRemain"` + PrefetchQuota int64 `json:"prefetchQuota"` + PrefetchRemain int64 `json:"prefetchRemain"` +} + +// Purge - tells the CDN system to purge the specified files +// For more details, please refer https://cloud.baidu.com/doc/CDN-ABROAD/s/Zkbsy0k8j +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - tasks: the tasks about purging the files from the CDN nodes +// RETURNS: +// - PurgedId: an ID representing a purged task, using it to search the task progress +// - error: nil if success otherwise the specific error +func Purge(cli bce.Client, tasks []PurgeTask) (PurgedId, error) { + respObj := &struct { + Id string `json:"id"` + }{} + + err := httpRequest(cli, "POST", "/v2/abroad/cache/purge", nil, &struct { + Tasks []PurgeTask `json:"tasks"` + }{ + Tasks: tasks, + }, respObj) + if err != nil { + return "", err + } + + return PurgedId(respObj.Id), nil +} + +// GetPurgedStatus - get the purged progress +// For details, please refer https://cloud.baidu.com/doc/CDN-ABROAD/s/ikbsy9cvb +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - queryData: querying conditions, it contains the time interval, the task ID and the specified url +// RETURNS: +// - *PurgedStatus: the details about the purged +// - error: nil if success otherwise the specific error +func GetPurgedStatus(cli bce.Client, queryData *CStatusQueryData) (*PurgedStatus, error) { + if queryData == nil { + queryData = &CStatusQueryData{} + } + + params := map[string]string{} + if queryData.Id != "" { + params["id"] = queryData.Id + } + if err := getTimeParams(params, queryData.StartTime, queryData.EndTime); err != nil { + return nil, err + } + + if queryData.Url != "" { + params["url"] = queryData.Url + } + if queryData.Marker != "" { + params["marker"] = queryData.Marker + } + + respObj := &PurgedStatus{} + err := httpRequest(cli, "GET", "/v2/abroad/cache/purge", params, nil, respObj) + if err != nil { + return nil, err + } + + return respObj, nil +} + +// Prefetch - tells the CDN system to prefetch the specified files +// For details, please refer https://cloud.baidu.com/doc/CDN-ABROAD/s/Dlj5ch09q +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - tasks: the tasks about prefetch the files from the CDN nodes +// - error: nil if success otherwise the specific error +func Prefetch(cli bce.Client, tasks []PrefetchTask) (PrefetchId, error) { + respObj := &struct { + Id string `json:"id"` + }{} + + err := httpRequest(cli, "POST", "/v2/abroad/cache/prefetch", nil, &struct { + Tasks []PrefetchTask `json:"tasks"` + }{ + Tasks: tasks, + }, respObj) + if err != nil { + return "", err + } + + return PrefetchId(respObj.Id), nil +} + +// GetPrefetchStatus - get the prefetch progress +// For details, please refer https://cloud.baidu.com/doc/CDN-ABROAD/s/Mlj5e9y0i +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - queryData: querying conditions, it contains the time interval, the task ID and the specified url +// RETURNS: +// - *PrefetchStatus: the details about the prefetch +// - error: nil if success otherwise the specific error +func GetPrefetchStatus(cli bce.Client, queryData *CStatusQueryData) (*PrefetchStatus, error) { + if queryData == nil { + queryData = &CStatusQueryData{} + } + + params := map[string]string{} + if queryData.Id != "" { + params["id"] = queryData.Id + } + if err := getTimeParams(params, queryData.StartTime, queryData.EndTime); err != nil { + return nil, err + } + + if queryData.Url != "" { + params["url"] = queryData.Url + } + if queryData.Marker != "" { + params["marker"] = queryData.Marker + } + + respObj := &PrefetchStatus{} + err := httpRequest(cli, "GET", "/v2/abroad/cache/prefetch", params, nil, respObj) + if err != nil { + return nil, err + } + + return respObj, nil +} + +// GetQuota - get the quota about purge and prefetch +// For details, please refer https://cloud.baidu.com/doc/CDN-ABROAD/s/flnoakciq +// +// RETURNS: +// - cli: the client agent which can perform sending request +// - QuotaDetail: the quota details about a specified user +// - error: nil if success otherwise the specific error +func GetQuota(cli bce.Client) (*QuotaDetail, error) { + respObj := &QuotaDetail{} + err := httpRequest(cli, "GET", "/v2/abroad/cache/quota", nil, nil, respObj) + if err != nil { + return nil, err + } + + return respObj, nil +} + +func getTimeParams(params map[string]string, startTime, endTime string) error { + // get "endTime" + endTs := int64(0) + if endTime == "" { + // default current time + endTs = time.Now().Unix() + params["endTime"] = util.FormatISO8601Date(endTs) + } else { + t, err := util.ParseISO8601Date(endTime) + if err != nil { + return err + } + endTs = t.Unix() + params["endTime"] = endTime + } + + // get "startTime", the default "startTime" is one day later than the "endTime" + startTs := int64(0) + if startTime == "" { + startTs = endTs - 24*60*60 + params["startTime"] = util.FormatISO8601Date(startTs) + } else { + t, err := util.ParseISO8601Date(startTime) + if err != nil { + return err + } + startTs = t.Unix() + params["startTime"] = startTime + } + + // the "startTime should be less than the "endTime" + // if we set "startTime" but not "endTime", we normally assign the current time to the "endTime", + // in this condition, we might get "startTs > endTs" + if startTs > endTs { + return errors.New("error time range, the startTime should be less than the endTime") + } + + return nil +} diff --git a/vendor/github.com/baidubce/bce-sdk-go/services/cdn/abroad/api/domain.go b/vendor/github.com/baidubce/bce-sdk-go/services/cdn/abroad/api/domain.go new file mode 100644 index 00000000..378c4cc5 --- /dev/null +++ b/vendor/github.com/baidubce/bce-sdk-go/services/cdn/abroad/api/domain.go @@ -0,0 +1,174 @@ +package api + +import ( + "errors" + "fmt" + + "github.com/baidubce/bce-sdk-go/bce" + "github.com/baidubce/bce-sdk-go/model" +) + +// DomainStatus defined a struct for domain info, +// the status only include "RUNNING", "OPERATING" and "STOPPED", +// the other status is undefined +type DomainStatus struct { + Domain string `json:"domain"` + Status string `json:"status"` +} + +// DomainCreatedInfo defined a struct for `CreateDomain` return +type DomainCreatedInfo struct { + Status string `json:"status"` + Cname string `json:"cname"` +} + +// ListDomains - list all domains that in ABROAD-CDN service +// For details, please refer https://cloud.baidu.com/doc/CDN-ABROAD/s/1kbsyj9m6 +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - marker: a marker is a start point of searching +// +// RETURNS: +// - []string: domains belongs to the user +// - string: a marker for next searching, empty if is in the end +// - error: nil if success otherwise the specific error +func ListDomains(cli bce.Client, marker string) ([]string, string, error) { + type domainInfo struct { + Name string `json:"name"` + } + + respObj := &struct { + IsTruncated bool `json:"isTruncated"` + Domains []domainInfo `json:"domains"` + NextMarker string `json:"nextMarker"` + }{} + + params := map[string]string{} + if marker != "" { + params["marker"] = marker + } + + err := httpRequest(cli, "GET", "/v2/abroad/domains", params, nil, respObj) + if err != nil { + return nil, "", err + } + + domains := make([]string, len(respObj.Domains)) + for i, domain := range respObj.Domains { + domains[i] = domain.Name + } + + return domains, respObj.NextMarker, nil +} + +// CreateDomain - add a specified domain into ABROAD-CDN service +// For details, please refer https://cloud.baidu.com/doc/CDN-ABROAD/s/ekbsyn5o5 +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - domain: the specified domain +// - originInit: initialized data for a ABROAD-CDN domain +// - tags: bind with the specified tags +// +// RETURNS: +// - *DomainCreatedInfo: the details about created a ABROAD-CDN domain +// - error: nil if success otherwise the specific error +func CreateDomain(cli bce.Client, domain string, originConfig []OriginPeer, tags []model.TagModel) (*DomainCreatedInfo, error) { + urlPath := fmt.Sprintf("/v2/abroad/domain/%s", domain) + respObj := &DomainCreatedInfo{} + + type Request struct { + OriginConfig []OriginPeer `json:"originConfig"` + Tags []model.TagModel `json:"tags,omitempty"` + } + + requestObject := &Request{ + OriginConfig: originConfig, + Tags: tags, + } + err := httpRequest(cli, "POST", urlPath, nil, requestObject, respObj) + if err != nil { + return nil, err + } + + return respObj, nil +} + +// EnableDomain - enable a specified domain +// For details, please refer https://cloud.baidu.com/doc/CDN-ABROAD/s/Zkbsypv9b +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - domain: the specified domain +// +// RETURNS: +// - error: nil if success otherwise the specific error +func EnableDomain(cli bce.Client, domain string) error { + if domain == "" { + return errors.New("domain parameter could not be empty") + } + + params := map[string]string{ + "enable": "", + } + urlPath := fmt.Sprintf("/v2/abroad/domain/%s", domain) + + err := httpRequest(cli, "PUT", urlPath, params, nil, nil) + if err != nil { + return err + } + + return nil +} + +// DisableDomain - disable a specified domain +// For details, please refer https://cloud.baidu.com/doc/CDN-ABROAD/s/gkbsyrdck +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - domain: the specified domain +// +// RETURNS: +// - error: nil if success otherwise the specific error +func DisableDomain(cli bce.Client, domain string) error { + if domain == "" { + return errors.New("domain parameter could not be empty") + } + + params := map[string]string{ + "disable": "", + } + urlPath := fmt.Sprintf("/v2/abroad/domain/%s", domain) + + err := httpRequest(cli, "PUT", urlPath, params, nil, nil) + if err != nil { + return err + } + + return nil +} + +// DeleteDomain - delete a specified domain from BCE CDN system +// For details, please refer https://cloud.baidu.com/doc/CDN-ABROAD/s/4kbsytf7q +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - domain: the specified domain +// +// RETURNS: +// - error: nil if success otherwise the specific error +func DeleteDomain(cli bce.Client, domain string) error { + if domain == "" { + return errors.New("domain parameter could not be empty") + } + + urlPath := fmt.Sprintf("/v2/abroad/domain/%s", domain) + + err := httpRequest(cli, "DELETE", urlPath, nil, nil, nil) + if err != nil { + return err + } + + return nil +} diff --git a/vendor/github.com/baidubce/bce-sdk-go/services/cdn/abroad/api/domain_config.go b/vendor/github.com/baidubce/bce-sdk-go/services/cdn/abroad/api/domain_config.go new file mode 100644 index 00000000..c8c78e34 --- /dev/null +++ b/vendor/github.com/baidubce/bce-sdk-go/services/cdn/abroad/api/domain_config.go @@ -0,0 +1,430 @@ +package api + +import ( + "errors" + "fmt" + + "github.com/baidubce/bce-sdk-go/bce" + "github.com/baidubce/bce-sdk-go/model" +) + +// DomainConfig defined a struct for total configurations. +type DomainConfig struct { + Domain string `json:"domain"` + Origin []OriginPeer `json:"originConfig"` + CacheTTL []CacheTTL `json:"cacheTtl"` + CacheFullUrl bool `json:"cacheFullUrl"` + OriginHost *string `json:"originHost"` + RefererACL *RefererACL `json:"refererACL"` + IpACL *IpACL `json:"ipACL"` + HTTPSConfig *HTTPSConfig `json:"https"` + Tags []model.TagModel `json:"tags"` +} + +// OriginPeer defined a struct for Origin server. +type OriginPeer struct { + Type string `json:"type"` + Addr string `json:"addr"` + Backup bool `json:"backup"` +} + +// CacheTTL defined a struct for cached rules. +type CacheTTL struct { + Type string `json:"type"` + Value string `json:"value"` + Weight int `json:"weight,omitempty"` + TTL int `json:"ttl"` + OverrideOrigin bool `json:"override_origin"` +} + +// RefererACL defined a struct for Referer whitelist or blacklist to enable hotlink protection. +type RefererACL struct { + BlackList []string `json:"blackList"` + WhiteList []string `json:"whiteList"` + AllowEmpty bool `json:"allowEmpty"` +} + +// IpACL defined a struct for IP address blacklist or whitelist. +type IpACL struct { + BlackList []string `json:"blackList"` + WhiteList []string `json:"whiteList"` +} + +type HTTPSConfig struct { + Enabled bool `json:"enabled"` + CertId string `json:"certId,omitempty"` + HttpRedirect bool `json:"httpRedirect,omitempty"` + Http2Enabled bool `json:"http2Enabled,omitempty"` +} + +// GetDomainConfig - get the configuration for the specified domain +// For details, please refer https://cloud.baidu.com/doc/CDN-ABROAD/s/9kbsye6k8 +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - domain: the specified domain +// +// RETURNS: +// - *DomainConfig: the configuration about the specified domain +// - error: nil if success otherwise the specific error +func GetDomainConfig(cli bce.Client, domain string) (*DomainConfig, error) { + urlPath := fmt.Sprintf("/v2/abroad/domain/%s/config", domain) + var config DomainConfig + err := httpRequest(cli, "GET", urlPath, nil, nil, &config) + if err != nil { + return nil, err + } + + return &config, nil +} + +// SetDomainOrigin - set the origin setting for the new +// For details, please refer https://cloud.baidu.com/doc/CDN-ABROAD/s/Gkbstcgaa +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - domain: the specified domain +// - origins: the origin servers +// +// RETURNS: +// - error: nil if success otherwise the specific error +func SetDomainOrigin(cli bce.Client, domain string, origins []OriginPeer) error { + urlPath := fmt.Sprintf("/v2/abroad/domain/%s/config", domain) + params := map[string]string{ + "origin": "", + } + + err := httpRequest(cli, "PUT", urlPath, params, &struct { + Origin []OriginPeer `json:"originConfig"` + }{ + Origin: origins, + }, nil) + + return err +} + +// SetCacheTTL - add rules to cache asserts. +// For details, please refer https://cloud.baidu.com/doc/CDN-ABROAD/s/Zkbstm0vg +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - domain: the specified domain +// - cacheTTLs: the cache setting list +// +// RETURNS: +// - error: nil if success otherwise the specific error +func SetCacheTTL(cli bce.Client, domain string, cacheTTLs []CacheTTL) error { + urlPath := fmt.Sprintf("/v2/abroad/domain/%s/config", domain) + params := map[string]string{ + "cacheTtl": "", + } + + err := httpRequest(cli, "PUT", urlPath, params, &struct { + CacheTTLs []CacheTTL `json:"cacheTtl"` + }{ + CacheTTLs: cacheTTLs, + }, nil) + if err != nil { + return err + } + + return nil +} + +// SetCacheFullUrl - set the rule to calculate the cache key, set `cacheFullUrl` to true +// means the whole query(the string right after the question mark in URL) will be added to the cache key. +// For details, please refer https://cloud.baidu.com/doc/CDN-ABROAD/s/nkbsxko6t +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - domain: the specified domain +// - cacheFullUrl: the query part in URL being added to the cache key or not +// +// RETURNS: +// - error: nil if success otherwise the specific error +func SetCacheFullUrl(cli bce.Client, domain string, cacheFullUrl bool) error { + urlPath := fmt.Sprintf("/v2/abroad/domain/%s/config", domain) + params := map[string]string{ + "cacheFullUrl": "", + } + + err := httpRequest(cli, "PUT", urlPath, params, &struct { + CacheFullUrl bool `json:"cacheFullUrl"` + }{ + CacheFullUrl: cacheFullUrl, + }, nil) + if err != nil { + return err + } + + return nil +} + +// SetHostToOrigin - Specify a default value for the HOST header for virtual sites in your origin server. +// For details, please refer https://cloud.baidu.com/doc/CDN-ABROAD/s/Pkbsxw8xw +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - domain: the specified domain +// - originHost: specified HOST header for origin server +// +// RETURNS: +// - error: nil if success otherwise the specific error +func SetHostToOrigin(cli bce.Client, domain string, originHost string) error { + urlPath := fmt.Sprintf("/v2/abroad/domain/%s/config", domain) + params := map[string]string{ + "designateHostToOrigin": "", + } + + err := httpRequest(cli, "PUT", urlPath, params, &struct { + DesignateHostToOrigin string `json:"designateHostToOrigin"` + }{ + DesignateHostToOrigin: originHost, + }, nil) + if err != nil { + return err + } + + return nil +} + +// SetRefererACL - Set a Referer whitelist or blacklist to enable hotlink protection. +// For details, please refer https://cloud.baidu.com/doc/CDN-ABROAD/s/ekbsxow69 +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - domain: the specified domain +// - refererACL: referer of whitelist or blacklist +// +// RETURNS: +// - error: nil if success otherwise the specific error +func SetRefererACL(cli bce.Client, domain string, refererACL *RefererACL) error { + urlPath := fmt.Sprintf("/v2/abroad/domain/%s/config", domain) + params := map[string]string{ + "refererACL": "", + } + + err := httpRequest(cli, "PUT", urlPath, params, &struct { + RefererACL *RefererACL `json:"refererACL"` + }{ + RefererACL: refererACL, + }, nil) + if err != nil { + return err + } + + return nil +} + +// SetIpACL - Set an IP whitelist or blacklist to block or allow requests from specific IP addresses. +// For details, please refer https://cloud.baidu.com/doc/CDN-ABROAD/s/2kbsxt693 +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - domain: the specified domain +// - ipACL: IP whitelist or blacklist +// +// RETURNS: +// - error: nil if success otherwise the specific error +func SetIpACL(cli bce.Client, domain string, ipACL *IpACL) error { + urlPath := fmt.Sprintf("/v2/abroad/domain/%s/config", domain) + params := map[string]string{ + "ipACL": "", + } + + err := httpRequest(cli, "PUT", urlPath, params, &struct { + IpACL *IpACL `json:"ipACL"` + }{ + IpACL: ipACL, + }, nil) + if err != nil { + return err + } + + return nil +} + +// HTTPSConfigOption defined a method for setting optional configurations for HTTPS config. +type HTTPSConfigOption func(interface{}) + +// HTTPSConfigCertID defined a method to pass certId witch represents a certificate uploaded in BCE SSL platform: +// https://console.bce.baidu.com/cas/#/cas/purchased/common/list. +// This Option works while the HTTPS in enabled state. +func HTTPSConfigCertID(certId string) HTTPSConfigOption { + return func(o interface{}) { + cfg, ok := o.(*httpsConfig) + if ok { + cfg.certId = certId + } + } +} + +// HTTPSConfigRedirectWith301 defined a method to enable the CDN PoPs to redirect the requests in HTTP protocol +// to the HTTPS ones, with the status 301. +// e.g. Assume that you have a CDN domain cdn.baidu.com, configured HTTPSConfigRedirectWith301, while the request +// comes just like "http://cdn.baidu.com/1.txt", the CDN Edge server would respond 301 page with Location header +// https://cdn.baidu.com/1.txt which change the scheme from "http" to "https". +// This Option works while the HTTPS in enabled state. +func HTTPSConfigRedirectWith301() HTTPSConfigOption { + return func(o interface{}) { + cfg, ok := o.(*httpsConfig) + if ok { + cfg.httpRedirect301 = true + } + } +} + +// HTTPSConfigEnableH2 defined a method to enable HTTP2 in CDN Edge server. +// This Option works while the HTTPS in enabled state. +func HTTPSConfigEnableH2() HTTPSConfigOption { + return func(o interface{}) { + cfg, ok := o.(*httpsConfig) + if ok { + cfg.enableH2 = true + } + } +} + +type httpsConfig struct { + certId string + httpRedirect301 bool + enableH2 bool +} + +// SetHTTPSConfigWithOptions - enable or disable HTTPS. +// For details, please refer https://cloud.baidu.com/doc/CDN-ABROAD/s/ckb0fx9ea +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - domain: the specified domain +// - enabled: true means enable HTTPS, otherwise disable. +// - options: more operations to configure HTTPS, the valid options are: +// 1. HTTPSConfigCertID +// 2. HTTPSConfigRedirectWith301 +// 3. HTTPSConfigEnableH2 +// +// RETURNS: +// - error: nil if success otherwise the specific error +func SetHTTPSConfigWithOptions(cli bce.Client, domain string, enabled bool, options ...HTTPSConfigOption) error { + urlPath := fmt.Sprintf("/v2/abroad/domain/%s/config", domain) + params := map[string]string{ + "https": "", + } + + var config httpsConfig + for _, opt := range options { + opt(&config) + } + + requestObj := map[string]interface{}{ + "enabled": enabled, + } + if enabled { + if config.certId == "" { + return errors.New("try enable HTTPS but the certId is empty") + } + requestObj["certId"] = config.certId + requestObj["httpRedirect"] = config.httpRedirect301 + requestObj["http2Enabled"] = config.enableH2 + } else { + if config.enableH2 { + return errors.New("config conflict: try enable HTTP2 and disable HTTPS") + } + if config.httpRedirect301 { + return errors.New("config conflict: try enable redirecting HTTPS requests to HTTP ones and disable HTTPS") + } + } + + err := httpRequest(cli, "PUT", urlPath, params, &struct { + HTTPS interface{} `json:"https"` + }{ + HTTPS: requestObj, + }, nil) + if err != nil { + return err + } + + return nil +} + +// SetHTTPSConfig - enable or disable HTTPS. +// For details, please refer https://cloud.baidu.com/doc/CDN-ABROAD/s/ckb0fx9ea +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - domain: the specified domain +// - httpsConfig: HTTPS configurations. +// +// RETURNS: +// - error: nil if success otherwise the specific error +func SetHTTPSConfig(cli bce.Client, domain string, httpsConfig *HTTPSConfig) error { + if httpsConfig == nil { + return errors.New("HTTPS config is empty") + } + + var options []HTTPSConfigOption + if httpsConfig.CertId != "" { + options = append(options, HTTPSConfigCertID(httpsConfig.CertId)) + } + if httpsConfig.HttpRedirect { + options = append(options, HTTPSConfigRedirectWith301()) + } + if httpsConfig.Http2Enabled { + options = append(options, HTTPSConfigEnableH2()) + } + return SetHTTPSConfigWithOptions(cli, domain, httpsConfig.Enabled, options...) +} + +// SetTags - bind ABROAD-CDN domain with the specified tags. +// +// PARAMS: +// - cli: the client agent can execute sending request +// - domain: the specified domain +// - tags: identifying CDN domain as something +// +// RETURNS: +// - error: nil if success otherwise the specific error +func SetTags(cli bce.Client, domain string, tags []model.TagModel) error { + urlPath := fmt.Sprintf("/v2/abroad/domain/%s/config", domain) + params := map[string]string{ + "tags": "", + } + err := httpRequest(cli, "PUT", urlPath, params, &struct { + Tags []model.TagModel `json:"tags"` + }{ + Tags: tags, + }, nil) + if err != nil { + return err + } + + return nil +} + +// GetTags - get tags the ABROAD-CDN domain bind with. +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - domain: the specified domain +// +// RETURNS: +// - []Tag: tags the ABROAD-CDN domain bind with +// - error: nil if success otherwise the specific error +func GetTags(cli bce.Client, domain string) ([]model.TagModel, error) { + urlPath := fmt.Sprintf("/v2/abroad/domain/%s/config", domain) + params := map[string]string{ + "tags": "", + } + + respObj := struct { + Tags []model.TagModel `json:"tags"` + }{} + + err := httpRequest(cli, "GET", urlPath, params, nil, &respObj) + + if err != nil { + return nil, err + } + + return respObj.Tags, nil +} diff --git a/vendor/github.com/baidubce/bce-sdk-go/services/cdn/abroad/api/log.go b/vendor/github.com/baidubce/bce-sdk-go/services/cdn/abroad/api/log.go new file mode 100644 index 00000000..3f59118b --- /dev/null +++ b/vendor/github.com/baidubce/bce-sdk-go/services/cdn/abroad/api/log.go @@ -0,0 +1,101 @@ +package api + +import ( + "errors" + "fmt" + "time" + + "github.com/baidubce/bce-sdk-go/bce" + "github.com/baidubce/bce-sdk-go/util" +) + +type LogBase struct { + Domain string `json:"domain"` + Url string `json:"url"` + Name string `json:"name"` + Size int64 `json:"size"` +} + +// TimeInterval defined a struct contains the started time and the end time +type TimeInterval struct { + StartTime string `json:"startTime"` + EndTime string `json:"endTime"` +} + +// LogEntry defined a struct for log information +type LogEntry struct { + *LogBase + *TimeInterval +} + +// GetDomainLog -get one domain's log urls +// For details, please refer https://cloud.baidu.com/doc/CDN-ABROAD/s/mjwvxj0ec +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - domain: the specified domain +// - timeInterval: the specified time interval +// RETURNS: +// - []LogEntry: the log detail list +// - error: nil if success otherwise the specific error +func GetDomainLog(cli bce.Client, domain string, timeInterval TimeInterval) ([]LogEntry, error) { + if err := checkTimeInterval(timeInterval, 14*24*60*60); err != nil { + return nil, err + } + + urlPath := fmt.Sprintf("/v2/abroad/log/%s", domain) + params := map[string]string{} + params["startTime"] = timeInterval.StartTime + params["endTime"] = timeInterval.EndTime + + respObj := &struct { + Logs []LogEntry `json:"logs"` + }{} + + if err := httpRequest(cli, "GET", urlPath, params, nil, respObj); err != nil { + return nil, err + } + + for i, _ := range respObj.Logs { + respObj.Logs[i].Domain = domain + } + + return respObj.Logs, nil +} + +func checkTimeInterval(timeInterval TimeInterval, maxTimeRange int64) error { + if timeInterval.StartTime == "" { + return errors.New("lack of startTime") + } + + if timeInterval.EndTime == "" { + return errors.New("lack of endTime") + } + + st, err := util.ParseISO8601Date(timeInterval.StartTime) + if err != nil { + return errors.New(fmt.Sprintf("invalid startTime, %s", err.Error())) + } + startTs := st.Unix() + + et, err := util.ParseISO8601Date(timeInterval.EndTime) + if err != nil { + return errors.New(fmt.Sprintf("invalid endTime, %s", err.Error())) + } + endTs := et.Unix() + + if startTs > endTs { + return errors.New(fmt.Sprintf("startTime shouble be less than endTime")) + } + + curTs := time.Now().Unix() + if curTs-startTs > maxTimeRange { + return errors.New(fmt.Sprintf("only the first %d seconds of log files can be downloaded, please reset startTime", maxTimeRange)) + } + + if startTs > curTs { + return errors.New("startTime could not larger than current time") + } + + return nil +} diff --git a/vendor/github.com/baidubce/bce-sdk-go/services/cdn/abroad/api/stat.go b/vendor/github.com/baidubce/bce-sdk-go/services/cdn/abroad/api/stat.go new file mode 100644 index 00000000..bf65c318 --- /dev/null +++ b/vendor/github.com/baidubce/bce-sdk-go/services/cdn/abroad/api/stat.go @@ -0,0 +1,310 @@ +package api + +import ( + "strconv" + "strings" + + "github.com/baidubce/bce-sdk-go/bce" +) + +// The time interval of statistics data merged by, we defined 3 valid values here. +var ( + Period300 = createPeriod(300) + Period3600 = createPeriod(3600) + Period86400 = createPeriod(86400) +) + +type Period interface { + Value() int64 +} + +type period int64 + +func (p *period) Value() int64 { + return int64(*p) +} + +func createPeriod(value int64) Period { + x := period(value) + return &x +} + +// QueryStatOption defined a method for setting optional configurations for query statistics. +type QueryStatOption func(interface{}) + +// QueryStatByDomains defined a method to pass the CDN domains you are interested in. +func QueryStatByDomains(domains []string) QueryStatOption { + return func(o interface{}) { + cfg, ok := o.(*queryStatOption) + if ok && len(domains) > 0 { + cfg.Domains = domains + } + } +} + +// QueryStatByTimeRange the beginning and the end of the time range to query, +// The time values are in the ISO 8601 standard with the yyyy-MM-ddTHH:mm:ssZ format, +// e.g. 2024-04-15T00:00:00Z. +func QueryStatByTimeRange(startTime, endTime string) QueryStatOption { + return func(o interface{}) { + cfg, ok := o.(*queryStatOption) + if ok { + cfg.StartTime = startTime + cfg.EndTime = endTime + } + } +} + +// QueryStatByPeriod the time interval of statistics data merged by, +// valid values are 300, 3600 and 86400 represents by Period300, Period3060 and Period86400 respectively +func QueryStatByPeriod(period Period) QueryStatOption { + return func(o interface{}) { + if period == nil { + return + } + cfg, ok := o.(*queryStatOption) + if ok { + cfg.Period = period.Value() + } + } +} + +// QueryStatByCountry the specific Country you want to know about. +// The country value is one of the GEC codes. +// More details about GEC, you can read this article: +// https://baike.baidu.com/item/%E4%B8%96%E7%95%8C%E5%90%84%E5%9B%BD%E5%92%8C%E5%9C%B0%E5%8C%BA%E5%90%8D%E7%A7%B0%E4%BB%A3%E7%A0%81/6560023 +// and pay attention of the column of the key world "两字母代码". +func QueryStatByCountry(country string) QueryStatOption { + return func(o interface{}) { + cfg, ok := o.(*queryStatOption) + if ok { + cfg.Country = country + } + } +} + +type queryStatOption struct { + Domains []string + EndTime string + StartTime string + Period int64 + Country string +} + +func (queryOption *queryStatOption) makeParams() map[string]string { + params := map[string]string{} + if len(queryOption.Domains) > 0 { + params["domain"] = strings.Join(queryOption.Domains, ",") + } + if queryOption.StartTime != "" { + params["startTime"] = queryOption.StartTime + } + if queryOption.EndTime != "" { + params["endTime"] = queryOption.EndTime + } + if queryOption.Period > 0 { + params["period"] = strconv.FormatInt(queryOption.Period, 10) + } + if queryOption.Country != "" { + params["region"] = queryOption.Country + } + return params +} + +// FlowDetail hold details of statistics of traffic. +type FlowDetail struct { + Timestamp string `json:"timestamp"` + Flow int64 `json:"flow"` + Bps int64 `json:"bps"` + Key string `json:"key"` +} + +// GetFlow - get the statistics of traffic(flow). +// For details, please refer https://cloud.baidu.com/doc/CDN-ABROAD/s/Bkbszintg +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - options: the querying conditions, valid options are: +// 1. QueryStatByTimeRange +// 2. QueryStatByPeriod +// 3. QueryStatByDomains +// 4. QueryStatByCountry +// RETURNS: +// - []FlowDetail: the details about traffic +// - error: nil if success otherwise the specific error +func GetFlow(cli bce.Client, options ...QueryStatOption) ([]FlowDetail, error) { + var queryOptions queryStatOption + for _, opt := range options { + opt(&queryOptions) + } + + respObj := &struct { + Status string `json:"status"` + Count int64 `json:"count"` + Details []FlowDetail `json:"details"` + }{} + + err := httpRequest(cli, "GET", "/v2/abroad/stat/flow", queryOptions.makeParams(), nil, respObj) + if err != nil { + return nil, err + } + + return respObj.Details, nil +} + +// PvDetail hold details of statistics of pv/qps. +type PvDetail struct { + Timestamp string `json:"timestamp"` + Pv int64 `json:"pv"` + Qps int64 `json:"qps"` + Key string `json:"key"` +} + +// GetPv - get the statistics of pv/qps. +// For details, please refer https://cloud.baidu.com/doc/CDN-ABROAD/s/dkbszg48s +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - options: the querying conditions, valid options are: +// 1. QueryStatByTimeRange +// 2. QueryStatByPeriod +// 3. QueryStatByDomains +// 4. QueryStatByCountry +// RETURNS: +// - []PvDetail: the details about pv/qps +// - error: nil if success otherwise the specific error +func GetPv(cli bce.Client, options ...QueryStatOption) ([]PvDetail, error) { + var queryOptions queryStatOption + for _, opt := range options { + opt(&queryOptions) + } + + respObj := &struct { + Status string `json:"status"` + Count int64 `json:"count"` + Details []PvDetail `json:"details"` + }{} + + err := httpRequest(cli, "GET", "/v2/abroad/stat/pv", queryOptions.makeParams(), nil, respObj) + if err != nil { + return nil, err + } + + return respObj.Details, nil +} + +// GetSrcFlow - get the statistics of traffic(flow) to your origin server. +// For details, please refer https://cloud.baidu.com/doc/CDN-ABROAD/s/rkbsznt4v +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - options: the querying conditions, valid options are: +// 1. QueryStatByTimeRange +// 2. QueryStatByPeriod +// 3. QueryStatByDomains +// RETURNS: +// - []FlowDetail: the details about traffic to your origin server. +// - error: nil if success otherwise the specific error +func GetSrcFlow(cli bce.Client, options ...QueryStatOption) ([]FlowDetail, error) { + var queryOptions queryStatOption + for _, opt := range options { + opt(&queryOptions) + } + + respObj := &struct { + Status string `json:"status"` + Count int64 `json:"count"` + Details []FlowDetail `json:"details"` + }{} + + err := httpRequest(cli, "GET", "/v2/abroad/stat/flow", queryOptions.makeParams(), nil, respObj) + if err != nil { + return nil, err + } + + return respObj.Details, nil +} + +// KvCounter defined a struct for name and count pairs. +type KvCounter struct { + Name int64 `json:"name"` + Count int64 `json:"count"` +} + +// HttpCodeDetail hold details of statistics of accessing HTTP codes. +type HttpCodeDetail struct { + Timestamp string `json:"timestamp"` + Counters []KvCounter `json:"counters"` + Key string `json:"key"` +} + +// GetHttpCode - get the statistics of accessing HTTP codes. +// For details, please refer https://cloud.baidu.com/doc/CDN-ABROAD/s/ekbszvxv5 +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - options: the querying conditions, valid options are: +// 1. QueryStatByTimeRange +// 2. QueryStatByPeriod +// 3. QueryStatByDomains +// RETURNS: +// - []HttpCodeDetail: the details about accessing HTTP codes. +// - error: nil if success otherwise the specific error +func GetHttpCode(cli bce.Client, options ...QueryStatOption) ([]HttpCodeDetail, error) { + var queryOptions queryStatOption + for _, opt := range options { + opt(&queryOptions) + } + + respObj := &struct { + Status string `json:"status"` + Count int64 `json:"count"` + Details []HttpCodeDetail `json:"details"` + }{} + + err := httpRequest(cli, "GET", "/v2/abroad/stat/httpcode", queryOptions.makeParams(), nil, respObj) + if err != nil { + return nil, err + } + + return respObj.Details, nil +} + +// HitDetail defined a struct for hitting ratio of Edge accessing. +type HitDetail struct { + Timestamp string `json:"timestamp"` + HitRate float64 `json:"hitrate"` + Key string `json:"key"` +} + +// GetRealHit - get the statistics of hit rate of accessing by traffic. +// For details, please refer https://cloud.baidu.com/doc/CDN-ABROAD/s/ckbszuehh +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - options: the querying conditions, valid options are: +// 1. QueryStatByTimeRange +// 2. QueryStatByPeriod +// 3. QueryStatByDomains +// RETURNS: +// - []HitDetail: the details about traffic hit rate. +// - error: nil if success otherwise the specific error +func GetRealHit(cli bce.Client, options ...QueryStatOption) ([]HitDetail, error) { + var queryOptions queryStatOption + for _, opt := range options { + opt(&queryOptions) + } + + respObj := &struct { + Status string `json:"status"` + Count int64 `json:"count"` + Details []HitDetail `json:"details"` + }{} + + err := httpRequest(cli, "GET", "/v2/abroad/stat/realhit", queryOptions.makeParams(), nil, respObj) + if err != nil { + return nil, err + } + + return respObj.Details, nil +} diff --git a/vendor/github.com/baidubce/bce-sdk-go/services/cdn/abroad/api/util.go b/vendor/github.com/baidubce/bce-sdk-go/services/cdn/abroad/api/util.go new file mode 100644 index 00000000..82529d2b --- /dev/null +++ b/vendor/github.com/baidubce/bce-sdk-go/services/cdn/abroad/api/util.go @@ -0,0 +1,79 @@ +package api + +import ( + "bytes" + "encoding/json" + "errors" + + "github.com/baidubce/bce-sdk-go/bce" +) + +// SendCustomRequest - send a HTTP request, and response data or error, it use the default times for retrying +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - method: the HTTP requested method, e.g. "GET", "POST", "PUT" ... +// - urlPath: a path component, consisting of a sequence of path segments separated by a slash ( / ). +// - params: the query params, which will be append to the query path, and separate by "&" +// e.g. http://www.baidu.com?query_param1=value1&query_param2=value2 +// - reqHeaders: the request http headers +// - bodyObj: the HTTP requested body content transferred to a goland object +// - respObj: the HTTP response content transferred to a goland object +// RETURNS: +// - error: nil if success otherwise the specific error +func SendCustomRequest(cli bce.Client, method string, urlPath string, params, reqHeaders map[string]string, bodyObj interface{}, respObj interface{}) error { + if method != "GET" && method != "POST" && method != "PUT" && method != "DELETE" { + return errors.New("invalid http method") + } + + req := &bce.BceRequest{} + req.SetUri(urlPath) + req.SetMethod(method) + req.SetParams(params) + req.SetHeaders(reqHeaders) + + if bodyObj != nil { + bodyBytes, err := newBodyFromJsonObj(bodyObj) + if err != nil { + return err + } + req.SetBody(bodyBytes) + } + + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + defer func() { + reader := resp.Body() + if reader != nil { + _ = reader.Close() + } + }() + + buf := new(bytes.Buffer) + _, _ = buf.ReadFrom(resp.Body()) + respBodyBytes := buf.Bytes() + + if respObj != nil { + err := json.Unmarshal(respBodyBytes, respObj) + if err != nil { + return err + } + } + + return nil +} + +func httpRequest(cli bce.Client, method string, urlPath string, params map[string]string, bodyObj interface{}, respObj interface{}) error { + return SendCustomRequest(cli, method, urlPath, params, nil, bodyObj, respObj) +} + +func newBodyFromJsonObj(obj interface{}) (*bce.Body, error) { + data, err := json.Marshal(obj) + if err != nil { + return nil, err + } + + return bce.NewBodyFromBytes(data) +} diff --git a/vendor/github.com/baidubce/bce-sdk-go/services/cdn/abroad/client.go b/vendor/github.com/baidubce/bce-sdk-go/services/cdn/abroad/client.go new file mode 100644 index 00000000..02fab575 --- /dev/null +++ b/vendor/github.com/baidubce/bce-sdk-go/services/cdn/abroad/client.go @@ -0,0 +1,485 @@ +package abroad + +import ( + "github.com/baidubce/bce-sdk-go/auth" + "github.com/baidubce/bce-sdk-go/bce" + "github.com/baidubce/bce-sdk-go/model" + "github.com/baidubce/bce-sdk-go/services/cdn/abroad/api" +) + +const ( + DEFAULT_SERVICE_DOMAIN = "cdn.baidubce.com" +) + +// Client of CDN service is a kind of BceClient, so derived from BceClient +type Client struct { + *bce.BceClient +} + +// NewClient make the CDN service client with default configuration +// Use `cli.Config.xxx` to access the config or change it to non-default value +func NewClient(ak, sk, endpoint string) (*Client, error) { + var credentials *auth.BceCredentials + var err error + if len(ak) == 0 && len(sk) == 0 { // to support public-read-write request + credentials, err = nil, nil + } else { + credentials, err = auth.NewBceCredentials(ak, sk) + if err != nil { + return nil, err + } + } + if len(endpoint) == 0 { + endpoint = DEFAULT_SERVICE_DOMAIN + } + defaultSignOptions := &auth.SignOptions{ + HeadersToSign: auth.DEFAULT_HEADERS_TO_SIGN, + ExpireSeconds: auth.DEFAULT_EXPIRE_SECONDS} + defaultConf := &bce.BceClientConfiguration{ + Endpoint: endpoint, + Region: bce.DEFAULT_REGION, + UserAgent: bce.DEFAULT_USER_AGENT, + Credentials: credentials, + SignOption: defaultSignOptions, + Retry: bce.DEFAULT_RETRY_POLICY, + ConnectionTimeoutInMillis: bce.DEFAULT_CONNECTION_TIMEOUT_IN_MILLIS} + v1Signer := &auth.BceV1Signer{} + + client := &Client{bce.NewBceClient(defaultConf, v1Signer)} + return client, nil +} + +// SendCustomRequest - send a HTTP request, and response data or error, it use the default times for retrying +// +// PARAMS: +// - method: the HTTP requested method, e.g. "GET", "POST", "PUT" ... +// - urlPath: a path component, consisting of a sequence of path segments separated by a slash ( / ). +// - params: the query params, which will be append to the query path, and separate by "&" +// e.g. http://www.baidu.com?query_param1=value1&query_param2=value2 +// - reqHeaders: the request http headers +// - bodyObj: the HTTP requested body content transferred to a goland object +// - respObj: the HTTP response content transferred to a goland object +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (cli *Client) SendCustomRequest(method string, urlPath string, params, reqHeaders map[string]string, bodyObj interface{}, respObj interface{}) error { + return api.SendCustomRequest(cli, method, urlPath, params, reqHeaders, bodyObj, respObj) +} + +// ListDomains - list all domains that in ABROAD-CDN service +// For details, please refer https://cloud.baidu.com/doc/CDN-ABROAD/s/1kbsyj9m6 +// +// PARAMS: +// - marker: a marker is a start point of searching +// +// RETURNS: +// - []string: domains belongs to the user +// - string: a marker for next searching, empty if is in the end +// - error: nil if success otherwise the specific error +func (cli *Client) ListDomains(marker string) ([]string, string, error) { + return api.ListDomains(cli, marker) +} + +// CreateDomainOption defined a method for setting optional configurations. +type CreateDomainOption func(interface{}) + +// CreateDomainWithTags defined a method for binding a CDN domain with the specified tags. +func CreateDomainWithTags(tags []model.TagModel) CreateDomainOption { + return func(o interface{}) { + cfg, ok := o.(*createDomainOption) + if ok { + cfg.tags = tags + } + } +} + +type createDomainOption struct { + tags []model.TagModel +} + +// CreateDomain - create a BCE ABROAD-CDN domain +// For details, please refer https://cloud.baidu.com/doc/CDN-ABROAD/s/ekbsyn5o5 +// +// PARAMS: +// - domain: the specified domain +// - originInit: origin server for a ABROAD-CDN domain +// +// RETURNS: +// - *DomainCreatedInfo: the details about created a ABROAD-CDN domain +// - error: nil if success otherwise the specific error +func (cli *Client) CreateDomain(domain string, originConfig []api.OriginPeer) (*api.DomainCreatedInfo, error) { + return api.CreateDomain(cli, domain, originConfig, nil) +} + +// CreateDomainWithOptions - create a BCE ABROAD-CDN domain with optional configurations. +// For details, please refer https://cloud.baidu.com/doc/CDN-ABROAD/s/ekbsyn5o5 +// +// PARAMS: +// - domain: the specified domain +// - origins: the origin servers +// - opts: optional configure for a CDN domain, e.g. bind with BCE tags. +// +// RETURNS: +// - *DomainCreatedInfo: the details about created a ABROAD-CDN domain +// - error: nil if success otherwise the specific error +func (cli *Client) CreateDomainWithOptions(domain string, origins []api.OriginPeer, opts ...CreateDomainOption) (*api.DomainCreatedInfo, error) { + var cfg createDomainOption + for _, opt := range opts { + opt(&cfg) + } + return api.CreateDomain(cli, domain, origins, cfg.tags) +} + +// EnableDomain - enable a specified domain +// For details, please refer https://cloud.baidu.com/doc/CDN-ABROAD/s/Zkbsypv9b +// +// PARAMS: +// - domain: the specified domain +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (cli *Client) EnableDomain(domain string) error { + return api.EnableDomain(cli, domain) +} + +// DisableDomain - disable a specified domain +// For details, please refer https://cloud.baidu.com/doc/CDN-ABROAD/s/gkbsyrdck +// +// PARAMS: +// - domain: the specified domain +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (cli *Client) DisableDomain(domain string) error { + return api.DisableDomain(cli, domain) +} + +// DeleteDomain - delete a specified domain from BCE ABROAD-CDN system. +// For details, please refer https://cloud.baidu.com/doc/CDN-ABROAD/s/4kbsytf7q +// +// PARAMS: +// - domain: the specified domain +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (cli *Client) DeleteDomain(domain string) error { + return api.DeleteDomain(cli, domain) +} + +// GetDomainConfig - get the configuration for the specified domain. +// For details, please refer https://cloud.baidu.com/doc/CDN-ABROAD/s/9kbsye6k8 +// +// PARAMS: +// - domain: the specified domain +// +// RETURNS: +// - *DomainConfig: the configuration about the specified domain +// - error: nil if success otherwise the specific error +func (cli *Client) GetDomainConfig(domain string) (*api.DomainConfig, error) { + return api.GetDomainConfig(cli, domain) +} + +// SetDomainOrigin - set the origin setting for the new +// For details, please refer https://cloud.baidu.com/doc/CDN-ABROAD/s/Gkbstcgaa +// +// PARAMS: +// - domain: the specified domain +// - origins: the origin servers +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (cli *Client) SetDomainOrigin(domain string, origins []api.OriginPeer) error { + return api.SetDomainOrigin(cli, domain, origins) +} + +// DomainOriginOption defined a method for setting optional origin configurations. +type DomainOriginOption func(interface{}) + +// SetDomainOriginWithOptions - set the origin setting for the new +// For details, please refer https://cloud.baidu.com/doc/CDN-ABROAD/s/Gkbstcgaa +// +// PARAMS: +// - domain: the specified domain +// - origins: the origin servers +// - opts: optional configurations for origin, unused now!!! +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (cli *Client) SetDomainOriginWithOptions(domain string, origins []api.OriginPeer, opts ...DomainOriginOption) error { + return api.SetDomainOrigin(cli, domain, origins) +} + +// SetCacheTTL - add rules to cache asserts. +// For details, please refer https://cloud.baidu.com/doc/CDN-ABROAD/s/Zkbstm0vg +// +// PARAMS: +// - domain: the specified domain +// - cacheTTLs: the cache setting list +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (cli *Client) SetCacheTTL(domain string, cacheTTLs []api.CacheTTL) error { + return api.SetCacheTTL(cli, domain, cacheTTLs) +} + +// SetCacheFullUrl - set the rule to calculate the cache key, set `cacheFullUrl` to true +// means the whole query(the string right after the question mark in URL) will be added to the cache key. +// For details, please refer https://cloud.baidu.com/doc/CDN-ABROAD/s/nkbsxko6t +// +// PARAMS: +// - domain: the specified domain +// - cacheFullUrl: the query part in URL being added to the cache key or not +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (cli *Client) SetCacheFullUrl(domain string, cacheFullUrl bool) error { + return api.SetCacheFullUrl(cli, domain, cacheFullUrl) +} + +// SetHostToOrigin - Specify a default value for the HOST header for virtual sites in your origin server. +// For details, please refer https://cloud.baidu.com/doc/CDN-ABROAD/s/Pkbsxw8xw +// +// PARAMS: +// - domain: the specified domain +// - originHost: specified HOST header for origin server +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (cli *Client) SetHostToOrigin(domain string, originHost string) error { + return api.SetHostToOrigin(cli, domain, originHost) +} + +// SetRefererACL - Set a Referer whitelist or blacklist to enable hotlink protection. +// For details, please refer https://cloud.baidu.com/doc/CDN-ABROAD/s/ekbsxow69 +// +// PARAMS: +// - domain: the specified domain +// - refererACL: referer of whitelist or blacklist +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (cli *Client) SetRefererACL(domain string, refererACL *api.RefererACL) error { + return api.SetRefererACL(cli, domain, refererACL) +} + +// SetIpACL - Set an IP whitelist or blacklist to block or allow requests from specific IP addresses. +// For details, please refer https://cloud.baidu.com/doc/CDN-ABROAD/s/2kbsxt693 +// +// PARAMS: +// - domain: the specified domain +// - ipACL: IP whitelist or blacklist +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (cli *Client) SetIpACL(domain string, ipACL *api.IpACL) error { + return api.SetIpACL(cli, domain, ipACL) +} + +// Purge - tells the CDN system to purge the specified files +// For more details, please refer https://cloud.baidu.com/doc/CDN-ABROAD/s/Zkbsy0k8j +// +// PARAMS: +// - tasks: the tasks about purging the files from the CDN nodes +// +// RETURNS: +// - PurgedId: an ID representing a purged task, using it to search the task progress +// - error: nil if success otherwise the specific error +func (cli *Client) Purge(tasks []api.PurgeTask) (api.PurgedId, error) { + return api.Purge(cli, tasks) +} + +// GetPurgedStatus - get the purged progress +// For details, please refer https://cloud.baidu.com/doc/CDN-ABROAD/s/ikbsy9cvb +// +// PARAMS: +// - queryData: querying conditions, it contains the time interval, the task ID and the specified url +// +// RETURNS: +// - *PurgedStatus: the details about the purged +// - error: nil if success otherwise the specific error +func (cli *Client) GetPurgedStatus(queryData *api.CStatusQueryData) (*api.PurgedStatus, error) { + return api.GetPurgedStatus(cli, queryData) +} + +// Prefetch - tells the CDN system to prefetch the specified files +// For details, please refer https://cloud.baidu.com/doc/CDN-ABROAD/s/Dlj5ch09q +// +// PARAMS: +// - tasks: the tasks about prefetch the files from the CDN nodes +// - error: nil if success otherwise the specific error +func (cli *Client) Prefetch(tasks []api.PrefetchTask) (api.PrefetchId, error) { + return api.Prefetch(cli, tasks) +} + +// GetPrefetchStatus - get the prefetch progress +// For details, please refer https://cloud.baidu.com/doc/CDN-ABROAD/s/Mlj5e9y0i +// +// PARAMS: +// - queryData: querying conditions, it contains the time interval, the task ID and the specified url +// +// RETURNS: +// - *PrefetchStatus: the details about the prefetch +// - error: nil if success otherwise the specific error +func (cli *Client) GetPrefetchStatus(queryData *api.CStatusQueryData) (*api.PrefetchStatus, error) { + return api.GetPrefetchStatus(cli, queryData) +} + +// GetQuota - get the quota about purge and prefetch +// For details, please refer https://cloud.baidu.com/doc/CDN-ABROAD/s/flnoakciq +// +// RETURNS: +// - QuotaDetail: the quota details about a specified user +// - error: nil if success otherwise the specific error +func (cli *Client) GetQuota() (*api.QuotaDetail, error) { + return api.GetQuota(cli) +} + +// GetDomainLog -get one domain's log urls +// For details, please refer https://cloud.baidu.com/doc/CDN-ABROAD/s/mjwvxj0ec +// +// PARAMS: +// - domain: the specified domain +// - timeInterval: the specified time interval +// +// RETURNS: +// - []LogEntry: the log detail list +// - error: nil if success otherwise the specific error +func (cli *Client) GetDomainLog(domain string, timeInterval api.TimeInterval) ([]api.LogEntry, error) { + return api.GetDomainLog(cli, domain, timeInterval) +} + +// GetFlow - get the statistics of traffic(flow). +// For details, please refer https://cloud.baidu.com/doc/CDN-ABROAD/s/Bkbszintg +// +// PARAMS: +// - options: the querying conditions, valid options are: +// 1. QueryStatByTimeRange +// 2. QueryStatByPeriod +// 3. QueryStatByDomains +// 4. QueryStatByCountry +// +// RETURNS: +// - []FlowDetail: the details about traffic +// - error: nil if success otherwise the specific error +func (cli *Client) GetFlow(options ...api.QueryStatOption) ([]api.FlowDetail, error) { + return api.GetFlow(cli, options...) +} + +// GetPv - get the statistics of pv/qps. +// For details, please refer https://cloud.baidu.com/doc/CDN-ABROAD/s/dkbszg48s +// +// PARAMS: +// - options: the querying conditions, valid options are: +// 1. QueryStatByTimeRange +// 2. QueryStatByPeriod +// 3. QueryStatByDomains +// 4. QueryStatByCountry +// +// RETURNS: +// - []PvDetail: the details about pv/qps +// - error: nil if success otherwise the specific error +func (cli *Client) GetPv(options ...api.QueryStatOption) ([]api.PvDetail, error) { + return api.GetPv(cli, options...) +} + +// GetSrcFlow - get the statistics of traffic(flow) to your origin server. +// For details, please refer https://cloud.baidu.com/doc/CDN-ABROAD/s/rkbsznt4v +// +// PARAMS: +// - options: the querying conditions, valid options are: +// 1. QueryStatByTimeRange +// 2. QueryStatByPeriod +// 3. QueryStatByDomains +// +// RETURNS: +// - []FlowDetail: the details about traffic to your origin server. +// - error: nil if success otherwise the specific error +func (cli *Client) GetSrcFlow(options ...api.QueryStatOption) ([]api.FlowDetail, error) { + return api.GetSrcFlow(cli, options...) +} + +// GetHttpCode - get the statistics of accessing HTTP codes. +// For details, please refer https://cloud.baidu.com/doc/CDN-ABROAD/s/ekbszvxv5 +// +// PARAMS: +// - options: the querying conditions, valid options are: +// 1. QueryStatByTimeRange +// 2. QueryStatByPeriod +// 3. QueryStatByDomains +// +// RETURNS: +// - []HttpCodeDetail: the details about accessing HTTP codes. +// - error: nil if success otherwise the specific error +func (cli *Client) GetHttpCode(options ...api.QueryStatOption) ([]api.HttpCodeDetail, error) { + return api.GetHttpCode(cli, options...) +} + +// GetRealHit - get the statistics of hit rate of accessing by traffic. +// For details, please refer https://cloud.baidu.com/doc/CDN-ABROAD/s/ckbszuehh +// +// PARAMS: +// - options: the querying conditions, valid options are: +// 1. QueryStatByTimeRange +// 2. QueryStatByPeriod +// 3. QueryStatByDomains +// +// RETURNS: +// - []HitDetail: the details about traffic hit rate. +// - error: nil if success otherwise the specific error +func (cli *Client) GetRealHit(options ...api.QueryStatOption) ([]api.HitDetail, error) { + return api.GetRealHit(cli, options...) +} + +// SetHTTPSConfigWithOptions - enable or disable HTTPS. +// For details, please refer https://cloud.baidu.com/doc/CDN-ABROAD/s/ckb0fx9ea +// +// PARAMS: +// - domain: the specified domain +// - enabled: true means enable HTTPS, otherwise disable. +// - options: more operations to configure HTTPS, the valid options are: +// 1. HTTPSConfigCertID +// 2. HTTPSConfigRedirectWith301 +// 3. HTTPSConfigEnableH2 +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (cli *Client) SetHTTPSConfigWithOptions(domain string, enabled bool, options ...api.HTTPSConfigOption) error { + return api.SetHTTPSConfigWithOptions(cli, domain, enabled, options...) +} + +// SetHTTPSConfig - enable or disable HTTPS. +// For details, please refer https://cloud.baidu.com/doc/CDN-ABROAD/s/ckb0fx9ea +// +// PARAMS: +// - domain: the specified domain +// - httpsConfig: HTTPS configurations. +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (cli *Client) SetHTTPSConfig(domain string, httpsConfig *api.HTTPSConfig) error { + return api.SetHTTPSConfig(cli, domain, httpsConfig) +} + +// SetTags - bind ABROAD-CDN domain with the specified tags. +// +// PARAMS: +// - domain: the specified domain +// - tags: identifying ABROAD-CDN domain as something +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (cli *Client) SetTags(domain string, tags []model.TagModel) error { + return api.SetTags(cli, domain, tags) +} + +// GetTags - get tags the ABROAD-CDN domain bind with. +// +// PARAMS: +// - domain: the specified domain +// +// RETURNS: +// - []Tag: tags the ABROAD-CDN domain bind with +// - error: nil if success otherwise the specific error +func (cli *Client) GetTags(domain string) ([]model.TagModel, error) { + return api.GetTags(cli, domain) +} diff --git a/vendor/github.com/baidubce/bce-sdk-go/services/cdn/abroad/config.json b/vendor/github.com/baidubce/bce-sdk-go/services/cdn/abroad/config.json new file mode 100644 index 00000000..8cc9fd83 --- /dev/null +++ b/vendor/github.com/baidubce/bce-sdk-go/services/cdn/abroad/config.json @@ -0,0 +1,6 @@ +{ + "AK":"Your BCE account AK", + "SK":"Your BCE account SK", + "Endpoint":"https://cdn.baidubce.com", + "TestDomain": "CDN domain for unit-test, must be created first." +} diff --git a/vendor/modules.txt b/vendor/modules.txt index 6cdc09d5..c23516ea 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -97,6 +97,8 @@ github.com/baidubce/bce-sdk-go/services/cce github.com/baidubce/bce-sdk-go/services/cce/v2 github.com/baidubce/bce-sdk-go/services/cce/v2/types github.com/baidubce/bce-sdk-go/services/cdn +github.com/baidubce/bce-sdk-go/services/cdn/abroad +github.com/baidubce/bce-sdk-go/services/cdn/abroad/api github.com/baidubce/bce-sdk-go/services/cdn/api github.com/baidubce/bce-sdk-go/services/cert github.com/baidubce/bce-sdk-go/services/cfc diff --git a/website/docs/r/abroad_cdn_domain.html.markdown b/website/docs/r/abroad_cdn_domain.html.markdown new file mode 100644 index 00000000..12adee79 --- /dev/null +++ b/website/docs/r/abroad_cdn_domain.html.markdown @@ -0,0 +1,67 @@ +--- +# generated by https://github.com/hashicorp/terraform-plugin-docs +page_title: "baiducloud_abroad_cdn_domain Resource - terraform-provider-baiducloud" +subcategory: "CDN" +description: |- + Use this resource to manage abroad acceleration domain and its origin configuration. + More information can be found in the Developer Guide https://cloud.baidu.com/doc/CDN-ABROAD/s/gjwvxiywx. +--- + +# baiducloud_abroad_cdn_domain (Resource) + +Use this resource to manage abroad acceleration domain and its origin configuration. + +More information can be found in the [Developer Guide](https://cloud.baidu.com/doc/CDN-ABROAD/s/gjwvxiywx). + +## Example Usage + +```terraform +resource "baiducloud_abroad_cdn_domain" "default" { + domain = "test.cdn.cloud" + + origin { + backup = false + type = "IP" + addr = "1.2.3.4" + } + tags = { + terraform = "terraform-test2" + } +} +``` + + +## Schema + +### Required + +- `domain` (String) Name of the acceleration domain. +- `origin` (Block List, Min: 1) Origin server configuration of the acceleration domain. (see [below for nested schema](#nestedblock--origin)) + +### Optional + +- `tags` (Map of String) Tags, do not support modify + +### Read-Only + +- `id` (String) The ID of this resource. + + +### Nested Schema for `origin` + +Required: + +- `addr` (String) The ip address when forwarding to origin server +- `type` (String) origin type, value is IP or DOMAIN + +Optional: + +- `backup` (Boolean) Whether is a backup origin server. Defaults to `false`. + +## Import + +Import is supported using the following syntax: + +```shell +terraform import baiducloud_abroad_cdn_domain.example example1.domain.com +```