Merge pull request #8304 from bittopaz/fix-lbacl

Alicloud: Refactor LoadBalancerWhiteList to LoadBalancerACL
This commit is contained in:
Kubernetes Prow Robot 2020-06-21 19:34:39 -07:00 committed by GitHub
commit abe4c12794
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
255 changed files with 24950 additions and 205 deletions

1
go.mod
View File

@ -54,6 +54,7 @@ require (
github.com/Masterminds/semver v1.3.1 // indirect
github.com/Masterminds/sprig v2.17.1+incompatible
github.com/Microsoft/go-winio v0.4.14 // indirect
github.com/aliyun/alibaba-cloud-sdk-go v1.61.264
github.com/aokoli/goutils v1.0.1 // indirect
github.com/aws/aws-sdk-go v1.30.16
github.com/bazelbuild/bazel-gazelle v0.19.1

5
go.sum
View File

@ -58,6 +58,8 @@ github.com/agext/levenshtein v1.2.1/go.mod h1:JEDfjyjHDjOF/1e4FlBE/PkbqA9OfWu2ki
github.com/agnivade/levenshtein v1.0.1/go.mod h1:CURSv5d9Uaml+FovSIICkLbAUZ9S4RqaHDIsdSBg7lM=
github.com/alecthomas/template v0.0.0-20160405071501-a0175ee3bccc/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc=
github.com/alecthomas/units v0.0.0-20151022065526-2efee857e7cf/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0=
github.com/aliyun/alibaba-cloud-sdk-go v1.61.264 h1:5o7dIWOmKWEujFfzD3XV8EmpnCbqekpTqdEsBlfNp6c=
github.com/aliyun/alibaba-cloud-sdk-go v1.61.264/go.mod h1:pUKYbK5JQ+1Dfxk80P0qxGqe5dkxDoabbZS7zOcouyA=
github.com/andreyvit/diff v0.0.0-20170406064948-c7f18ee00883/go.mod h1:rCTlJbsFo29Kk6CurOXKm700vrz8f0KW0JNfpkRJY/8=
github.com/anmitsu/go-shlex v0.0.0-20161002113705-648efa622239/go.mod h1:2FmKhYUyUczH0OGQWaF5ceTx0UBShxjsH6f8oGKYe2c=
github.com/aokoli/goutils v1.0.1 h1:7fpzNGoJ3VA8qcrm++XEE1QUe0mIwNeLa02Nwq7RDkg=
@ -316,6 +318,7 @@ github.com/gogo/protobuf v1.2.2-0.20190723190241-65acae22fc9d h1:3PaI8p3seN09Vjb
github.com/gogo/protobuf v1.2.2-0.20190723190241-65acae22fc9d/go.mod h1:SlYgWuQ5SjCEi6WLHjHCa1yvBfUnHcTbrrZtXPKa29o=
github.com/gogo/protobuf v1.3.1 h1:DqDEcV5aeaTmdFBePNpYsp3FlcVH/2ISVVM9Qf8PSls=
github.com/gogo/protobuf v1.3.1/go.mod h1:SlYgWuQ5SjCEi6WLHjHCa1yvBfUnHcTbrrZtXPKa29o=
github.com/goji/httpauth v0.0.0-20160601135302-2da839ab0f4d/go.mod h1:nnjvkQ9ptGaCkuDUx6wNykzzlUixGxvkme+H/lnzb+A=
github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b h1:VKtxabqXZkF25pY9ekfRL6a582T4P37/31XEstQ5p58=
github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q=
github.com/golang/groupcache v0.0.0-20160516000752-02826c3e7903 h1:LbsanbbD6LieFkXbj9YNNBupiGHJgFeLpO0j0Fza1h8=
@ -492,6 +495,7 @@ github.com/jonboulle/clockwork v0.1.0/go.mod h1:Ii8DK3G1RaLaWxj9trq07+26W01tbo22
github.com/jpillora/backoff v0.0.0-20170918002102-8eab2debe79d h1:ix3WmphUvN0GDd0DO9MH0v6/5xTv+Xm1bPN+1UJn58k=
github.com/jpillora/backoff v0.0.0-20170918002102-8eab2debe79d/go.mod h1:2iMrUgbbvHEiQClaW2NsSzMyGHqN+rDFqY705q49KG0=
github.com/json-iterator/go v0.0.0-20180612202835-f2b4162afba3/go.mod h1:+SdeFBvtyEkXs7REEP0seUULqWtbJapLOCVDaaPEHmU=
github.com/json-iterator/go v1.1.5/go.mod h1:+SdeFBvtyEkXs7REEP0seUULqWtbJapLOCVDaaPEHmU=
github.com/json-iterator/go v1.1.6/go.mod h1:+SdeFBvtyEkXs7REEP0seUULqWtbJapLOCVDaaPEHmU=
github.com/json-iterator/go v1.1.7 h1:KfgG9LzI+pYjr4xvmz/5H4FXjokeP+rlHLhv3iH62Fo=
github.com/json-iterator/go v1.1.7/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4=
@ -1058,6 +1062,7 @@ gopkg.in/gcfg.v1 v1.2.3/go.mod h1:yesOnuUOFQAhST5vPY4nbZsb/huCgGGXlipJsBn0b3o=
gopkg.in/gemnasium/logrus-airbrake-hook.v2 v2.1.2/go.mod h1:Xk6kEKp8OKb+X14hQBKWaSkCsqBpgog8nAV2xsGOxlo=
gopkg.in/inf.v0 v0.9.1 h1:73M5CoZyi3ZLMOyDlQh031Cx6N9NDJ2Vvfl76EDAgDc=
gopkg.in/inf.v0 v0.9.1/go.mod h1:cWUDdTG/fYaXco+Dcufb5Vnc6Gp2YChqWtbxRZE0mXw=
gopkg.in/ini.v1 v1.42.0/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k=
gopkg.in/ini.v1 v1.51.0 h1:AQvPpx3LzTDM0AjnIRlVFwFFGC+npRopjZxLJj6gdno=
gopkg.in/ini.v1 v1.51.0/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k=
gopkg.in/mcuadros/go-syslog.v2 v2.2.1/go.mod h1:l5LPIyOOyIdQquNg+oU6Z3524YwrcqEm0aKH+5zpt2U=

View File

@ -19,7 +19,6 @@ package alimodel
import (
"errors"
"fmt"
"strings"
"k8s.io/kops/pkg/apis/kops"
"k8s.io/kops/pkg/dns"
@ -106,28 +105,28 @@ func (b *APILoadBalancerModelBuilder) Build(c *fi.ModelBuilderContext) error {
c.AddTask(loadbalancerlistener)
}
// Create LoadBalancerWhiteList for API ELB
var loadbalancerwhiteList *alitasks.LoadBalancerWhiteList
// Allow traffic into the SLB from KubernetesAPIAccess CIDRs
var loadBalancerACL *alitasks.LoadBalancerACL
{
sourceItems := ""
var cidrs []string
var cidrs []*string
for _, cidr := range b.Cluster.Spec.KubernetesAPIAccess {
if cidr != "0.0.0.0" && cidr != "0.0.0.0/0" {
cidrs = append(cidrs, cidr)
cc := cidr
cidrs = append(cidrs, &cc)
}
}
sourceItems = strings.Join(cidrs, ",")
loadbalancerwhiteList = &alitasks.LoadBalancerWhiteList{
if len(cidrs) != 0 {
loadBalancerACL = &alitasks.LoadBalancerACL{
Name: s("api." + b.ClusterName()),
Lifecycle: b.Lifecycle,
LoadBalancer: loadbalancer,
LoadBalancerListener: loadbalancerlistener,
SourceItems: s(sourceItems),
SourceItems: cidrs,
}
c.AddTask(loadBalancerACL)
}
c.AddTask(loadbalancerwhiteList)
}
// Temporarily do not know the role of the following function

View File

@ -47,8 +47,8 @@ type ALIVolumes struct {
var _ Volumes = &ALIVolumes{}
func NewALIVolumes() (*ALIVolumes, error) {
accessKeyId := os.Getenv("ALIYUN_ACCESS_KEY_ID")
if accessKeyId == "" {
accessKeyID := os.Getenv("ALIYUN_ACCESS_KEY_ID")
if accessKeyID == "" {
return nil, fmt.Errorf("error initialing ALIVolumes: ALIYUN_ACCESS_KEY_ID cannot be empty")
}
accessKeySecret := os.Getenv("ALIYUN_ACCESS_KEY_SECRET")
@ -61,7 +61,7 @@ func NewALIVolumes() (*ALIVolumes, error) {
ecsEndpoint = ecs.ECSDefaultEndpoint
}
client := ecs.NewClientWithEndpoint(ecsEndpoint, accessKeyId, accessKeySecret)
client := ecs.NewClientWithEndpoint(ecsEndpoint, accessKeyID, accessKeySecret)
a := &ALIVolumes{
client: client,
}

View File

@ -11,10 +11,10 @@ go_library(
"launchconfiguration_fitask.go",
"loadbalancer.go",
"loadbalancer_fitask.go",
"loadbalanceracl.go",
"loadbalanceracl_fitask.go",
"loadbalancerlistener.go",
"loadbalancerlistener_fitask.go",
"loadbalancerwhitelist.go",
"loadbalancerwhitelist_fitask.go",
"natgateway.go",
"natgateway_fitask.go",
"rampolicy.go",
@ -44,6 +44,8 @@ go_library(
"//upup/pkg/fi:go_default_library",
"//upup/pkg/fi/cloudup/aliup:go_default_library",
"//upup/pkg/fi/cloudup/terraform:go_default_library",
"//vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests:go_default_library",
"//vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/slb:go_default_library",
"//vendor/github.com/denverdino/aliyungo/common:go_default_library",
"//vendor/github.com/denverdino/aliyungo/ecs:go_default_library",
"//vendor/github.com/denverdino/aliyungo/ess:go_default_library",

View File

@ -0,0 +1,272 @@
/*
Copyright 2019 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package alitasks
import (
"encoding/json"
"fmt"
"sort"
"k8s.io/klog"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
slbnew "github.com/aliyun/alibaba-cloud-sdk-go/services/slb"
"k8s.io/kops/upup/pkg/fi"
"k8s.io/kops/upup/pkg/fi/cloudup/aliup"
"k8s.io/kops/upup/pkg/fi/cloudup/terraform"
)
type LoadBalancerACL struct {
ID *string
Name *string
LoadBalancer *LoadBalancer
LoadBalancerListener *LoadBalancerListener
SourceItems []*string
Lifecycle *fi.Lifecycle
}
type AclEntry struct {
Entry string `json:"entry"`
Comment string `json:"comment"`
}
var _ fi.CompareWithID = &LoadBalancerACL{}
func (l *LoadBalancerACL) CompareWithID() *string {
return l.Name
}
func (l *LoadBalancerACL) Find(c *fi.Context) (*LoadBalancerACL, error) {
if l.LoadBalancer == nil || l.LoadBalancer.LoadbalancerId == nil {
klog.V(4).Infof("LoadBalancer / LoadbalancerId not found for %s, skipping Find", fi.StringValue(l.Name))
return nil, nil
}
if l.LoadBalancerListener == nil || l.LoadBalancerListener.ListenerPort == nil {
klog.V(4).Infof("LoadBalancerListener / LoadbalancerListenerPort not found for %s, skipping Find", fi.StringValue(l.Name))
return nil, nil
}
cloud := c.Cloud.(aliup.ALICloud)
describeAclReq := slbnew.CreateDescribeAccessControlListsRequest()
describeAclReq.AclName = fi.StringValue(l.Name)
describeAclResp, err := cloud.SLB().DescribeAccessControlLists(describeAclReq)
if err != nil {
return nil, fmt.Errorf("error listing LoadBalancerAccessControlList: %v", err)
}
acls := describeAclResp.Acls.Acl
if len(acls) == 0 {
return nil, nil
}
if len(acls) > 1 {
return nil, fmt.Errorf("found multiple LoadBalancerAccessControlList with name %s", fi.StringValue(l.Name))
}
acl := acls[0]
klog.V(2).Infof("found matching LoadBalancerAccessControlList: %s", acl.AclId)
describeAclAttrReq := slbnew.CreateDescribeAccessControlListAttributeRequest()
describeAclAttrReq.AclId = acl.AclId
describeAclAttrResp, err := cloud.SLB().DescribeAccessControlListAttribute(describeAclAttrReq)
if err != nil {
return nil, fmt.Errorf("error describing LoadBalancerAccessControlListAttribute: %v", err)
}
var sourceItems []*string
for _, entry := range describeAclAttrResp.AclEntrys.AclEntry {
ip := entry.AclEntryIP
sourceItems = append(sourceItems, &ip)
}
actual := &LoadBalancerACL{
ID: fi.String(acl.AclId),
Name: fi.String(describeAclAttrResp.AclName),
SourceItems: sourceItems,
}
listeners := describeAclAttrResp.RelatedListeners.RelatedListener
if len(listeners) != 1 {
actual.LoadBalancerListener = nil
actual.LoadBalancer = nil
} else {
listener := listeners[0]
lb := &LoadBalancer{LoadbalancerId: fi.String(listener.LoadBalancerId)}
actual.LoadBalancer = lb
actual.LoadBalancerListener = &LoadBalancerListener{
LoadBalancer: lb,
ListenerPort: fi.Int(listener.ListenerPort),
}
}
// Ignore "system" fields
l.ID = actual.ID
actual.Lifecycle = l.Lifecycle
return actual, nil
}
func (l *LoadBalancerACL) Run(c *fi.Context) error {
l.Normalize()
return fi.DefaultDeltaRunMethod(l, c)
}
func (l *LoadBalancerACL) Normalize() {
// We need to sort our arrays consistently, so we don't get spurious changes
sort.Stable(StringPointers(l.SourceItems))
}
// StringPointers implements sort.Interface for []*string
type StringPointers []*string
func (s StringPointers) Len() int { return len(s) }
func (s StringPointers) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
func (s StringPointers) Less(i, j int) bool {
return fi.StringValue(s[i]) < fi.StringValue(s[j])
}
func (_ *LoadBalancerACL) CheckChanges(a, e, changes *LoadBalancerACL) error {
if a == nil {
if e.Name == nil {
return fi.RequiredField("Name")
}
}
return nil
}
func (_ *LoadBalancerACL) RenderALI(t *aliup.ALIAPITarget, a, e, changes *LoadBalancerACL) error {
if a == nil {
klog.V(2).Infof("Creating LoadBalancerAccessControlList with name: %q for SLB %q", *e.Name, *e.LoadBalancer.LoadbalancerId)
if err := createAcl(t.Cloud, e); err != nil {
return err
}
return e.on(t.Cloud)
} else {
if changes.SourceItems != nil {
klog.V(2).Info("Turning off LoadBalancerACL for SLB")
if err := e.off(t.Cloud); err != nil {
return err
}
klog.V(2).Infof("Deleting LoadBalancerAccessControlList %q", *a.Name)
err := deleteAcl(t.Cloud, a)
if err != nil {
return fmt.Errorf("error deleting LoadBalancerAccessControlList: %v", err)
}
klog.V(2).Infof("Creating LoadBalancerAccessControlList with name: %q for SLB %q", *e.Name, *e.LoadBalancer.LoadbalancerId)
if err := createAcl(t.Cloud, e); err != nil {
return err
}
return e.on(t.Cloud)
}
if changes.LoadBalancer != nil || changes.LoadBalancerListener != nil {
klog.V(2).Info("Turning on LoadBalancerACL for SLB")
return e.on(t.Cloud)
}
}
return nil
}
func (l *LoadBalancerACL) on(alicloud aliup.ALICloud) error {
setLBTCPlistenerAttrReq := slbnew.CreateSetLoadBalancerTCPListenerAttributeRequest()
setLBTCPlistenerAttrReq.AclId = fi.StringValue(l.ID)
setLBTCPlistenerAttrReq.AclType = "white"
setLBTCPlistenerAttrReq.AclStatus = "on"
setLBTCPlistenerAttrReq.LoadBalancerId = fi.StringValue(l.LoadBalancer.LoadbalancerId)
setLBTCPlistenerAttrReq.ListenerPort = requests.NewInteger(fi.IntValue(l.LoadBalancerListener.ListenerPort))
_, err := alicloud.SLB().SetLoadBalancerTCPListenerAttribute(setLBTCPlistenerAttrReq)
if err != nil {
return fmt.Errorf("error turning on LoadBalancerACL %v", err)
}
return nil
}
func (l *LoadBalancerACL) off(alicloud aliup.ALICloud) error {
setLBTCPlistenerAttrReq := slbnew.CreateSetLoadBalancerTCPListenerAttributeRequest()
setLBTCPlistenerAttrReq.AclStatus = "off"
setLBTCPlistenerAttrReq.LoadBalancerId = fi.StringValue(l.LoadBalancer.LoadbalancerId)
setLBTCPlistenerAttrReq.ListenerPort = requests.NewInteger(fi.IntValue(l.LoadBalancerListener.ListenerPort))
_, err := alicloud.SLB().SetLoadBalancerTCPListenerAttribute(setLBTCPlistenerAttrReq)
if err != nil {
return fmt.Errorf("error turning off LoadBalancerACL %v", err)
}
return nil
}
func createAcl(alicloud aliup.ALICloud, acl *LoadBalancerACL) error {
createAclReq := slbnew.CreateCreateAccessControlListRequest()
createAclReq.AclName = fi.StringValue(acl.Name)
resp, err := alicloud.SLB().CreateAccessControlList(createAclReq)
if err != nil {
return fmt.Errorf("error creating LoadBalancerAccessControlList: %v", err)
}
aclID := resp.AclId
acl.ID = fi.String(aclID)
var aclEntries []AclEntry
for _, each := range acl.SourceItems {
aclEntries = append(aclEntries, AclEntry{Entry: *each})
}
aclEntriesBytes, err := json.Marshal(aclEntries)
if err != nil {
return fmt.Errorf("error marshalling %v : %v", aclEntries, err)
}
addAclEntryReq := slbnew.CreateAddAccessControlListEntryRequest()
addAclEntryReq.AclId = aclID
addAclEntryReq.AclEntrys = string(aclEntriesBytes)
_, err = alicloud.SLB().AddAccessControlListEntry(addAclEntryReq)
if err != nil {
return fmt.Errorf("error adding AclEntries %v: %v", addAclEntryReq, err)
}
return nil
}
func deleteAcl(alicloud aliup.ALICloud, acl *LoadBalancerACL) error {
deleteAclReq := slbnew.CreateDeleteAccessControlListRequest()
deleteAclReq.AclId = fi.StringValue(acl.ID)
_, err := alicloud.SLB().DeleteAccessControlList(deleteAclReq)
if err != nil {
return fmt.Errorf("error deleting LoadBalancerAccessControlList %q, %v", fi.StringValue(acl.ID), err)
}
return nil
}
func (_ *LoadBalancerACL) RenderTerraform(t *terraform.TerraformTarget, a, e, changes *LoadBalancerACL) error {
klog.Warningf("terraform does not support LoadBalancerAccessControlList on ALI cloud")
return nil
}

View File

@ -14,7 +14,7 @@ See the License for the specific language governing permissions and
limitations under the License.
*/
// Code generated by ""fitask" -type=LoadBalancerWhiteList"; DO NOT EDIT
// Code generated by ""fitask" -type=LoadBalancerACL"; DO NOT EDIT
package alitasks
@ -24,52 +24,52 @@ import (
"k8s.io/kops/upup/pkg/fi"
)
// LoadBalancerWhiteList
// LoadBalancerACL
// JSON marshaling boilerplate
type realLoadBalancerWhiteList LoadBalancerWhiteList
type realLoadBalancerACL LoadBalancerACL
// UnmarshalJSON implements conversion to JSON, supporting an alternate specification of the object as a string
func (o *LoadBalancerWhiteList) UnmarshalJSON(data []byte) error {
func (o *LoadBalancerACL) UnmarshalJSON(data []byte) error {
var jsonName string
if err := json.Unmarshal(data, &jsonName); err == nil {
o.Name = &jsonName
return nil
}
var r realLoadBalancerWhiteList
var r realLoadBalancerACL
if err := json.Unmarshal(data, &r); err != nil {
return err
}
*o = LoadBalancerWhiteList(r)
*o = LoadBalancerACL(r)
return nil
}
var _ fi.HasLifecycle = &LoadBalancerWhiteList{}
var _ fi.HasLifecycle = &LoadBalancerACL{}
// GetLifecycle returns the Lifecycle of the object, implementing fi.HasLifecycle
func (o *LoadBalancerWhiteList) GetLifecycle() *fi.Lifecycle {
func (o *LoadBalancerACL) GetLifecycle() *fi.Lifecycle {
return o.Lifecycle
}
// SetLifecycle sets the Lifecycle of the object, implementing fi.SetLifecycle
func (o *LoadBalancerWhiteList) SetLifecycle(lifecycle fi.Lifecycle) {
func (o *LoadBalancerACL) SetLifecycle(lifecycle fi.Lifecycle) {
o.Lifecycle = &lifecycle
}
var _ fi.HasName = &LoadBalancerWhiteList{}
var _ fi.HasName = &LoadBalancerACL{}
// GetName returns the Name of the object, implementing fi.HasName
func (o *LoadBalancerWhiteList) GetName() *string {
func (o *LoadBalancerACL) GetName() *string {
return o.Name
}
// SetName sets the Name of the object, implementing fi.SetName
func (o *LoadBalancerWhiteList) SetName(name string) {
func (o *LoadBalancerACL) SetName(name string) {
o.Name = &name
}
// String is the stringer function for the task, producing readable output using fi.TaskAsString
func (o *LoadBalancerWhiteList) String() string {
func (o *LoadBalancerACL) String() string {
return fi.TaskAsString(o)
}

View File

@ -1,145 +0,0 @@
/*
Copyright 2019 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package alitasks
import (
"fmt"
"strings"
"k8s.io/klog"
"k8s.io/kops/upup/pkg/fi"
"k8s.io/kops/upup/pkg/fi/cloudup/aliup"
"k8s.io/kops/upup/pkg/fi/cloudup/terraform"
)
//go:generate fitask -type=LoadBalancerWhiteList
type LoadBalancerWhiteList struct {
LoadBalancer *LoadBalancer
LoadBalancerListener *LoadBalancerListener
Name *string
SourceItems *string
Lifecycle *fi.Lifecycle
}
var _ fi.CompareWithID = &LoadBalancerWhiteList{}
func (l *LoadBalancerWhiteList) CompareWithID() *string {
return l.Name
}
func (l *LoadBalancerWhiteList) Find(c *fi.Context) (*LoadBalancerWhiteList, error) {
if l.LoadBalancer == nil || l.LoadBalancer.LoadbalancerId == nil {
klog.V(4).Infof("LoadBalancer / LoadbalancerId not found for %s, skipping Find", fi.StringValue(l.Name))
return nil, nil
}
if l.LoadBalancerListener == nil || l.LoadBalancerListener.ListenerPort == nil {
klog.V(4).Infof("LoadBalancerListener / LoadbalancerListenerPort not found for %s, skipping Find", fi.StringValue(l.Name))
return nil, nil
}
cloud := c.Cloud.(aliup.ALICloud)
loadBalancerId := fi.StringValue(l.LoadBalancer.LoadbalancerId)
listenertPort := fi.IntValue(l.LoadBalancerListener.ListenerPort)
response, err := cloud.SlbClient().DescribeListenerAccessControlAttribute(loadBalancerId, listenertPort)
if err != nil {
return nil, fmt.Errorf("error finding LoadBalancerWhiteList: %v", err)
}
if response.SourceItems == "" {
klog.V(2).Infof("can't find matching LoadBalancerWhiteList of ListenerPort: %v", listenertPort)
return nil, nil
}
klog.V(2).Infof("found matching LoadBalancerWhiteList of ListenerPort: %v", listenertPort)
actual := &LoadBalancerWhiteList{}
actual.SourceItems = fi.String(response.SourceItems)
// Ignore "system" fields
actual.Name = l.Name
actual.LoadBalancer = l.LoadBalancer
actual.LoadBalancerListener = l.LoadBalancerListener
actual.Lifecycle = l.Lifecycle
return actual, nil
}
func (l *LoadBalancerWhiteList) Run(c *fi.Context) error {
return fi.DefaultDeltaRunMethod(l, c)
}
func (_ *LoadBalancerWhiteList) CheckChanges(a, e, changes *LoadBalancerWhiteList) error {
if a == nil {
if e.Name == nil {
return fi.RequiredField("Name")
}
}
return nil
}
func (_ *LoadBalancerWhiteList) RenderALI(t *aliup.ALIAPITarget, a, e, changes *LoadBalancerWhiteList) error {
klog.V(2).Infof("Updating LoadBalancerWhiteList of ListenerPort: %q", *e.LoadBalancerListener.ListenerPort)
loadBalancerId := fi.StringValue(e.LoadBalancer.LoadbalancerId)
listenertPort := fi.IntValue(e.LoadBalancerListener.ListenerPort)
sourceItems := fi.StringValue(e.SourceItems)
if sourceItems != "" {
err := t.Cloud.SlbClient().AddListenerWhiteListItem(loadBalancerId, listenertPort, sourceItems)
if err != nil {
return fmt.Errorf("error adding LoadBalancerWhiteListItems: %v", err)
}
}
if a != nil && changes.SourceItems != nil {
itemsToDelete := e.getWhiteItemsToDelete(fi.StringValue(a.SourceItems))
if itemsToDelete != "" {
err := t.Cloud.SlbClient().RemoveListenerWhiteListItem(loadBalancerId, listenertPort, itemsToDelete)
if err != nil {
return fmt.Errorf("error removing LoadBalancerWhiteListItems: %v", err)
}
}
}
return nil
}
func (l *LoadBalancerWhiteList) getWhiteItemsToDelete(currentWhiteItems string) string {
currentWhiteItemsList := strings.Split(currentWhiteItems, ",")
expectedWhiteItemsList := strings.Split(fi.StringValue(l.SourceItems), ",")
itemsToDelete := ""
for _, currentItem := range currentWhiteItemsList {
expected := false
if currentItem == "" {
continue
}
for _, expectedItem := range expectedWhiteItemsList {
if currentItem == expectedItem {
expected = true
}
}
if !expected {
itemsToDelete = itemsToDelete + "," + currentItem
}
}
return itemsToDelete
}
func (_ *LoadBalancerWhiteList) RenderTerraform(t *terraform.TerraformTarget, a, e, changes *LoadBalancerWhiteList) error {
klog.Warningf("terraform does not support LoadBalancerWhiteList on ALI cloud")
return nil
}

View File

@ -17,6 +17,9 @@ go_library(
"//pkg/cloudinstances:go_default_library",
"//protokube/pkg/etcd:go_default_library",
"//upup/pkg/fi:go_default_library",
"//vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk:go_default_library",
"//vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credentials:go_default_library",
"//vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/slb:go_default_library",
"//vendor/github.com/denverdino/aliyungo/common:go_default_library",
"//vendor/github.com/denverdino/aliyungo/ecs:go_default_library",
"//vendor/github.com/denverdino/aliyungo/ess:go_default_library",

View File

@ -24,6 +24,9 @@ import (
"k8s.io/klog"
alicloud "github.com/aliyun/alibaba-cloud-sdk-go/sdk"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credentials"
slbnew "github.com/aliyun/alibaba-cloud-sdk-go/services/slb"
"github.com/denverdino/aliyungo/common"
"github.com/denverdino/aliyungo/ecs"
"github.com/denverdino/aliyungo/ess"
@ -50,6 +53,12 @@ var KubernetesKopsIdentity = fmt.Sprintf("Kubernetes.Kops/%s", prj.Version)
type ALICloud interface {
fi.Cloud
// Clients that use official Alicloud go sdk
SLB() *slbnew.Client
// Since package github.com/denverdino/aliyungo is not actively maintained,
// clients that use github.com/denverdino/aliyungo, will be deprecated after
// the above official SDK clients covers all of them
EcsClient() *ecs.Client
SlbClient() *slb.Client
RamClient() *ram.RamClient
@ -66,6 +75,8 @@ type ALICloud interface {
}
type aliCloudImplementation struct {
slb *slbnew.Client
ecsClient *ecs.Client
slbClient *slb.Client
ramClient *ram.RamClient
@ -84,8 +95,8 @@ func NewALICloud(region string, tags map[string]string) (ALICloud, error) {
c := &aliCloudImplementation{region: region}
accessKeyId := os.Getenv("ALIYUN_ACCESS_KEY_ID")
if accessKeyId == "" {
accessKeyID := os.Getenv("ALIYUN_ACCESS_KEY_ID")
if accessKeyID == "" {
return nil, errors.New("ALIYUN_ACCESS_KEY_ID is required")
}
accessKeySecret := os.Getenv("ALIYUN_ACCESS_KEY_SECRET")
@ -93,19 +104,34 @@ func NewALICloud(region string, tags map[string]string) (ALICloud, error) {
return nil, errors.New("ALIYUN_ACCESS_KEY_SECRET is required")
}
c.ecsClient = ecs.NewClient(accessKeyId, accessKeySecret)
c.ecsClient = ecs.NewClient(accessKeyID, accessKeySecret)
c.ecsClient.SetUserAgent(KubernetesKopsIdentity)
c.slbClient = slb.NewClient(accessKeyId, accessKeySecret)
ramclient := ram.NewClient(accessKeyId, accessKeySecret)
c.slbClient = slb.NewClient(accessKeyID, accessKeySecret)
ramclient := ram.NewClient(accessKeyID, accessKeySecret)
c.ramClient = ramclient.(*ram.RamClient)
c.essClient = ess.NewClient(accessKeyId, accessKeySecret)
c.vpcClient = ecs.NewVPCClient(accessKeyId, accessKeySecret, common.Region(region))
c.essClient = ess.NewClient(accessKeyID, accessKeySecret)
c.vpcClient = ecs.NewVPCClient(accessKeyID, accessKeySecret, common.Region(region))
c.tags = tags
// With Alicloud official go SDK
var err error
config := alicloud.NewConfig()
credential := credentials.NewAccessKeyCredential(accessKeyID, accessKeySecret)
c.slb, err = slbnew.NewClientWithOptions(region, config, credential)
if err != nil {
return nil, fmt.Errorf("error creating slb sdk client: %v", err)
}
return c, nil
}
func (c *aliCloudImplementation) SLB() *slbnew.Client {
return c.slb
}
// Clients as below are with github.com/denverdino/aliyungo
func (c *aliCloudImplementation) EcsClient() *ecs.Client {
return c.ecsClient
}

View File

@ -475,7 +475,7 @@ func (c *ApplyClusterCmd) Run(ctx context.Context) error {
"SecurityGroupRule": &alitasks.SecurityGroupRule{},
"LoadBalancer": &alitasks.LoadBalancer{},
"LoadBalancerListener": &alitasks.LoadBalancerListener{},
"LoadBalancerWhiteList": &alitasks.LoadBalancerWhiteList{},
"LoadBalancerACL": &alitasks.LoadBalancerACL{},
"AutoscalingGroup": &alitasks.ScalingGroup{},
"LaunchConfiguration": &alitasks.LaunchConfiguration{},
"RAMPolicy": &alitasks.RAMPolicy{},

View File

@ -28,7 +28,7 @@ import (
type aliyunOSSConfig struct {
region oss.Region
internal bool
accessKeyId string
accessKeyID string
accessKeySecret string
securityToken string
secure bool
@ -53,10 +53,10 @@ func NewAliOSSClient() (*oss.Client, error) {
}
if c.securityToken != "" {
return oss.NewOSSClientForAssumeRole(c.region, c.internal, c.accessKeyId, c.accessKeySecret, c.securityToken, c.secure), nil
return oss.NewOSSClientForAssumeRole(c.region, c.internal, c.accessKeyID, c.accessKeySecret, c.securityToken, c.secure), nil
}
return oss.NewOSSClient(c.region, c.internal, c.accessKeyId, c.accessKeySecret, c.secure), nil
return oss.NewOSSClient(c.region, c.internal, c.accessKeyID, c.accessKeySecret, c.secure), nil
}
func (c *aliyunOSSConfig) loadConfig() error {
@ -71,8 +71,8 @@ func (c *aliyunOSSConfig) loadConfig() error {
c.region = oss.Region(fmt.Sprintf("oss-%s", region))
}
c.accessKeyId = os.Getenv("ALIYUN_ACCESS_KEY_ID")
if c.accessKeyId != "" {
c.accessKeyID = os.Getenv("ALIYUN_ACCESS_KEY_ID")
if c.accessKeyID != "" {
c.accessKeySecret = os.Getenv("ALIYUN_ACCESS_KEY_SECRET")
if c.accessKeySecret == "" {
return fmt.Errorf("ALIYUN_ACCESS_KEY_SECRET cannot be empty")
@ -87,7 +87,7 @@ func (c *aliyunOSSConfig) loadConfig() error {
if err != nil {
return fmt.Errorf("Can't get role token: %s", err)
}
c.accessKeyId = roleAuth.AccessKeyId
c.accessKeyID = roleAuth.AccessKeyId
c.accessKeySecret = roleAuth.AccessKeySecret
c.securityToken = roleAuth.SecurityToken
}

201
vendor/github.com/aliyun/alibaba-cloud-sdk-go/LICENSE generated vendored Normal file
View File

@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright (c) 2009-present, Alibaba Cloud All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

View File

@ -0,0 +1,24 @@
load("@io_bazel_rules_go//go:def.bzl", "go_library")
go_library(
name = "go_default_library",
srcs = [
"api_timeout.go",
"client.go",
"config.go",
"logger.go",
],
importmap = "k8s.io/kops/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk",
importpath = "github.com/aliyun/alibaba-cloud-sdk-go/sdk",
visibility = ["//visibility:public"],
deps = [
"//vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth:go_default_library",
"//vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credentials:go_default_library",
"//vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credentials/provider:go_default_library",
"//vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/endpoints:go_default_library",
"//vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/errors:go_default_library",
"//vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests:go_default_library",
"//vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses:go_default_library",
"//vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/utils:go_default_library",
],
)

View File

@ -0,0 +1,249 @@
package sdk
import (
"encoding/json"
"strings"
"time"
)
var apiTimeouts = `{
"ecs": {
"ActivateRouterInterface": 10,
"AddTags": 61,
"AllocateDedicatedHosts": 10,
"AllocateEipAddress": 17,
"AllocatePublicIpAddress": 36,
"ApplyAutoSnapshotPolicy": 10,
"AssignIpv6Addresses": 10,
"AssignPrivateIpAddresses": 10,
"AssociateEipAddress": 17,
"AttachClassicLinkVpc": 14,
"AttachDisk": 36,
"AttachInstanceRamRole": 11,
"AttachKeyPair": 16,
"AttachNetworkInterface": 16,
"AuthorizeSecurityGroupEgress": 16,
"AuthorizeSecurityGroup": 16,
"CancelAutoSnapshotPolicy": 10,
"CancelCopyImage": 10,
"CancelPhysicalConnection": 10,
"CancelSimulatedSystemEvents": 10,
"CancelTask": 10,
"ConnectRouterInterface": 10,
"ConvertNatPublicIpToEip": 12,
"CopyImage": 10,
"CreateAutoSnapshotPolicy": 10,
"CreateCommand": 16,
"CreateDeploymentSet": 16,
"CreateDisk": 36,
"CreateHpcCluster": 10,
"CreateImage": 36,
"CreateInstance": 86,
"CreateKeyPair": 10,
"CreateLaunchTemplate": 10,
"CreateLaunchTemplateVersion": 10,
"CreateNatGateway": 36,
"CreateNetworkInterfacePermission": 13,
"CreateNetworkInterface": 16,
"CreatePhysicalConnection": 10,
"CreateRouteEntry": 17,
"CreateRouterInterface": 10,
"CreateSecurityGroup": 86,
"CreateSimulatedSystemEvents": 10,
"CreateSnapshot": 86,
"CreateVirtualBorderRouter": 10,
"CreateVpc": 16,
"CreateVSwitch": 17,
"DeactivateRouterInterface": 10,
"DeleteAutoSnapshotPolicy": 10,
"DeleteBandwidthPackage": 10,
"DeleteCommand": 16,
"DeleteDeploymentSet": 12,
"DeleteDisk": 16,
"DeleteHpcCluster": 10,
"DeleteImage": 36,
"DeleteInstance": 66,
"DeleteKeyPairs": 10,
"DeleteLaunchTemplate": 10,
"DeleteLaunchTemplateVersion": 10,
"DeleteNatGateway": 10,
"DeleteNetworkInterfacePermission": 10,
"DeleteNetworkInterface": 16,
"DeletePhysicalConnection": 10,
"DeleteRouteEntry": 16,
"DeleteRouterInterface": 10,
"DeleteSecurityGroup": 87,
"DeleteSnapshot": 17,
"DeleteVirtualBorderRouter": 10,
"DeleteVpc": 17,
"DeleteVSwitch": 17,
"DescribeAccessPoints": 10,
"DescribeAccountAttributes": 10,
"DescribeAutoSnapshotPolicyEx": 16,
"DescribeAvailableResource": 10,
"DescribeBandwidthLimitation": 16,
"DescribeBandwidthPackages": 10,
"DescribeClassicLinkInstances": 15,
"DescribeCloudAssistantStatus": 16,
"DescribeClusters": 10,
"DescribeCommands": 16,
"DescribeDedicatedHosts": 10,
"DescribeDedicatedHostTypes": 10,
"DescribeDeploymentSets": 26,
"DescribeDiskMonitorData": 16,
"DescribeDisksFullStatus": 14,
"DescribeDisks": 19,
"DescribeEipAddresses": 16,
"DescribeEipMonitorData": 16,
"DescribeEniMonitorData": 10,
"DescribeHaVips": 10,
"DescribeHpcClusters": 16,
"DescribeImageSharePermission": 10,
"DescribeImages": 38,
"DescribeImageSupportInstanceTypes": 16,
"DescribeInstanceAttribute": 36,
"DescribeInstanceAutoRenewAttribute": 17,
"DescribeInstanceHistoryEvents": 19,
"DescribeInstanceMonitorData": 19,
"DescribeInstancePhysicalAttribute": 10,
"DescribeInstanceRamRole": 11,
"DescribeInstancesFullStatus": 14,
"DescribeInstances": 10,
"DescribeInstanceStatus": 26,
"DescribeInstanceTopology": 12,
"DescribeInstanceTypeFamilies": 17,
"DescribeInstanceTypes": 17,
"DescribeInstanceVncPasswd": 10,
"DescribeInstanceVncUrl": 36,
"DescribeInvocationResults": 16,
"DescribeInvocations": 16,
"DescribeKeyPairs": 12,
"DescribeLaunchTemplates": 16,
"DescribeLaunchTemplateVersions": 16,
"DescribeLimitation": 36,
"DescribeNatGateways": 10,
"DescribeNetworkInterfacePermissions": 13,
"DescribeNetworkInterfaces": 16,
"DescribeNewProjectEipMonitorData": 16,
"DescribePhysicalConnections": 10,
"DescribePrice": 16,
"DescribeRecommendInstanceType": 10,
"DescribeRegions": 19,
"DescribeRenewalPrice": 16,
"DescribeResourceByTags": 10,
"DescribeResourcesModification": 17,
"DescribeRouterInterfaces": 10,
"DescribeRouteTables": 17,
"DescribeSecurityGroupAttribute": 133,
"DescribeSecurityGroupReferences": 16,
"DescribeSecurityGroups": 25,
"DescribeSnapshotLinks": 17,
"DescribeSnapshotMonitorData": 12,
"DescribeSnapshotPackage": 10,
"DescribeSnapshots": 26,
"DescribeSnapshotsUsage": 26,
"DescribeSpotPriceHistory": 22,
"DescribeTags": 17,
"DescribeTaskAttribute": 10,
"DescribeTasks": 11,
"DescribeUserBusinessBehavior": 13,
"DescribeUserData": 10,
"DescribeVirtualBorderRoutersForPhysicalConnection": 10,
"DescribeVirtualBorderRouters": 10,
"DescribeVpcs": 41,
"DescribeVRouters": 17,
"DescribeVSwitches": 17,
"DescribeZones": 103,
"DetachClassicLinkVpc": 14,
"DetachDisk": 17,
"DetachInstanceRamRole": 10,
"DetachKeyPair": 10,
"DetachNetworkInterface": 16,
"EipFillParams": 19,
"EipFillProduct": 13,
"EipNotifyPaid": 10,
"EnablePhysicalConnection": 10,
"ExportImage": 10,
"GetInstanceConsoleOutput": 14,
"GetInstanceScreenshot": 14,
"ImportImage": 29,
"ImportKeyPair": 10,
"InstallCloudAssistant": 10,
"InvokeCommand": 16,
"JoinResourceGroup": 10,
"JoinSecurityGroup": 66,
"LeaveSecurityGroup": 66,
"ModifyAutoSnapshotPolicyEx": 10,
"ModifyBandwidthPackageSpec": 11,
"ModifyCommand": 10,
"ModifyDeploymentSetAttribute": 10,
"ModifyDiskAttribute": 16,
"ModifyDiskChargeType": 13,
"ModifyEipAddressAttribute": 14,
"ModifyImageAttribute": 10,
"ModifyImageSharePermission": 16,
"ModifyInstanceAttribute": 22,
"ModifyInstanceAutoReleaseTime": 15,
"ModifyInstanceAutoRenewAttribute": 16,
"ModifyInstanceChargeType": 22,
"ModifyInstanceDeployment": 10,
"ModifyInstanceNetworkSpec": 36,
"ModifyInstanceSpec": 62,
"ModifyInstanceVncPasswd": 35,
"ModifyInstanceVpcAttribute": 15,
"ModifyLaunchTemplateDefaultVersion": 10,
"ModifyNetworkInterfaceAttribute": 10,
"ModifyPhysicalConnectionAttribute": 10,
"ModifyPrepayInstanceSpec": 13,
"ModifyRouterInterfaceAttribute": 10,
"ModifySecurityGroupAttribute": 10,
"ModifySecurityGroupEgressRule": 10,
"ModifySecurityGroupPolicy": 10,
"ModifySecurityGroupRule": 16,
"ModifySnapshotAttribute": 10,
"ModifyUserBusinessBehavior": 10,
"ModifyVirtualBorderRouterAttribute": 10,
"ModifyVpcAttribute": 10,
"ModifyVRouterAttribute": 10,
"ModifyVSwitchAttribute": 10,
"ReActivateInstances": 10,
"RebootInstance": 27,
"RedeployInstance": 14,
"ReInitDisk": 16,
"ReleaseDedicatedHost": 10,
"ReleaseEipAddress": 16,
"ReleasePublicIpAddress": 10,
"RemoveTags": 10,
"RenewInstance": 19,
"ReplaceSystemDisk": 36,
"ResetDisk": 36,
"ResizeDisk": 11,
"RevokeSecurityGroupEgress": 13,
"RevokeSecurityGroup": 16,
"RunInstances": 86,
"StartInstance": 46,
"StopInstance": 27,
"StopInvocation": 10,
"TerminatePhysicalConnection": 10,
"TerminateVirtualBorderRouter": 10,
"UnassignIpv6Addresses": 10,
"UnassignPrivateIpAddresses": 10,
"UnassociateEipAddress": 16
}
}
`
func getAPIMaxTimeout(product, actionName string) (time.Duration, bool) {
timeout := make(map[string]map[string]int)
err := json.Unmarshal([]byte(apiTimeouts), &timeout)
if err != nil {
return 0 * time.Millisecond, false
}
obj := timeout[strings.ToLower(product)]
if obj != nil && obj[actionName] != 0 {
return time.Duration(obj[actionName]) * time.Second, true
}
return 0 * time.Millisecond, false
}

View File

@ -0,0 +1,22 @@
load("@io_bazel_rules_go//go:def.bzl", "go_library")
go_library(
name = "go_default_library",
srcs = [
"credential.go",
"roa_signature_composer.go",
"rpc_signature_composer.go",
"signer.go",
],
importmap = "k8s.io/kops/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth",
importpath = "github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth",
visibility = ["//visibility:public"],
deps = [
"//vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credentials:go_default_library",
"//vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/signers:go_default_library",
"//vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/errors:go_default_library",
"//vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests:go_default_library",
"//vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses:go_default_library",
"//vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/utils:go_default_library",
],
)

View File

@ -0,0 +1,18 @@
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package auth
type Credential interface {
}

View File

@ -0,0 +1,16 @@
load("@io_bazel_rules_go//go:def.bzl", "go_library")
go_library(
name = "go_default_library",
srcs = [
"access_key_credential.go",
"bearer_token_credential.go",
"ecs_ram_role.go",
"rsa_key_pair_credential.go",
"sts_credential.go",
"sts_role_arn_credential.go",
],
importmap = "k8s.io/kops/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credentials",
importpath = "github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credentials",
visibility = ["//visibility:public"],
)

View File

@ -0,0 +1,34 @@
package credentials
// Deprecated: Use AccessKeyCredential in this package instead.
type BaseCredential struct {
AccessKeyId string
AccessKeySecret string
}
type AccessKeyCredential struct {
AccessKeyId string
AccessKeySecret string
}
// Deprecated: Use NewAccessKeyCredential in this package instead.
func NewBaseCredential(accessKeyId, accessKeySecret string) *BaseCredential {
return &BaseCredential{
AccessKeyId: accessKeyId,
AccessKeySecret: accessKeySecret,
}
}
func (baseCred *BaseCredential) ToAccessKeyCredential() *AccessKeyCredential {
return &AccessKeyCredential{
AccessKeyId: baseCred.AccessKeyId,
AccessKeySecret: baseCred.AccessKeySecret,
}
}
func NewAccessKeyCredential(accessKeyId, accessKeySecret string) *AccessKeyCredential {
return &AccessKeyCredential{
AccessKeyId: accessKeyId,
AccessKeySecret: accessKeySecret,
}
}

View File

@ -0,0 +1,12 @@
package credentials
type BearerTokenCredential struct {
BearerToken string
}
// NewBearerTokenCredential return a BearerTokenCredential object
func NewBearerTokenCredential(token string) *BearerTokenCredential {
return &BearerTokenCredential{
BearerToken: token,
}
}

View File

@ -0,0 +1,29 @@
package credentials
func (oldCred *StsRoleNameOnEcsCredential) ToEcsRamRoleCredential() *EcsRamRoleCredential {
return &EcsRamRoleCredential{
RoleName: oldCred.RoleName,
}
}
type EcsRamRoleCredential struct {
RoleName string
}
func NewEcsRamRoleCredential(roleName string) *EcsRamRoleCredential {
return &EcsRamRoleCredential{
RoleName: roleName,
}
}
// Deprecated: Use EcsRamRoleCredential in this package instead.
type StsRoleNameOnEcsCredential struct {
RoleName string
}
// Deprecated: Use NewEcsRamRoleCredential in this package instead.
func NewStsRoleNameOnEcsCredential(roleName string) *StsRoleNameOnEcsCredential {
return &StsRoleNameOnEcsCredential{
RoleName: roleName,
}
}

View File

@ -0,0 +1,20 @@
load("@io_bazel_rules_go//go:def.bzl", "go_library")
go_library(
name = "go_default_library",
srcs = [
"env.go",
"instance_credentials.go",
"profile_credentials.go",
"provider.go",
"provider_chain.go",
],
importmap = "k8s.io/kops/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credentials/provider",
importpath = "github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credentials/provider",
visibility = ["//visibility:public"],
deps = [
"//vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth:go_default_library",
"//vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credentials:go_default_library",
"//vendor/gopkg.in/ini.v1:go_default_library",
],
)

View File

@ -0,0 +1,30 @@
package provider
import (
"errors"
"os"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credentials"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth"
)
type EnvProvider struct{}
var ProviderEnv = new(EnvProvider)
func NewEnvProvider() Provider {
return &EnvProvider{}
}
func (p *EnvProvider) Resolve() (auth.Credential, error) {
accessKeyID, ok1 := os.LookupEnv(ENVAccessKeyID)
accessKeySecret, ok2 := os.LookupEnv(ENVAccessKeySecret)
if !ok1 || !ok2 {
return nil, nil
}
if accessKeyID == "" || accessKeySecret == "" {
return nil, errors.New("Environmental variable (ALIBABACLOUD_ACCESS_KEY_ID or ALIBABACLOUD_ACCESS_KEY_SECRET) is empty")
}
return credentials.NewAccessKeyCredential(accessKeyID, accessKeySecret), nil
}

View File

@ -0,0 +1,92 @@
package provider
import (
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"net/http"
"os"
"time"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credentials"
)
var securityCredURL = "http://100.100.100.200/latest/meta-data/ram/security-credentials/"
type InstanceCredentialsProvider struct{}
var ProviderInstance = new(InstanceCredentialsProvider)
var HookGet = func(fn func(string) (int, []byte, error)) func(string) (int, []byte, error) {
return fn
}
func NewInstanceCredentialsProvider() Provider {
return &InstanceCredentialsProvider{}
}
func (p *InstanceCredentialsProvider) Resolve() (auth.Credential, error) {
roleName, ok := os.LookupEnv(ENVEcsMetadata)
if !ok {
return nil, nil
}
if roleName == "" {
return nil, errors.New("Environmental variable 'ALIBABA_CLOUD_ECS_METADATA' are empty")
}
status, content, err := HookGet(get)(securityCredURL + roleName)
if err != nil {
return nil, err
}
if status != 200 {
if status == 404 {
return nil, fmt.Errorf("The role was not found in the instance")
}
return nil, fmt.Errorf("Received %d when getting security credentials for %s", status, roleName)
}
body := make(map[string]interface{})
if err := json.Unmarshal(content, &body); err != nil {
return nil, err
}
accessKeyID, err := extractString(body, "AccessKeyId")
if err != nil {
return nil, err
}
accessKeySecret, err := extractString(body, "AccessKeySecret")
if err != nil {
return nil, err
}
securityToken, err := extractString(body, "SecurityToken")
if err != nil {
return nil, err
}
return credentials.NewStsTokenCredential(accessKeyID, accessKeySecret, securityToken), nil
}
func get(url string) (status int, content []byte, err error) {
httpClient := http.DefaultClient
httpClient.Timeout = 1 * time.Second
resp, err := httpClient.Get(url)
if err != nil {
return
}
defer resp.Body.Close()
content, err = ioutil.ReadAll(resp.Body)
return resp.StatusCode, content, err
}
func extractString(m map[string]interface{}, key string) (string, error) {
raw, ok := m[key]
if !ok {
return "", fmt.Errorf("%s not in map", key)
}
str, ok := raw.(string)
if !ok {
return "", fmt.Errorf("%s is not a string in map", key)
}
return str, nil
}

View File

@ -0,0 +1,159 @@
package provider
import (
"bufio"
"errors"
"os"
"runtime"
"strings"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credentials"
ini "gopkg.in/ini.v1"
)
type ProfileProvider struct {
Profile string
}
var ProviderProfile = NewProfileProvider()
// NewProfileProvider receive zero or more parameters,
// when length of name is 0, the value of field Profile will be "default",
// and when there are multiple inputs, the function will take the
// first one and discard the other values.
func NewProfileProvider(name ...string) Provider {
p := new(ProfileProvider)
if len(name) == 0 {
p.Profile = "default"
} else {
p.Profile = name[0]
}
return p
}
// Resolve implements the Provider interface
// when credential type is rsa_key_pair, the content of private_key file
// must be able to be parsed directly into the required string
// that NewRsaKeyPairCredential function needed
func (p *ProfileProvider) Resolve() (auth.Credential, error) {
path, ok := os.LookupEnv(ENVCredentialFile)
if !ok {
var err error
path, err = checkDefaultPath()
if err != nil {
return nil, err
}
if path == "" {
return nil, nil
}
} else if path == "" {
return nil, errors.New("Environment variable '" + ENVCredentialFile + "' cannot be empty")
}
ini, err := ini.Load(path)
if err != nil {
return nil, errors.New("ERROR: Can not open file" + err.Error())
}
section, err := ini.GetSection(p.Profile)
if err != nil {
return nil, errors.New("ERROR: Can not load section" + err.Error())
}
value, err := section.GetKey("type")
if err != nil {
return nil, errors.New("ERROR: Can not find credential type" + err.Error())
}
switch value.String() {
case "access_key":
value1, err1 := section.GetKey("access_key_id")
value2, err2 := section.GetKey("access_key_secret")
if err1 != nil || err2 != nil {
return nil, errors.New("ERROR: Failed to get value")
}
if value1.String() == "" || value2.String() == "" {
return nil, errors.New("ERROR: Value can't be empty")
}
return credentials.NewAccessKeyCredential(value1.String(), value2.String()), nil
case "ecs_ram_role":
value1, err1 := section.GetKey("role_name")
if err1 != nil {
return nil, errors.New("ERROR: Failed to get value")
}
if value1.String() == "" {
return nil, errors.New("ERROR: Value can't be empty")
}
return credentials.NewEcsRamRoleCredential(value1.String()), nil
case "ram_role_arn":
value1, err1 := section.GetKey("access_key_id")
value2, err2 := section.GetKey("access_key_secret")
value3, err3 := section.GetKey("role_arn")
value4, err4 := section.GetKey("role_session_name")
if err1 != nil || err2 != nil || err3 != nil || err4 != nil {
return nil, errors.New("ERROR: Failed to get value")
}
if value1.String() == "" || value2.String() == "" || value3.String() == "" || value4.String() == "" {
return nil, errors.New("ERROR: Value can't be empty")
}
return credentials.NewRamRoleArnCredential(value1.String(), value2.String(), value3.String(), value4.String(), 3600), nil
case "rsa_key_pair":
value1, err1 := section.GetKey("public_key_id")
value2, err2 := section.GetKey("private_key_file")
if err1 != nil || err2 != nil {
return nil, errors.New("ERROR: Failed to get value")
}
if value1.String() == "" || value2.String() == "" {
return nil, errors.New("ERROR: Value can't be empty")
}
file, err := os.Open(value2.String())
if err != nil {
return nil, errors.New("ERROR: Can not get private_key")
}
defer file.Close()
var privateKey string
scan := bufio.NewScanner(file)
var data string
for scan.Scan() {
if strings.HasPrefix(scan.Text(), "----") {
continue
}
data += scan.Text() + "\n"
}
return credentials.NewRsaKeyPairCredential(privateKey, value1.String(), 3600), nil
default:
return nil, errors.New("ERROR: Failed to get credential")
}
}
// GetHomePath return home directory according to the system.
// if the environmental virables does not exist, will return empty
func GetHomePath() string {
if runtime.GOOS == "windows" {
path, ok := os.LookupEnv("USERPROFILE")
if !ok {
return ""
}
return path
}
path, ok := os.LookupEnv("HOME")
if !ok {
return ""
}
return path
}
func checkDefaultPath() (path string, err error) {
path = GetHomePath()
if path == "" {
return "", errors.New("The default credential file path is invalid")
}
path = strings.Replace("~/.alibabacloud/credentials", "~", path, 1)
_, err = os.Stat(path)
if err != nil {
return "", nil
}
return path, nil
}

View File

@ -0,0 +1,19 @@
package provider
import (
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth"
)
//Environmental virables that may be used by the provider
const (
ENVAccessKeyID = "ALIBABA_CLOUD_ACCESS_KEY_ID"
ENVAccessKeySecret = "ALIBABA_CLOUD_ACCESS_KEY_SECRET"
ENVCredentialFile = "ALIBABA_CLOUD_CREDENTIALS_FILE"
ENVEcsMetadata = "ALIBABA_CLOUD_ECS_METADATA"
PATHCredentialFile = "~/.alibabacloud/credentials"
)
// When you want to customize the provider, you only need to implement the method of the interface.
type Provider interface {
Resolve() (auth.Credential, error)
}

View File

@ -0,0 +1,34 @@
package provider
import (
"errors"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth"
)
type ProviderChain struct {
Providers []Provider
}
var defaultproviders = []Provider{ProviderEnv, ProviderProfile, ProviderInstance}
var DefaultChain = NewProviderChain(defaultproviders)
func NewProviderChain(providers []Provider) Provider {
return &ProviderChain{
Providers: providers,
}
}
func (p *ProviderChain) Resolve() (auth.Credential, error) {
for _, provider := range p.Providers {
creds, err := provider.Resolve()
if err != nil {
return nil, err
} else if err == nil && creds == nil {
continue
}
return creds, err
}
return nil, errors.New("No credential found")
}

View File

@ -0,0 +1,15 @@
package credentials
type RsaKeyPairCredential struct {
PrivateKey string
PublicKeyId string
SessionExpiration int
}
func NewRsaKeyPairCredential(privateKey, publicKeyId string, sessionExpiration int) *RsaKeyPairCredential {
return &RsaKeyPairCredential{
PrivateKey: privateKey,
PublicKeyId: publicKeyId,
SessionExpiration: sessionExpiration,
}
}

View File

@ -0,0 +1,15 @@
package credentials
type StsTokenCredential struct {
AccessKeyId string
AccessKeySecret string
AccessKeyStsToken string
}
func NewStsTokenCredential(accessKeyId, accessKeySecret, accessKeyStsToken string) *StsTokenCredential {
return &StsTokenCredential{
AccessKeyId: accessKeyId,
AccessKeySecret: accessKeySecret,
AccessKeyStsToken: accessKeyStsToken,
}
}

View File

@ -0,0 +1,61 @@
package credentials
// Deprecated: Use RamRoleArnCredential in this package instead.
type StsRoleArnCredential struct {
AccessKeyId string
AccessKeySecret string
RoleArn string
RoleSessionName string
RoleSessionExpiration int
}
type RamRoleArnCredential struct {
AccessKeyId string
AccessKeySecret string
RoleArn string
RoleSessionName string
RoleSessionExpiration int
Policy string
}
// Deprecated: Use RamRoleArnCredential in this package instead.
func NewStsRoleArnCredential(accessKeyId, accessKeySecret, roleArn, roleSessionName string, roleSessionExpiration int) *StsRoleArnCredential {
return &StsRoleArnCredential{
AccessKeyId: accessKeyId,
AccessKeySecret: accessKeySecret,
RoleArn: roleArn,
RoleSessionName: roleSessionName,
RoleSessionExpiration: roleSessionExpiration,
}
}
func (oldCred *StsRoleArnCredential) ToRamRoleArnCredential() *RamRoleArnCredential {
return &RamRoleArnCredential{
AccessKeyId: oldCred.AccessKeyId,
AccessKeySecret: oldCred.AccessKeySecret,
RoleArn: oldCred.RoleArn,
RoleSessionName: oldCred.RoleSessionName,
RoleSessionExpiration: oldCred.RoleSessionExpiration,
}
}
func NewRamRoleArnCredential(accessKeyId, accessKeySecret, roleArn, roleSessionName string, roleSessionExpiration int) *RamRoleArnCredential {
return &RamRoleArnCredential{
AccessKeyId: accessKeyId,
AccessKeySecret: accessKeySecret,
RoleArn: roleArn,
RoleSessionName: roleSessionName,
RoleSessionExpiration: roleSessionExpiration,
}
}
func NewRamRoleArnWithPolicyCredential(accessKeyId, accessKeySecret, roleArn, roleSessionName, policy string, roleSessionExpiration int) *RamRoleArnCredential {
return &RamRoleArnCredential{
AccessKeyId: accessKeyId,
AccessKeySecret: accessKeySecret,
RoleArn: roleArn,
RoleSessionName: roleSessionName,
RoleSessionExpiration: roleSessionExpiration,
Policy: policy,
}
}

View File

@ -0,0 +1,138 @@
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package auth
import (
"bytes"
"sort"
"strings"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/utils"
)
var debug utils.Debug
var hookGetDate = func(fn func() string) string {
return fn()
}
func init() {
debug = utils.Init("sdk")
}
func signRoaRequest(request requests.AcsRequest, signer Signer, regionId string) (err error) {
completeROASignParams(request, signer, regionId)
stringToSign := buildRoaStringToSign(request)
request.SetStringToSign(stringToSign)
accessKeyId, err := signer.GetAccessKeyId()
if err != nil {
return err
}
signature := signer.Sign(stringToSign, "")
request.GetHeaders()["Authorization"] = "acs " + accessKeyId + ":" + signature
return
}
func completeROASignParams(request requests.AcsRequest, signer Signer, regionId string) {
headerParams := request.GetHeaders()
// complete query params
queryParams := request.GetQueryParams()
//if _, ok := queryParams["RegionId"]; !ok {
// queryParams["RegionId"] = regionId
//}
if extraParam := signer.GetExtraParam(); extraParam != nil {
for key, value := range extraParam {
if key == "SecurityToken" {
headerParams["x-acs-security-token"] = value
continue
}
if key == "BearerToken" {
headerParams["x-acs-bearer-token"] = value
continue
}
queryParams[key] = value
}
}
// complete header params
headerParams["Date"] = hookGetDate(utils.GetTimeInFormatRFC2616)
headerParams["x-acs-signature-method"] = signer.GetName()
headerParams["x-acs-signature-version"] = signer.GetVersion()
if request.GetFormParams() != nil && len(request.GetFormParams()) > 0 {
formString := utils.GetUrlFormedMap(request.GetFormParams())
request.SetContent([]byte(formString))
if headerParams["Content-Type"] == "" {
headerParams["Content-Type"] = requests.Form
}
}
contentMD5 := utils.GetMD5Base64(request.GetContent())
headerParams["Content-MD5"] = contentMD5
if _, contains := headerParams["Content-Type"]; !contains {
headerParams["Content-Type"] = requests.Raw
}
switch format := request.GetAcceptFormat(); format {
case "JSON":
headerParams["Accept"] = requests.Json
case "XML":
headerParams["Accept"] = requests.Xml
default:
headerParams["Accept"] = requests.Raw
}
}
func buildRoaStringToSign(request requests.AcsRequest) (stringToSign string) {
headers := request.GetHeaders()
stringToSignBuilder := bytes.Buffer{}
stringToSignBuilder.WriteString(request.GetMethod())
stringToSignBuilder.WriteString(requests.HeaderSeparator)
// append header keys for sign
appendIfContain(headers, &stringToSignBuilder, "Accept", requests.HeaderSeparator)
appendIfContain(headers, &stringToSignBuilder, "Content-MD5", requests.HeaderSeparator)
appendIfContain(headers, &stringToSignBuilder, "Content-Type", requests.HeaderSeparator)
appendIfContain(headers, &stringToSignBuilder, "Date", requests.HeaderSeparator)
// sort and append headers witch starts with 'x-acs-'
var acsHeaders []string
for key := range headers {
if strings.HasPrefix(key, "x-acs-") {
acsHeaders = append(acsHeaders, key)
}
}
sort.Strings(acsHeaders)
for _, key := range acsHeaders {
stringToSignBuilder.WriteString(key + ":" + headers[key])
stringToSignBuilder.WriteString(requests.HeaderSeparator)
}
// append query params
stringToSignBuilder.WriteString(request.BuildQueries())
stringToSign = stringToSignBuilder.String()
debug("stringToSign: %s", stringToSign)
return
}
func appendIfContain(sourceMap map[string]string, target *bytes.Buffer, key, separator string) {
if value, contain := sourceMap[key]; contain && len(value) > 0 {
target.WriteString(sourceMap[key])
target.WriteString(separator)
}
}

View File

@ -0,0 +1,94 @@
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package auth
import (
"net/url"
"strings"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/utils"
)
var hookGetNonce = func(fn func() string) string {
return fn()
}
func signRpcRequest(request requests.AcsRequest, signer Signer, regionId string) (err error) {
err = completeRpcSignParams(request, signer, regionId)
if err != nil {
return
}
// remove while retry
if _, containsSign := request.GetQueryParams()["Signature"]; containsSign {
delete(request.GetQueryParams(), "Signature")
}
stringToSign := buildRpcStringToSign(request)
request.SetStringToSign(stringToSign)
signature := signer.Sign(stringToSign, "&")
request.GetQueryParams()["Signature"] = signature
return
}
func completeRpcSignParams(request requests.AcsRequest, signer Signer, regionId string) (err error) {
queryParams := request.GetQueryParams()
queryParams["Version"] = request.GetVersion()
queryParams["Action"] = request.GetActionName()
queryParams["Format"] = request.GetAcceptFormat()
queryParams["Timestamp"] = hookGetDate(utils.GetTimeInFormatISO8601)
queryParams["SignatureMethod"] = signer.GetName()
queryParams["SignatureType"] = signer.GetType()
queryParams["SignatureVersion"] = signer.GetVersion()
queryParams["SignatureNonce"] = hookGetNonce(utils.GetUUID)
queryParams["AccessKeyId"], err = signer.GetAccessKeyId()
if err != nil {
return
}
if _, contains := queryParams["RegionId"]; !contains {
queryParams["RegionId"] = regionId
}
if extraParam := signer.GetExtraParam(); extraParam != nil {
for key, value := range extraParam {
queryParams[key] = value
}
}
request.GetHeaders()["Content-Type"] = requests.Form
formString := utils.GetUrlFormedMap(request.GetFormParams())
request.SetContent([]byte(formString))
return
}
func buildRpcStringToSign(request requests.AcsRequest) (stringToSign string) {
signParams := make(map[string]string)
for key, value := range request.GetQueryParams() {
signParams[key] = value
}
for key, value := range request.GetFormParams() {
signParams[key] = value
}
stringToSign = utils.GetUrlFormedMap(signParams)
stringToSign = strings.Replace(stringToSign, "+", "%20", -1)
stringToSign = strings.Replace(stringToSign, "*", "%2A", -1)
stringToSign = strings.Replace(stringToSign, "%7E", "~", -1)
stringToSign = url.QueryEscape(stringToSign)
stringToSign = request.GetMethod() + "&%2F&" + stringToSign
return
}

View File

@ -0,0 +1,98 @@
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package auth
import (
"fmt"
"reflect"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credentials"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/signers"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/errors"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses"
)
type Signer interface {
GetName() string
GetType() string
GetVersion() string
GetAccessKeyId() (string, error)
GetExtraParam() map[string]string
Sign(stringToSign, secretSuffix string) string
}
func NewSignerWithCredential(credential Credential, commonApi func(request *requests.CommonRequest, signer interface{}) (response *responses.CommonResponse, err error)) (signer Signer, err error) {
switch instance := credential.(type) {
case *credentials.AccessKeyCredential:
{
signer = signers.NewAccessKeySigner(instance)
}
case *credentials.StsTokenCredential:
{
signer = signers.NewStsTokenSigner(instance)
}
case *credentials.BearerTokenCredential:
{
signer = signers.NewBearerTokenSigner(instance)
}
case *credentials.RamRoleArnCredential:
{
signer, err = signers.NewRamRoleArnSigner(instance, commonApi)
}
case *credentials.RsaKeyPairCredential:
{
signer, err = signers.NewSignerKeyPair(instance, commonApi)
}
case *credentials.EcsRamRoleCredential:
{
signer = signers.NewEcsRamRoleSigner(instance, commonApi)
}
case *credentials.BaseCredential: // deprecated user interface
{
signer = signers.NewAccessKeySigner(instance.ToAccessKeyCredential())
}
case *credentials.StsRoleArnCredential: // deprecated user interface
{
signer, err = signers.NewRamRoleArnSigner(instance.ToRamRoleArnCredential(), commonApi)
}
case *credentials.StsRoleNameOnEcsCredential: // deprecated user interface
{
signer = signers.NewEcsRamRoleSigner(instance.ToEcsRamRoleCredential(), commonApi)
}
default:
message := fmt.Sprintf(errors.UnsupportedCredentialErrorMessage, reflect.TypeOf(credential))
err = errors.NewClientError(errors.UnsupportedCredentialErrorCode, message, nil)
}
return
}
func Sign(request requests.AcsRequest, signer Signer, regionId string) (err error) {
switch request.GetStyle() {
case requests.ROA:
{
err = signRoaRequest(request, signer, regionId)
}
case requests.RPC:
{
err = signRpcRequest(request, signer, regionId)
}
default:
message := fmt.Sprintf(errors.UnknownRequestTypeErrorMessage, reflect.TypeOf(request))
err = errors.NewClientError(errors.UnknownRequestTypeErrorCode, message, nil)
}
return
}

View File

@ -0,0 +1,27 @@
load("@io_bazel_rules_go//go:def.bzl", "go_library")
go_library(
name = "go_default_library",
srcs = [
"algorithms.go",
"credential_updater.go",
"session_credential.go",
"signer_access_key.go",
"signer_bearer_token.go",
"signer_ecs_ram_role.go",
"signer_key_pair.go",
"signer_ram_role_arn.go",
"signer_sts_token.go",
"signer_v2.go",
],
importmap = "k8s.io/kops/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/signers",
importpath = "github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/signers",
visibility = ["//visibility:public"],
deps = [
"//vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credentials:go_default_library",
"//vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/errors:go_default_library",
"//vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests:go_default_library",
"//vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses:go_default_library",
"//vendor/github.com/jmespath/go-jmespath:go_default_library",
],
)

View File

@ -0,0 +1,57 @@
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package signers
import (
"crypto"
"crypto/hmac"
"crypto/rand"
"crypto/rsa"
"crypto/sha1"
"crypto/x509"
"encoding/base64"
)
func ShaHmac1(source, secret string) string {
key := []byte(secret)
hmac := hmac.New(sha1.New, key)
hmac.Write([]byte(source))
signedBytes := hmac.Sum(nil)
signedString := base64.StdEncoding.EncodeToString(signedBytes)
return signedString
}
func Sha256WithRsa(source, secret string) string {
// block, _ := pem.Decode([]byte(secret))
decodeString, err := base64.StdEncoding.DecodeString(secret)
if err != nil {
panic(err)
}
private, err := x509.ParsePKCS8PrivateKey(decodeString)
if err != nil {
panic(err)
}
h := crypto.Hash.New(crypto.SHA256)
h.Write([]byte(source))
hashed := h.Sum(nil)
signature, err := rsa.SignPKCS1v15(rand.Reader, private.(*rsa.PrivateKey),
crypto.SHA256, hashed)
if err != nil {
panic(err)
}
return base64.StdEncoding.EncodeToString(signature)
}

View File

@ -0,0 +1,54 @@
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package signers
import (
"time"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses"
)
const defaultInAdvanceScale = 0.95
type credentialUpdater struct {
credentialExpiration int
lastUpdateTimestamp int64
inAdvanceScale float64
buildRequestMethod func() (*requests.CommonRequest, error)
responseCallBack func(response *responses.CommonResponse) error
refreshApi func(request *requests.CommonRequest) (response *responses.CommonResponse, err error)
}
func (updater *credentialUpdater) needUpdateCredential() (result bool) {
if updater.inAdvanceScale == 0 {
updater.inAdvanceScale = defaultInAdvanceScale
}
return time.Now().Unix()-updater.lastUpdateTimestamp >= int64(float64(updater.credentialExpiration)*updater.inAdvanceScale)
}
func (updater *credentialUpdater) updateCredential() (err error) {
request, err := updater.buildRequestMethod()
if err != nil {
return
}
response, err := updater.refreshApi(request)
if err != nil {
return
}
updater.lastUpdateTimestamp = time.Now().Unix()
err = updater.responseCallBack(response)
return
}

View File

@ -0,0 +1,7 @@
package signers
type SessionCredential struct {
AccessKeyId string
AccessKeySecret string
StsToken string
}

View File

@ -0,0 +1,54 @@
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package signers
import (
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credentials"
)
type AccessKeySigner struct {
credential *credentials.AccessKeyCredential
}
func (signer *AccessKeySigner) GetExtraParam() map[string]string {
return nil
}
func NewAccessKeySigner(credential *credentials.AccessKeyCredential) *AccessKeySigner {
return &AccessKeySigner{
credential: credential,
}
}
func (*AccessKeySigner) GetName() string {
return "HMAC-SHA1"
}
func (*AccessKeySigner) GetType() string {
return ""
}
func (*AccessKeySigner) GetVersion() string {
return "1.0"
}
func (signer *AccessKeySigner) GetAccessKeyId() (accessKeyId string, err error) {
return signer.credential.AccessKeyId, nil
}
func (signer *AccessKeySigner) Sign(stringToSign, secretSuffix string) string {
secret := signer.credential.AccessKeySecret + secretSuffix
return ShaHmac1(stringToSign, secret)
}

View File

@ -0,0 +1,35 @@
package signers
import (
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credentials"
)
type BearerTokenSigner struct {
credential *credentials.BearerTokenCredential
}
func NewBearerTokenSigner(credential *credentials.BearerTokenCredential) *BearerTokenSigner {
return &BearerTokenSigner{
credential: credential,
}
}
func (signer *BearerTokenSigner) GetExtraParam() map[string]string {
return map[string]string{"BearerToken": signer.credential.BearerToken}
}
func (*BearerTokenSigner) GetName() string {
return ""
}
func (*BearerTokenSigner) GetType() string {
return "BEARERTOKEN"
}
func (*BearerTokenSigner) GetVersion() string {
return "1.0"
}
func (signer *BearerTokenSigner) GetAccessKeyId() (accessKeyId string, err error) {
return "", nil
}
func (signer *BearerTokenSigner) Sign(stringToSign, secretSuffix string) string {
return ""
}

View File

@ -0,0 +1,167 @@
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package signers
import (
"encoding/json"
"fmt"
"net/http"
"strings"
"time"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credentials"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses"
jmespath "github.com/jmespath/go-jmespath"
)
var securityCredURL = "http://100.100.100.200/latest/meta-data/ram/security-credentials/"
type EcsRamRoleSigner struct {
*credentialUpdater
sessionCredential *SessionCredential
credential *credentials.EcsRamRoleCredential
commonApi func(request *requests.CommonRequest, signer interface{}) (response *responses.CommonResponse, err error)
}
func NewEcsRamRoleSigner(credential *credentials.EcsRamRoleCredential, commonApi func(*requests.CommonRequest, interface{}) (response *responses.CommonResponse, err error)) (signer *EcsRamRoleSigner) {
signer = &EcsRamRoleSigner{
credential: credential,
commonApi: commonApi,
}
signer.credentialUpdater = &credentialUpdater{
credentialExpiration: defaultDurationSeconds / 60,
buildRequestMethod: signer.buildCommonRequest,
responseCallBack: signer.refreshCredential,
refreshApi: signer.refreshApi,
}
return signer
}
func (*EcsRamRoleSigner) GetName() string {
return "HMAC-SHA1"
}
func (*EcsRamRoleSigner) GetType() string {
return ""
}
func (*EcsRamRoleSigner) GetVersion() string {
return "1.0"
}
func (signer *EcsRamRoleSigner) GetAccessKeyId() (accessKeyId string, err error) {
if signer.sessionCredential == nil || signer.needUpdateCredential() {
err = signer.updateCredential()
if err != nil {
return
}
}
if signer.sessionCredential == nil || len(signer.sessionCredential.AccessKeyId) <= 0 {
return "", nil
}
return signer.sessionCredential.AccessKeyId, nil
}
func (signer *EcsRamRoleSigner) GetExtraParam() map[string]string {
if signer.sessionCredential == nil {
return make(map[string]string)
}
if len(signer.sessionCredential.StsToken) <= 0 {
return make(map[string]string)
}
return map[string]string{"SecurityToken": signer.sessionCredential.StsToken}
}
func (signer *EcsRamRoleSigner) Sign(stringToSign, secretSuffix string) string {
secret := signer.sessionCredential.AccessKeySecret + secretSuffix
return ShaHmac1(stringToSign, secret)
}
func (signer *EcsRamRoleSigner) buildCommonRequest() (request *requests.CommonRequest, err error) {
return
}
func (signer *EcsRamRoleSigner) refreshApi(request *requests.CommonRequest) (response *responses.CommonResponse, err error) {
requestUrl := securityCredURL + signer.credential.RoleName
httpRequest, err := http.NewRequest(requests.GET, requestUrl, strings.NewReader(""))
if err != nil {
err = fmt.Errorf("refresh Ecs sts token err: %s", err.Error())
return
}
httpClient := &http.Client{}
httpResponse, err := httpClient.Do(httpRequest)
if err != nil {
err = fmt.Errorf("refresh Ecs sts token err: %s", err.Error())
return
}
response = responses.NewCommonResponse()
err = responses.Unmarshal(response, httpResponse, "")
return
}
func (signer *EcsRamRoleSigner) refreshCredential(response *responses.CommonResponse) (err error) {
if response.GetHttpStatus() != http.StatusOK {
return fmt.Errorf("refresh Ecs sts token err, httpStatus: %d, message = %s", response.GetHttpStatus(), response.GetHttpContentString())
}
var data interface{}
err = json.Unmarshal(response.GetHttpContentBytes(), &data)
if err != nil {
return fmt.Errorf("refresh Ecs sts token err, json.Unmarshal fail: %s", err.Error())
}
code, err := jmespath.Search("Code", data)
if err != nil {
return fmt.Errorf("refresh Ecs sts token err, fail to get Code: %s", err.Error())
}
if code.(string) != "Success" {
return fmt.Errorf("refresh Ecs sts token err, Code is not Success")
}
accessKeyId, err := jmespath.Search("AccessKeyId", data)
if err != nil {
return fmt.Errorf("refresh Ecs sts token err, fail to get AccessKeyId: %s", err.Error())
}
accessKeySecret, err := jmespath.Search("AccessKeySecret", data)
if err != nil {
return fmt.Errorf("refresh Ecs sts token err, fail to get AccessKeySecret: %s", err.Error())
}
securityToken, err := jmespath.Search("SecurityToken", data)
if err != nil {
return fmt.Errorf("refresh Ecs sts token err, fail to get SecurityToken: %s", err.Error())
}
expiration, err := jmespath.Search("Expiration", data)
if err != nil {
return fmt.Errorf("refresh Ecs sts token err, fail to get Expiration: %s", err.Error())
}
if accessKeyId == nil || accessKeySecret == nil || securityToken == nil || expiration == nil {
return
}
expirationTime, err := time.Parse("2006-01-02T15:04:05Z", expiration.(string))
signer.credentialExpiration = int(expirationTime.Unix() - time.Now().Unix())
signer.sessionCredential = &SessionCredential{
AccessKeyId: accessKeyId.(string),
AccessKeySecret: accessKeySecret.(string),
StsToken: securityToken.(string),
}
return
}
func (signer *EcsRamRoleSigner) GetSessionCredential() *SessionCredential {
return signer.sessionCredential
}

View File

@ -0,0 +1,148 @@
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package signers
import (
"encoding/json"
"fmt"
"net/http"
"strconv"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credentials"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/errors"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses"
jmespath "github.com/jmespath/go-jmespath"
)
type SignerKeyPair struct {
*credentialUpdater
sessionCredential *SessionCredential
credential *credentials.RsaKeyPairCredential
commonApi func(request *requests.CommonRequest, signer interface{}) (response *responses.CommonResponse, err error)
}
func NewSignerKeyPair(credential *credentials.RsaKeyPairCredential, commonApi func(*requests.CommonRequest, interface{}) (response *responses.CommonResponse, err error)) (signer *SignerKeyPair, err error) {
signer = &SignerKeyPair{
credential: credential,
commonApi: commonApi,
}
signer.credentialUpdater = &credentialUpdater{
credentialExpiration: credential.SessionExpiration,
buildRequestMethod: signer.buildCommonRequest,
responseCallBack: signer.refreshCredential,
refreshApi: signer.refreshApi,
}
if credential.SessionExpiration > 0 {
if credential.SessionExpiration >= 900 && credential.SessionExpiration <= 3600 {
signer.credentialExpiration = credential.SessionExpiration
} else {
err = errors.NewClientError(errors.InvalidParamErrorCode, "Key Pair session duration should be in the range of 15min - 1Hr", nil)
}
} else {
signer.credentialExpiration = defaultDurationSeconds
}
return
}
func (*SignerKeyPair) GetName() string {
return "HMAC-SHA1"
}
func (*SignerKeyPair) GetType() string {
return ""
}
func (*SignerKeyPair) GetVersion() string {
return "1.0"
}
func (signer *SignerKeyPair) ensureCredential() error {
if signer.sessionCredential == nil || signer.needUpdateCredential() {
return signer.updateCredential()
}
return nil
}
func (signer *SignerKeyPair) GetAccessKeyId() (accessKeyId string, err error) {
err = signer.ensureCredential()
if err != nil {
return
}
if signer.sessionCredential == nil || len(signer.sessionCredential.AccessKeyId) <= 0 {
accessKeyId = ""
return
}
accessKeyId = signer.sessionCredential.AccessKeyId
return
}
func (signer *SignerKeyPair) GetExtraParam() map[string]string {
return make(map[string]string)
}
func (signer *SignerKeyPair) Sign(stringToSign, secretSuffix string) string {
secret := signer.sessionCredential.AccessKeySecret + secretSuffix
return ShaHmac1(stringToSign, secret)
}
func (signer *SignerKeyPair) buildCommonRequest() (request *requests.CommonRequest, err error) {
request = requests.NewCommonRequest()
request.Product = "Sts"
request.Version = "2015-04-01"
request.ApiName = "GenerateSessionAccessKey"
request.Scheme = requests.HTTPS
request.SetDomain("sts.ap-northeast-1.aliyuncs.com")
request.QueryParams["PublicKeyId"] = signer.credential.PublicKeyId
request.QueryParams["DurationSeconds"] = strconv.Itoa(signer.credentialExpiration)
return
}
func (signer *SignerKeyPair) refreshApi(request *requests.CommonRequest) (response *responses.CommonResponse, err error) {
signerV2 := NewSignerV2(signer.credential)
return signer.commonApi(request, signerV2)
}
func (signer *SignerKeyPair) refreshCredential(response *responses.CommonResponse) (err error) {
if response.GetHttpStatus() != http.StatusOK {
message := "refresh session AccessKey failed"
err = errors.NewServerError(response.GetHttpStatus(), response.GetHttpContentString(), message)
return
}
var data interface{}
err = json.Unmarshal(response.GetHttpContentBytes(), &data)
if err != nil {
return fmt.Errorf("refresh KeyPair err, json.Unmarshal fail: %s", err.Error())
}
accessKeyId, err := jmespath.Search("SessionAccessKey.SessionAccessKeyId", data)
if err != nil {
return fmt.Errorf("refresh KeyPair err, fail to get SessionAccessKeyId: %s", err.Error())
}
accessKeySecret, err := jmespath.Search("SessionAccessKey.SessionAccessKeySecret", data)
if err != nil {
return fmt.Errorf("refresh KeyPair err, fail to get SessionAccessKeySecret: %s", err.Error())
}
if accessKeyId == nil || accessKeySecret == nil {
return
}
signer.sessionCredential = &SessionCredential{
AccessKeyId: accessKeyId.(string),
AccessKeySecret: accessKeySecret.(string),
}
return
}

View File

@ -0,0 +1,175 @@
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package signers
import (
"encoding/json"
"fmt"
"net/http"
"strconv"
"time"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credentials"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/errors"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses"
jmespath "github.com/jmespath/go-jmespath"
)
const (
defaultDurationSeconds = 3600
)
type RamRoleArnSigner struct {
*credentialUpdater
roleSessionName string
sessionCredential *SessionCredential
credential *credentials.RamRoleArnCredential
commonApi func(request *requests.CommonRequest, signer interface{}) (response *responses.CommonResponse, err error)
}
func NewRamRoleArnSigner(credential *credentials.RamRoleArnCredential, commonApi func(request *requests.CommonRequest, signer interface{}) (response *responses.CommonResponse, err error)) (signer *RamRoleArnSigner, err error) {
signer = &RamRoleArnSigner{
credential: credential,
commonApi: commonApi,
}
signer.credentialUpdater = &credentialUpdater{
credentialExpiration: credential.RoleSessionExpiration,
buildRequestMethod: signer.buildCommonRequest,
responseCallBack: signer.refreshCredential,
refreshApi: signer.refreshApi,
}
if len(credential.RoleSessionName) > 0 {
signer.roleSessionName = credential.RoleSessionName
} else {
signer.roleSessionName = "aliyun-go-sdk-" + strconv.FormatInt(time.Now().UnixNano()/1000, 10)
}
if credential.RoleSessionExpiration > 0 {
if credential.RoleSessionExpiration >= 900 && credential.RoleSessionExpiration <= 3600 {
signer.credentialExpiration = credential.RoleSessionExpiration
} else {
err = errors.NewClientError(errors.InvalidParamErrorCode, "Assume Role session duration should be in the range of 15min - 1Hr", nil)
}
} else {
signer.credentialExpiration = defaultDurationSeconds
}
return
}
func (*RamRoleArnSigner) GetName() string {
return "HMAC-SHA1"
}
func (*RamRoleArnSigner) GetType() string {
return ""
}
func (*RamRoleArnSigner) GetVersion() string {
return "1.0"
}
func (signer *RamRoleArnSigner) GetAccessKeyId() (accessKeyId string, err error) {
if signer.sessionCredential == nil || signer.needUpdateCredential() {
err = signer.updateCredential()
if err != nil {
return
}
}
if signer.sessionCredential == nil || len(signer.sessionCredential.AccessKeyId) <= 0 {
return "", err
}
return signer.sessionCredential.AccessKeyId, nil
}
func (signer *RamRoleArnSigner) GetExtraParam() map[string]string {
if signer.sessionCredential == nil || signer.needUpdateCredential() {
signer.updateCredential()
}
if signer.sessionCredential == nil || len(signer.sessionCredential.StsToken) <= 0 {
return make(map[string]string)
}
return map[string]string{"SecurityToken": signer.sessionCredential.StsToken}
}
func (signer *RamRoleArnSigner) Sign(stringToSign, secretSuffix string) string {
secret := signer.sessionCredential.AccessKeySecret + secretSuffix
return ShaHmac1(stringToSign, secret)
}
func (signer *RamRoleArnSigner) buildCommonRequest() (request *requests.CommonRequest, err error) {
request = requests.NewCommonRequest()
request.Product = "Sts"
request.Version = "2015-04-01"
request.ApiName = "AssumeRole"
request.Scheme = requests.HTTPS
request.QueryParams["RoleArn"] = signer.credential.RoleArn
if signer.credential.Policy != "" {
request.QueryParams["Policy"] = signer.credential.Policy
}
request.QueryParams["RoleSessionName"] = signer.credential.RoleSessionName
request.QueryParams["DurationSeconds"] = strconv.Itoa(signer.credentialExpiration)
return
}
func (signer *RamRoleArnSigner) refreshApi(request *requests.CommonRequest) (response *responses.CommonResponse, err error) {
credential := &credentials.AccessKeyCredential{
AccessKeyId: signer.credential.AccessKeyId,
AccessKeySecret: signer.credential.AccessKeySecret,
}
signerV1 := NewAccessKeySigner(credential)
return signer.commonApi(request, signerV1)
}
func (signer *RamRoleArnSigner) refreshCredential(response *responses.CommonResponse) (err error) {
if response.GetHttpStatus() != http.StatusOK {
message := "refresh session token failed"
err = errors.NewServerError(response.GetHttpStatus(), response.GetHttpContentString(), message)
return
}
var data interface{}
err = json.Unmarshal(response.GetHttpContentBytes(), &data)
if err != nil {
return fmt.Errorf("refresh RoleArn sts token err, json.Unmarshal fail: %s", err.Error())
}
accessKeyId, err := jmespath.Search("Credentials.AccessKeyId", data)
if err != nil {
return fmt.Errorf("refresh RoleArn sts token err, fail to get AccessKeyId: %s", err.Error())
}
accessKeySecret, err := jmespath.Search("Credentials.AccessKeySecret", data)
if err != nil {
return fmt.Errorf("refresh RoleArn sts token err, fail to get AccessKeySecret: %s", err.Error())
}
securityToken, err := jmespath.Search("Credentials.SecurityToken", data)
if err != nil {
return fmt.Errorf("refresh RoleArn sts token err, fail to get SecurityToken: %s", err.Error())
}
if accessKeyId == nil || accessKeySecret == nil || securityToken == nil {
return
}
signer.sessionCredential = &SessionCredential{
AccessKeyId: accessKeyId.(string),
AccessKeySecret: accessKeySecret.(string),
StsToken: securityToken.(string),
}
return
}
func (signer *RamRoleArnSigner) GetSessionCredential() *SessionCredential {
return signer.sessionCredential
}

View File

@ -0,0 +1,54 @@
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package signers
import (
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credentials"
)
type StsTokenSigner struct {
credential *credentials.StsTokenCredential
}
func NewStsTokenSigner(credential *credentials.StsTokenCredential) *StsTokenSigner {
return &StsTokenSigner{
credential: credential,
}
}
func (*StsTokenSigner) GetName() string {
return "HMAC-SHA1"
}
func (*StsTokenSigner) GetType() string {
return ""
}
func (*StsTokenSigner) GetVersion() string {
return "1.0"
}
func (signer *StsTokenSigner) GetAccessKeyId() (accessKeyId string, err error) {
return signer.credential.AccessKeyId, nil
}
func (signer *StsTokenSigner) GetExtraParam() map[string]string {
return map[string]string{"SecurityToken": signer.credential.AccessKeyStsToken}
}
func (signer *StsTokenSigner) Sign(stringToSign, secretSuffix string) string {
secret := signer.credential.AccessKeySecret + secretSuffix
return ShaHmac1(stringToSign, secret)
}

View File

@ -0,0 +1,54 @@
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package signers
import (
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credentials"
)
type SignerV2 struct {
credential *credentials.RsaKeyPairCredential
}
func (signer *SignerV2) GetExtraParam() map[string]string {
return nil
}
func NewSignerV2(credential *credentials.RsaKeyPairCredential) *SignerV2 {
return &SignerV2{
credential: credential,
}
}
func (*SignerV2) GetName() string {
return "SHA256withRSA"
}
func (*SignerV2) GetType() string {
return "PRIVATEKEY"
}
func (*SignerV2) GetVersion() string {
return "1.0"
}
func (signer *SignerV2) GetAccessKeyId() (accessKeyId string, err error) {
return signer.credential.PublicKeyId, err
}
func (signer *SignerV2) Sign(stringToSign, secretSuffix string) string {
secret := signer.credential.PrivateKey
return Sha256WithRsa(stringToSign, secret)
}

View File

@ -0,0 +1,823 @@
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package sdk
import (
"context"
"crypto/tls"
"fmt"
"net"
"net/http"
"net/url"
"os"
"runtime"
"strconv"
"strings"
"sync"
"time"
"regexp"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credentials"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credentials/provider"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/endpoints"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/errors"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/utils"
)
var debug utils.Debug
func init() {
debug = utils.Init("sdk")
}
// Version this value will be replaced while build: -ldflags="-X sdk.version=x.x.x"
var Version = "0.0.1"
var defaultConnectTimeout = 5 * time.Second
var defaultReadTimeout = 10 * time.Second
var DefaultUserAgent = fmt.Sprintf("AlibabaCloud (%s; %s) Golang/%s Core/%s", runtime.GOOS, runtime.GOARCH, strings.Trim(runtime.Version(), "go"), Version)
var hookDo = func(fn func(req *http.Request) (*http.Response, error)) func(req *http.Request) (*http.Response, error) {
return fn
}
// Client the type Client
type Client struct {
isInsecure bool
regionId string
config *Config
httpProxy string
httpsProxy string
noProxy string
logger *Logger
userAgent map[string]string
signer auth.Signer
httpClient *http.Client
asyncTaskQueue chan func()
readTimeout time.Duration
connectTimeout time.Duration
EndpointMap map[string]string
EndpointType string
Network string
Domain string
debug bool
isRunning bool
// void "panic(write to close channel)" cause of addAsync() after Shutdown()
asyncChanLock *sync.RWMutex
}
func (client *Client) Init() (err error) {
panic("not support yet")
}
func (client *Client) SetEndpointRules(endpointMap map[string]string, endpointType string, netWork string) {
client.EndpointMap = endpointMap
client.Network = netWork
client.EndpointType = endpointType
}
func (client *Client) SetHTTPSInsecure(isInsecure bool) {
client.isInsecure = isInsecure
}
func (client *Client) GetHTTPSInsecure() bool {
return client.isInsecure
}
func (client *Client) SetHttpsProxy(httpsProxy string) {
client.httpsProxy = httpsProxy
}
func (client *Client) GetHttpsProxy() string {
return client.httpsProxy
}
func (client *Client) SetHttpProxy(httpProxy string) {
client.httpProxy = httpProxy
}
func (client *Client) GetHttpProxy() string {
return client.httpProxy
}
func (client *Client) SetNoProxy(noProxy string) {
client.noProxy = noProxy
}
func (client *Client) GetNoProxy() string {
return client.noProxy
}
func (client *Client) SetTransport(transport http.RoundTripper) {
if client.httpClient == nil {
client.httpClient = &http.Client{}
}
client.httpClient.Transport = transport
}
// InitWithProviderChain will get credential from the providerChain,
// the RsaKeyPairCredential Only applicable to regionID `ap-northeast-1`,
// if your providerChain may return a credential type with RsaKeyPairCredential,
// please ensure your regionID is `ap-northeast-1`.
func (client *Client) InitWithProviderChain(regionId string, provider provider.Provider) (err error) {
config := client.InitClientConfig()
credential, err := provider.Resolve()
if err != nil {
return
}
return client.InitWithOptions(regionId, config, credential)
}
func (client *Client) InitWithOptions(regionId string, config *Config, credential auth.Credential) (err error) {
client.isRunning = true
client.asyncChanLock = new(sync.RWMutex)
client.regionId = regionId
client.config = config
client.httpClient = &http.Client{}
if config.Transport != nil {
client.httpClient.Transport = config.Transport
} else if config.HttpTransport != nil {
client.httpClient.Transport = config.HttpTransport
}
if config.Timeout > 0 {
client.httpClient.Timeout = config.Timeout
}
if config.EnableAsync {
client.EnableAsync(config.GoRoutinePoolSize, config.MaxTaskQueueSize)
}
client.signer, err = auth.NewSignerWithCredential(credential, client.ProcessCommonRequestWithSigner)
return
}
func (client *Client) SetReadTimeout(readTimeout time.Duration) {
client.readTimeout = readTimeout
}
func (client *Client) SetConnectTimeout(connectTimeout time.Duration) {
client.connectTimeout = connectTimeout
}
func (client *Client) GetReadTimeout() time.Duration {
return client.readTimeout
}
func (client *Client) GetConnectTimeout() time.Duration {
return client.connectTimeout
}
func (client *Client) getHttpProxy(scheme string) (proxy *url.URL, err error) {
if scheme == "https" {
if client.GetHttpsProxy() != "" {
proxy, err = url.Parse(client.httpsProxy)
} else if rawurl := os.Getenv("HTTPS_PROXY"); rawurl != "" {
proxy, err = url.Parse(rawurl)
} else if rawurl := os.Getenv("https_proxy"); rawurl != "" {
proxy, err = url.Parse(rawurl)
}
} else {
if client.GetHttpProxy() != "" {
proxy, err = url.Parse(client.httpProxy)
} else if rawurl := os.Getenv("HTTP_PROXY"); rawurl != "" {
proxy, err = url.Parse(rawurl)
} else if rawurl := os.Getenv("http_proxy"); rawurl != "" {
proxy, err = url.Parse(rawurl)
}
}
return proxy, err
}
func (client *Client) getNoProxy(scheme string) []string {
var urls []string
if client.GetNoProxy() != "" {
urls = strings.Split(client.noProxy, ",")
} else if rawurl := os.Getenv("NO_PROXY"); rawurl != "" {
urls = strings.Split(rawurl, ",")
} else if rawurl := os.Getenv("no_proxy"); rawurl != "" {
urls = strings.Split(rawurl, ",")
}
return urls
}
// EnableAsync enable the async task queue
func (client *Client) EnableAsync(routinePoolSize, maxTaskQueueSize int) {
client.asyncTaskQueue = make(chan func(), maxTaskQueueSize)
for i := 0; i < routinePoolSize; i++ {
go func() {
for client.isRunning {
select {
case task, notClosed := <-client.asyncTaskQueue:
if notClosed {
task()
}
}
}
}()
}
}
func (client *Client) InitWithAccessKey(regionId, accessKeyId, accessKeySecret string) (err error) {
config := client.InitClientConfig()
credential := &credentials.BaseCredential{
AccessKeyId: accessKeyId,
AccessKeySecret: accessKeySecret,
}
return client.InitWithOptions(regionId, config, credential)
}
func (client *Client) InitWithStsToken(regionId, accessKeyId, accessKeySecret, securityToken string) (err error) {
config := client.InitClientConfig()
credential := &credentials.StsTokenCredential{
AccessKeyId: accessKeyId,
AccessKeySecret: accessKeySecret,
AccessKeyStsToken: securityToken,
}
return client.InitWithOptions(regionId, config, credential)
}
func (client *Client) InitWithRamRoleArn(regionId, accessKeyId, accessKeySecret, roleArn, roleSessionName string) (err error) {
config := client.InitClientConfig()
credential := &credentials.RamRoleArnCredential{
AccessKeyId: accessKeyId,
AccessKeySecret: accessKeySecret,
RoleArn: roleArn,
RoleSessionName: roleSessionName,
}
return client.InitWithOptions(regionId, config, credential)
}
func (client *Client) InitWithRamRoleArnAndPolicy(regionId, accessKeyId, accessKeySecret, roleArn, roleSessionName, policy string) (err error) {
config := client.InitClientConfig()
credential := &credentials.RamRoleArnCredential{
AccessKeyId: accessKeyId,
AccessKeySecret: accessKeySecret,
RoleArn: roleArn,
RoleSessionName: roleSessionName,
Policy: policy,
}
return client.InitWithOptions(regionId, config, credential)
}
func (client *Client) InitWithRsaKeyPair(regionId, publicKeyId, privateKey string, sessionExpiration int) (err error) {
config := client.InitClientConfig()
credential := &credentials.RsaKeyPairCredential{
PrivateKey: privateKey,
PublicKeyId: publicKeyId,
SessionExpiration: sessionExpiration,
}
return client.InitWithOptions(regionId, config, credential)
}
func (client *Client) InitWithEcsRamRole(regionId, roleName string) (err error) {
config := client.InitClientConfig()
credential := &credentials.EcsRamRoleCredential{
RoleName: roleName,
}
return client.InitWithOptions(regionId, config, credential)
}
func (client *Client) InitWithBearerToken(regionId, bearerToken string) (err error) {
config := client.InitClientConfig()
credential := &credentials.BearerTokenCredential{
BearerToken: bearerToken,
}
return client.InitWithOptions(regionId, config, credential)
}
func (client *Client) InitClientConfig() (config *Config) {
if client.config != nil {
return client.config
} else {
return NewConfig()
}
}
func (client *Client) DoAction(request requests.AcsRequest, response responses.AcsResponse) (err error) {
return client.DoActionWithSigner(request, response, nil)
}
func (client *Client) GetEndpointRules(regionId string, product string) (endpointRaw string, err error) {
if client.EndpointType == "regional" {
if regionId == "" {
err = fmt.Errorf("RegionId is empty, please set a valid RegionId.")
return "", err
}
endpointRaw = strings.Replace("<product><network>.<region_id>.aliyuncs.com", "<region_id>", regionId, 1)
} else {
endpointRaw = "<product><network>.aliyuncs.com"
}
endpointRaw = strings.Replace(endpointRaw, "<product>", strings.ToLower(product), 1)
if client.Network == "" || client.Network == "public" {
endpointRaw = strings.Replace(endpointRaw, "<network>", "", 1)
} else {
endpointRaw = strings.Replace(endpointRaw, "<network>", "-"+client.Network, 1)
}
return endpointRaw, nil
}
func (client *Client) buildRequestWithSigner(request requests.AcsRequest, signer auth.Signer) (httpRequest *http.Request, err error) {
// add clientVersion
request.GetHeaders()["x-sdk-core-version"] = Version
regionId := client.regionId
if len(request.GetRegionId()) > 0 {
regionId = request.GetRegionId()
}
// resolve endpoint
endpoint := request.GetDomain()
if endpoint == "" && client.Domain != "" {
endpoint = client.Domain
}
if endpoint == "" {
endpoint = endpoints.GetEndpointFromMap(regionId, request.GetProduct())
}
if endpoint == "" && client.EndpointType != "" && request.GetProduct() != "Sts" {
if client.EndpointMap != nil && client.Network == "" || client.Network == "public" {
endpoint = client.EndpointMap[regionId]
}
if endpoint == "" {
endpoint, err = client.GetEndpointRules(regionId, request.GetProduct())
if err != nil {
return
}
}
}
if endpoint == "" {
resolveParam := &endpoints.ResolveParam{
Domain: request.GetDomain(),
Product: request.GetProduct(),
RegionId: regionId,
LocationProduct: request.GetLocationServiceCode(),
LocationEndpointType: request.GetLocationEndpointType(),
CommonApi: client.ProcessCommonRequest,
}
endpoint, err = endpoints.Resolve(resolveParam)
if err != nil {
return
}
}
request.SetDomain(endpoint)
if request.GetScheme() == "" {
request.SetScheme(client.config.Scheme)
}
// init request params
err = requests.InitParams(request)
if err != nil {
return
}
// signature
var finalSigner auth.Signer
if signer != nil {
finalSigner = signer
} else {
finalSigner = client.signer
}
httpRequest, err = buildHttpRequest(request, finalSigner, regionId)
if err == nil {
userAgent := DefaultUserAgent + getSendUserAgent(client.config.UserAgent, client.userAgent, request.GetUserAgent())
httpRequest.Header.Set("User-Agent", userAgent)
}
return
}
func getSendUserAgent(configUserAgent string, clientUserAgent, requestUserAgent map[string]string) string {
realUserAgent := ""
for key1, value1 := range clientUserAgent {
for key2, _ := range requestUserAgent {
if key1 == key2 {
key1 = ""
}
}
if key1 != "" {
realUserAgent += fmt.Sprintf(" %s/%s", key1, value1)
}
}
for key, value := range requestUserAgent {
realUserAgent += fmt.Sprintf(" %s/%s", key, value)
}
if configUserAgent != "" {
return realUserAgent + fmt.Sprintf(" Extra/%s", configUserAgent)
}
return realUserAgent
}
func (client *Client) AppendUserAgent(key, value string) {
newkey := true
if client.userAgent == nil {
client.userAgent = make(map[string]string)
}
if strings.ToLower(key) != "core" && strings.ToLower(key) != "go" {
for tag, _ := range client.userAgent {
if tag == key {
client.userAgent[tag] = value
newkey = false
}
}
if newkey {
client.userAgent[key] = value
}
}
}
func (client *Client) BuildRequestWithSigner(request requests.AcsRequest, signer auth.Signer) (err error) {
_, err = client.buildRequestWithSigner(request, signer)
return
}
func (client *Client) getTimeout(request requests.AcsRequest) (time.Duration, time.Duration) {
readTimeout := defaultReadTimeout
connectTimeout := defaultConnectTimeout
reqReadTimeout := request.GetReadTimeout()
reqConnectTimeout := request.GetConnectTimeout()
if reqReadTimeout != 0*time.Millisecond {
readTimeout = reqReadTimeout
} else if client.readTimeout != 0*time.Millisecond {
readTimeout = client.readTimeout
} else if client.httpClient.Timeout != 0 {
readTimeout = client.httpClient.Timeout
} else if timeout, ok := getAPIMaxTimeout(request.GetProduct(), request.GetActionName()); ok {
readTimeout = timeout
}
if reqConnectTimeout != 0*time.Millisecond {
connectTimeout = reqConnectTimeout
} else if client.connectTimeout != 0*time.Millisecond {
connectTimeout = client.connectTimeout
}
return readTimeout, connectTimeout
}
func Timeout(connectTimeout time.Duration) func(cxt context.Context, net, addr string) (c net.Conn, err error) {
return func(ctx context.Context, network, address string) (net.Conn, error) {
return (&net.Dialer{
Timeout: connectTimeout,
DualStack: true,
}).DialContext(ctx, network, address)
}
}
func (client *Client) setTimeout(request requests.AcsRequest) {
readTimeout, connectTimeout := client.getTimeout(request)
client.httpClient.Timeout = readTimeout
if trans, ok := client.httpClient.Transport.(*http.Transport); ok && trans != nil {
trans.DialContext = Timeout(connectTimeout)
client.httpClient.Transport = trans
} else if client.httpClient.Transport == nil {
client.httpClient.Transport = &http.Transport{
DialContext: Timeout(connectTimeout),
}
}
}
func (client *Client) getHTTPSInsecure(request requests.AcsRequest) (insecure bool) {
if request.GetHTTPSInsecure() != nil {
insecure = *request.GetHTTPSInsecure()
} else {
insecure = client.GetHTTPSInsecure()
}
return insecure
}
func (client *Client) DoActionWithSigner(request requests.AcsRequest, response responses.AcsResponse, signer auth.Signer) (err error) {
fieldMap := make(map[string]string)
initLogMsg(fieldMap)
defer func() {
client.printLog(fieldMap, err)
}()
httpRequest, err := client.buildRequestWithSigner(request, signer)
if err != nil {
return
}
client.setTimeout(request)
proxy, err := client.getHttpProxy(httpRequest.URL.Scheme)
if err != nil {
return err
}
noProxy := client.getNoProxy(httpRequest.URL.Scheme)
var flag bool
for _, value := range noProxy {
if strings.HasPrefix(value, "*") {
value = fmt.Sprintf(".%s", value)
}
noProxyReg, err := regexp.Compile(value)
if err != nil {
return err
}
if noProxyReg.MatchString(httpRequest.Host){
flag = true
break
}
}
// Set whether to ignore certificate validation.
// Default InsecureSkipVerify is false.
if trans, ok := client.httpClient.Transport.(*http.Transport); ok && trans != nil {
if trans.TLSClientConfig != nil {
trans.TLSClientConfig.InsecureSkipVerify = client.getHTTPSInsecure(request)
} else {
trans.TLSClientConfig = &tls.Config{
InsecureSkipVerify: client.getHTTPSInsecure(request),
}
}
if proxy != nil && !flag {
trans.Proxy = http.ProxyURL(proxy)
}
client.httpClient.Transport = trans
}
var httpResponse *http.Response
for retryTimes := 0; retryTimes <= client.config.MaxRetryTime; retryTimes++ {
if proxy != nil && proxy.User != nil {
if password, passwordSet := proxy.User.Password(); passwordSet {
httpRequest.SetBasicAuth(proxy.User.Username(), password)
}
}
if retryTimes > 0 {
client.printLog(fieldMap, err)
initLogMsg(fieldMap)
}
putMsgToMap(fieldMap, httpRequest)
debug("> %s %s %s", httpRequest.Method, httpRequest.URL.RequestURI(), httpRequest.Proto)
debug("> Host: %s", httpRequest.Host)
for key, value := range httpRequest.Header {
debug("> %s: %v", key, strings.Join(value, ""))
}
debug(">")
debug(" Retry Times: %d.", retryTimes)
startTime := time.Now()
fieldMap["{start_time}"] = startTime.Format("2006-01-02 15:04:05")
httpResponse, err = hookDo(client.httpClient.Do)(httpRequest)
fieldMap["{cost}"] = time.Now().Sub(startTime).String()
if err == nil {
fieldMap["{code}"] = strconv.Itoa(httpResponse.StatusCode)
fieldMap["{res_headers}"] = TransToString(httpResponse.Header)
debug("< %s %s", httpResponse.Proto, httpResponse.Status)
for key, value := range httpResponse.Header {
debug("< %s: %v", key, strings.Join(value, ""))
}
}
debug("<")
// receive error
if err != nil {
debug(" Error: %s.", err.Error())
if !client.config.AutoRetry {
return
} else if retryTimes >= client.config.MaxRetryTime {
// timeout but reached the max retry times, return
times := strconv.Itoa(retryTimes + 1)
timeoutErrorMsg := fmt.Sprintf(errors.TimeoutErrorMessage, times, times)
if strings.Contains(err.Error(), "Client.Timeout") {
timeoutErrorMsg += " Read timeout. Please set a valid ReadTimeout."
} else {
timeoutErrorMsg += " Connect timeout. Please set a valid ConnectTimeout."
}
err = errors.NewClientError(errors.TimeoutErrorCode, timeoutErrorMsg, err)
return
}
}
if isCertificateError(err) {
return
}
// if status code >= 500 or timeout, will trigger retry
if client.config.AutoRetry && (err != nil || isServerError(httpResponse)) {
client.setTimeout(request)
// rewrite signatureNonce and signature
httpRequest, err = client.buildRequestWithSigner(request, signer)
// buildHttpRequest(request, finalSigner, regionId)
if err != nil {
return
}
continue
}
break
}
err = responses.Unmarshal(response, httpResponse, request.GetAcceptFormat())
fieldMap["{res_body}"] = response.GetHttpContentString()
debug("%s", response.GetHttpContentString())
// wrap server errors
if serverErr, ok := err.(*errors.ServerError); ok {
var wrapInfo = map[string]string{}
wrapInfo["StringToSign"] = request.GetStringToSign()
err = errors.WrapServerError(serverErr, wrapInfo)
}
return
}
func isCertificateError(err error) bool {
if err != nil && strings.Contains(err.Error(), "x509: certificate signed by unknown authority") {
return true
}
return false
}
func putMsgToMap(fieldMap map[string]string, request *http.Request) {
fieldMap["{host}"] = request.Host
fieldMap["{method}"] = request.Method
fieldMap["{uri}"] = request.URL.RequestURI()
fieldMap["{pid}"] = strconv.Itoa(os.Getpid())
fieldMap["{version}"] = strings.Split(request.Proto, "/")[1]
hostname, _ := os.Hostname()
fieldMap["{hostname}"] = hostname
fieldMap["{req_headers}"] = TransToString(request.Header)
fieldMap["{target}"] = request.URL.Path + request.URL.RawQuery
}
func buildHttpRequest(request requests.AcsRequest, singer auth.Signer, regionId string) (httpRequest *http.Request, err error) {
err = auth.Sign(request, singer, regionId)
if err != nil {
return
}
requestMethod := request.GetMethod()
requestUrl := request.BuildUrl()
body := request.GetBodyReader()
httpRequest, err = http.NewRequest(requestMethod, requestUrl, body)
if err != nil {
return
}
for key, value := range request.GetHeaders() {
httpRequest.Header[key] = []string{value}
}
// host is a special case
if host, containsHost := request.GetHeaders()["Host"]; containsHost {
httpRequest.Host = host
}
return
}
func isServerError(httpResponse *http.Response) bool {
return httpResponse.StatusCode >= http.StatusInternalServerError
}
/**
only block when any one of the following occurs:
1. the asyncTaskQueue is full, increase the queue size to avoid this
2. Shutdown() in progressing, the client is being closed
**/
func (client *Client) AddAsyncTask(task func()) (err error) {
if client.asyncTaskQueue != nil {
client.asyncChanLock.RLock()
defer client.asyncChanLock.RUnlock()
if client.isRunning {
client.asyncTaskQueue <- task
}
} else {
err = errors.NewClientError(errors.AsyncFunctionNotEnabledCode, errors.AsyncFunctionNotEnabledMessage, nil)
}
return
}
func (client *Client) GetConfig() *Config {
return client.config
}
func (client *Client) GetSigner() auth.Signer {
return client.signer
}
func (client *Client) SetSigner(signer auth.Signer) {
client.signer = signer
}
func NewClient() (client *Client, err error) {
client = &Client{}
err = client.Init()
return
}
func NewClientWithProvider(regionId string, providers ...provider.Provider) (client *Client, err error) {
client = &Client{}
var pc provider.Provider
if len(providers) == 0 {
pc = provider.DefaultChain
} else {
pc = provider.NewProviderChain(providers)
}
err = client.InitWithProviderChain(regionId, pc)
return
}
func NewClientWithOptions(regionId string, config *Config, credential auth.Credential) (client *Client, err error) {
client = &Client{}
err = client.InitWithOptions(regionId, config, credential)
return
}
func NewClientWithAccessKey(regionId, accessKeyId, accessKeySecret string) (client *Client, err error) {
client = &Client{}
err = client.InitWithAccessKey(regionId, accessKeyId, accessKeySecret)
return
}
func NewClientWithStsToken(regionId, stsAccessKeyId, stsAccessKeySecret, stsToken string) (client *Client, err error) {
client = &Client{}
err = client.InitWithStsToken(regionId, stsAccessKeyId, stsAccessKeySecret, stsToken)
return
}
func NewClientWithRamRoleArn(regionId string, accessKeyId, accessKeySecret, roleArn, roleSessionName string) (client *Client, err error) {
client = &Client{}
err = client.InitWithRamRoleArn(regionId, accessKeyId, accessKeySecret, roleArn, roleSessionName)
return
}
func NewClientWithRamRoleArnAndPolicy(regionId string, accessKeyId, accessKeySecret, roleArn, roleSessionName, policy string) (client *Client, err error) {
client = &Client{}
err = client.InitWithRamRoleArnAndPolicy(regionId, accessKeyId, accessKeySecret, roleArn, roleSessionName, policy)
return
}
func NewClientWithEcsRamRole(regionId string, roleName string) (client *Client, err error) {
client = &Client{}
err = client.InitWithEcsRamRole(regionId, roleName)
return
}
func NewClientWithRsaKeyPair(regionId string, publicKeyId, privateKey string, sessionExpiration int) (client *Client, err error) {
client = &Client{}
err = client.InitWithRsaKeyPair(regionId, publicKeyId, privateKey, sessionExpiration)
return
}
func NewClientWithBearerToken(regionId, bearerToken string) (client *Client, err error) {
client = &Client{}
err = client.InitWithBearerToken(regionId, bearerToken)
return
}
func (client *Client) ProcessCommonRequest(request *requests.CommonRequest) (response *responses.CommonResponse, err error) {
request.TransToAcsRequest()
response = responses.NewCommonResponse()
err = client.DoAction(request, response)
return
}
func (client *Client) ProcessCommonRequestWithSigner(request *requests.CommonRequest, signerInterface interface{}) (response *responses.CommonResponse, err error) {
if signer, isSigner := signerInterface.(auth.Signer); isSigner {
request.TransToAcsRequest()
response = responses.NewCommonResponse()
err = client.DoActionWithSigner(request, response, signer)
return
}
panic("should not be here")
}
func (client *Client) Shutdown() {
// lock the addAsync()
client.asyncChanLock.Lock()
defer client.asyncChanLock.Unlock()
if client.asyncTaskQueue != nil {
close(client.asyncTaskQueue)
}
client.isRunning = false
}
// Deprecated: Use NewClientWithRamRoleArn in this package instead.
func NewClientWithStsRoleArn(regionId string, accessKeyId, accessKeySecret, roleArn, roleSessionName string) (client *Client, err error) {
return NewClientWithRamRoleArn(regionId, accessKeyId, accessKeySecret, roleArn, roleSessionName)
}
// Deprecated: Use NewClientWithEcsRamRole in this package instead.
func NewClientWithStsRoleNameOnEcs(regionId string, roleName string) (client *Client, err error) {
return NewClientWithEcsRamRole(regionId, roleName)
}

View File

@ -0,0 +1,92 @@
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package sdk
import (
"net/http"
"time"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/utils"
)
type Config struct {
AutoRetry bool `default:"true"`
MaxRetryTime int `default:"3"`
UserAgent string `default:""`
Debug bool `default:"false"`
HttpTransport *http.Transport `default:""`
Transport http.RoundTripper `default:""`
EnableAsync bool `default:"false"`
MaxTaskQueueSize int `default:"1000"`
GoRoutinePoolSize int `default:"5"`
Scheme string `default:"HTTP"`
Timeout time.Duration
}
func NewConfig() (config *Config) {
config = &Config{}
utils.InitStructWithDefaultTag(config)
return
}
func (c *Config) WithAutoRetry(isAutoRetry bool) *Config {
c.AutoRetry = isAutoRetry
return c
}
func (c *Config) WithMaxRetryTime(maxRetryTime int) *Config {
c.MaxRetryTime = maxRetryTime
return c
}
func (c *Config) WithUserAgent(userAgent string) *Config {
c.UserAgent = userAgent
return c
}
func (c *Config) WithDebug(isDebug bool) *Config {
c.Debug = isDebug
return c
}
func (c *Config) WithTimeout(timeout time.Duration) *Config {
c.Timeout = timeout
return c
}
func (c *Config) WithHttpTransport(httpTransport *http.Transport) *Config {
c.HttpTransport = httpTransport
return c
}
func (c *Config) WithEnableAsync(isEnableAsync bool) *Config {
c.EnableAsync = isEnableAsync
return c
}
func (c *Config) WithMaxTaskQueueSize(maxTaskQueueSize int) *Config {
c.MaxTaskQueueSize = maxTaskQueueSize
return c
}
func (c *Config) WithGoRoutinePoolSize(goRoutinePoolSize int) *Config {
c.GoRoutinePoolSize = goRoutinePoolSize
return c
}
func (c *Config) WithScheme(scheme string) *Config {
c.Scheme = scheme
return c
}

View File

@ -0,0 +1,23 @@
load("@io_bazel_rules_go//go:def.bzl", "go_library")
go_library(
name = "go_default_library",
srcs = [
"endpoints_config.go",
"local_global_resolver.go",
"local_regional_resolver.go",
"location_resolver.go",
"mapping_resolver.go",
"resolver.go",
],
importmap = "k8s.io/kops/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/endpoints",
importpath = "github.com/aliyun/alibaba-cloud-sdk-go/sdk/endpoints",
visibility = ["//visibility:public"],
deps = [
"//vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/errors:go_default_library",
"//vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests:go_default_library",
"//vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses:go_default_library",
"//vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/utils:go_default_library",
"//vendor/github.com/jmespath/go-jmespath:go_default_library",
],
)

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,43 @@
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package endpoints
import (
"fmt"
"strings"
"github.com/jmespath/go-jmespath"
)
type LocalGlobalResolver struct {
}
func (resolver *LocalGlobalResolver) GetName() (name string) {
name = "local global resolver"
return
}
func (resolver *LocalGlobalResolver) TryResolve(param *ResolveParam) (endpoint string, support bool, err error) {
// get the global endpoints configs
endpointExpression := fmt.Sprintf("products[?code=='%s'].global_endpoint", strings.ToLower(param.Product))
endpointData, err := jmespath.Search(endpointExpression, getEndpointConfigData())
if err == nil && endpointData != nil && len(endpointData.([]interface{})) > 0 {
endpoint = endpointData.([]interface{})[0].(string)
support = len(endpoint) > 0
return
}
support = false
return
}

View File

@ -0,0 +1,48 @@
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package endpoints
import (
"fmt"
"strings"
"github.com/jmespath/go-jmespath"
)
type LocalRegionalResolver struct {
}
func (resolver *LocalRegionalResolver) GetName() (name string) {
name = "local regional resolver"
return
}
func (resolver *LocalRegionalResolver) TryResolve(param *ResolveParam) (endpoint string, support bool, err error) {
// get the regional endpoints configs
regionalExpression := fmt.Sprintf("products[?code=='%s'].regional_endpoints", strings.ToLower(param.Product))
regionalData, err := jmespath.Search(regionalExpression, getEndpointConfigData())
if err == nil && regionalData != nil && len(regionalData.([]interface{})) > 0 {
endpointExpression := fmt.Sprintf("[0][?region=='%s'].endpoint", strings.ToLower(param.RegionId))
var endpointData interface{}
endpointData, err = jmespath.Search(endpointExpression, regionalData)
if err == nil && endpointData != nil && len(endpointData.([]interface{})) > 0 {
endpoint = endpointData.([]interface{})[0].(string)
support = len(endpoint) > 0
return
}
}
support = false
return
}

View File

@ -0,0 +1,176 @@
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package endpoints
import (
"encoding/json"
"sync"
"time"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
)
const (
// EndpointCacheExpireTime ...
EndpointCacheExpireTime = 3600 //Seconds
)
// Cache caches endpoint for specific product and region
type Cache struct {
sync.RWMutex
cache map[string]interface{}
}
// Get ...
func (c *Cache) Get(k string) (v interface{}) {
c.RLock()
v = c.cache[k]
c.RUnlock()
return
}
// Set ...
func (c *Cache) Set(k string, v interface{}) {
c.Lock()
c.cache[k] = v
c.Unlock()
}
var lastClearTimePerProduct = &Cache{cache: make(map[string]interface{})}
var endpointCache = &Cache{cache: make(map[string]interface{})}
// LocationResolver ...
type LocationResolver struct {
}
func (resolver *LocationResolver) GetName() (name string) {
name = "location resolver"
return
}
// TryResolve resolves endpoint giving product and region
func (resolver *LocationResolver) TryResolve(param *ResolveParam) (endpoint string, support bool, err error) {
if len(param.LocationProduct) <= 0 {
support = false
return
}
//get from cache
cacheKey := param.Product + "#" + param.RegionId
var ok bool
endpoint, ok = endpointCache.Get(cacheKey).(string)
if ok && len(endpoint) > 0 && !CheckCacheIsExpire(cacheKey) {
support = true
return
}
//get from remote
getEndpointRequest := requests.NewCommonRequest()
getEndpointRequest.Product = "Location"
getEndpointRequest.Version = "2015-06-12"
getEndpointRequest.ApiName = "DescribeEndpoints"
getEndpointRequest.Domain = "location-readonly.aliyuncs.com"
getEndpointRequest.Method = "GET"
getEndpointRequest.Scheme = requests.HTTPS
getEndpointRequest.QueryParams["Id"] = param.RegionId
getEndpointRequest.QueryParams["ServiceCode"] = param.LocationProduct
if len(param.LocationEndpointType) > 0 {
getEndpointRequest.QueryParams["Type"] = param.LocationEndpointType
} else {
getEndpointRequest.QueryParams["Type"] = "openAPI"
}
response, err := param.CommonApi(getEndpointRequest)
if err != nil {
support = false
return
}
if !response.IsSuccess() {
support = false
return
}
var getEndpointResponse GetEndpointResponse
err = json.Unmarshal([]byte(response.GetHttpContentString()), &getEndpointResponse)
if err != nil {
support = false
return
}
if !getEndpointResponse.Success || getEndpointResponse.Endpoints == nil {
support = false
return
}
if len(getEndpointResponse.Endpoints.Endpoint) <= 0 {
support = false
return
}
if len(getEndpointResponse.Endpoints.Endpoint[0].Endpoint) > 0 {
endpoint = getEndpointResponse.Endpoints.Endpoint[0].Endpoint
endpointCache.Set(cacheKey, endpoint)
lastClearTimePerProduct.Set(cacheKey, time.Now().Unix())
support = true
return
}
support = false
return
}
// CheckCacheIsExpire ...
func CheckCacheIsExpire(cacheKey string) bool {
lastClearTime, ok := lastClearTimePerProduct.Get(cacheKey).(int64)
if !ok {
return true
}
if lastClearTime <= 0 {
lastClearTime = time.Now().Unix()
lastClearTimePerProduct.Set(cacheKey, lastClearTime)
}
now := time.Now().Unix()
elapsedTime := now - lastClearTime
if elapsedTime > EndpointCacheExpireTime {
return true
}
return false
}
// GetEndpointResponse ...
type GetEndpointResponse struct {
Endpoints *EndpointsObj
RequestId string
Success bool
}
// EndpointsObj ...
type EndpointsObj struct {
Endpoint []EndpointObj
}
// EndpointObj ...
type EndpointObj struct {
// Protocols map[string]string
Type string
Namespace string
Id string
SerivceCode string
Endpoint string
}

View File

@ -0,0 +1,49 @@
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package endpoints
import (
"fmt"
"strings"
"sync"
)
const keyFormatter = "%s::%s"
type EndpointMapping struct {
sync.RWMutex
endpoint map[string]string
}
var endpointMapping = EndpointMapping{endpoint: make(map[string]string)}
// AddEndpointMapping use productId and regionId as key to store the endpoint into inner map
// when using the same productId and regionId as key, the endpoint will be covered.
func AddEndpointMapping(regionId, productId, endpoint string) (err error) {
key := fmt.Sprintf(keyFormatter, strings.ToLower(regionId), strings.ToLower(productId))
endpointMapping.Lock()
endpointMapping.endpoint[key] = endpoint
endpointMapping.Unlock()
return nil
}
// GetEndpointFromMap use Product and RegionId as key to find endpoint from inner map
func GetEndpointFromMap(regionId, productId string) string {
key := fmt.Sprintf(keyFormatter, strings.ToLower(regionId), strings.ToLower(productId))
endpointMapping.RLock()
endpoint := endpointMapping.endpoint[key]
endpointMapping.RUnlock()
return endpoint
}

View File

@ -0,0 +1,96 @@
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package endpoints
import (
"encoding/json"
"fmt"
"sync"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/errors"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/utils"
)
var debug utils.Debug
func init() {
debug = utils.Init("sdk")
}
const (
ResolveEndpointUserGuideLink = ""
)
var once sync.Once
var resolvers []Resolver
type Resolver interface {
TryResolve(param *ResolveParam) (endpoint string, support bool, err error)
GetName() (name string)
}
// Resolve resolve endpoint with params
// It will resolve with each supported resolver until anyone resolved
func Resolve(param *ResolveParam) (endpoint string, err error) {
supportedResolvers := getAllResolvers()
var lastErr error
for _, resolver := range supportedResolvers {
endpoint, supported, resolveErr := resolver.TryResolve(param)
if resolveErr != nil {
lastErr = resolveErr
}
if supported {
debug("resolve endpoint with %s\n", param)
debug("\t%s by resolver(%s)\n", endpoint, resolver.GetName())
return endpoint, nil
}
}
// not support
errorMsg := fmt.Sprintf(errors.CanNotResolveEndpointErrorMessage, param, ResolveEndpointUserGuideLink)
err = errors.NewClientError(errors.CanNotResolveEndpointErrorCode, errorMsg, lastErr)
return
}
func getAllResolvers() []Resolver {
once.Do(func() {
resolvers = []Resolver{
&LocationResolver{},
&LocalRegionalResolver{},
&LocalGlobalResolver{},
}
})
return resolvers
}
type ResolveParam struct {
Domain string
Product string
RegionId string
LocationProduct string
LocationEndpointType string
CommonApi func(request *requests.CommonRequest) (response *responses.CommonResponse, err error) `json:"-"`
}
func (param *ResolveParam) String() string {
jsonBytes, err := json.Marshal(param)
if err != nil {
return fmt.Sprint("ResolveParam.String() process error:", err)
}
return string(jsonBytes)
}

View File

@ -0,0 +1,18 @@
load("@io_bazel_rules_go//go:def.bzl", "go_library")
go_library(
name = "go_default_library",
srcs = [
"client_error.go",
"error.go",
"server_error.go",
"signature_does_not_match_wrapper.go",
],
importmap = "k8s.io/kops/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/errors",
importpath = "github.com/aliyun/alibaba-cloud-sdk-go/sdk/errors",
visibility = ["//visibility:public"],
deps = [
"//vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/utils:go_default_library",
"//vendor/github.com/jmespath/go-jmespath:go_default_library",
],
)

View File

@ -0,0 +1,92 @@
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package errors
import "fmt"
const (
DefaultClientErrorStatus = 400
DefaultClientErrorCode = "SDK.ClientError"
UnsupportedCredentialErrorCode = "SDK.UnsupportedCredential"
UnsupportedCredentialErrorMessage = "Specified credential (type = %s) is not supported, please check"
CanNotResolveEndpointErrorCode = "SDK.CanNotResolveEndpoint"
CanNotResolveEndpointErrorMessage = "Can not resolve endpoint(param = %s), please check your accessKey with secret, and read the user guide\n %s"
UnsupportedParamPositionErrorCode = "SDK.UnsupportedParamPosition"
UnsupportedParamPositionErrorMessage = "Specified param position (%s) is not supported, please upgrade sdk and retry"
AsyncFunctionNotEnabledCode = "SDK.AsyncFunctionNotEnabled"
AsyncFunctionNotEnabledMessage = "Async function is not enabled in client, please invoke 'client.EnableAsync' function"
UnknownRequestTypeErrorCode = "SDK.UnknownRequestType"
UnknownRequestTypeErrorMessage = "Unknown Request Type: %s"
MissingParamErrorCode = "SDK.MissingParam"
InvalidParamErrorCode = "SDK.InvalidParam"
JsonUnmarshalErrorCode = "SDK.JsonUnmarshalError"
JsonUnmarshalErrorMessage = "Failed to unmarshal response, but you can get the data via response.GetHttpStatusCode() and response.GetHttpContentString()"
TimeoutErrorCode = "SDK.TimeoutError"
TimeoutErrorMessage = "The request timed out %s times(%s for retry), perhaps we should have the threshold raised a little?"
)
type ClientError struct {
errorCode string
message string
originError error
}
func NewClientError(errorCode, message string, originErr error) Error {
return &ClientError{
errorCode: errorCode,
message: message,
originError: originErr,
}
}
func (err *ClientError) Error() string {
clientErrMsg := fmt.Sprintf("[%s] %s", err.ErrorCode(), err.message)
if err.originError != nil {
return clientErrMsg + "\ncaused by:\n" + err.originError.Error()
}
return clientErrMsg
}
func (err *ClientError) OriginError() error {
return err.originError
}
func (*ClientError) HttpStatus() int {
return DefaultClientErrorStatus
}
func (err *ClientError) ErrorCode() string {
if err.errorCode == "" {
return DefaultClientErrorCode
} else {
return err.errorCode
}
}
func (err *ClientError) Message() string {
return err.message
}
func (err *ClientError) String() string {
return err.Error()
}

View File

@ -0,0 +1,23 @@
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package errors
type Error interface {
error
HttpStatus() int
ErrorCode() string
Message() string
OriginError() error
}

View File

@ -0,0 +1,123 @@
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package errors
import (
"encoding/json"
"fmt"
"github.com/jmespath/go-jmespath"
)
var wrapperList = []ServerErrorWrapper{
&SignatureDostNotMatchWrapper{},
}
type ServerError struct {
httpStatus int
requestId string
hostId string
errorCode string
recommend string
message string
comment string
}
type ServerErrorWrapper interface {
tryWrap(error *ServerError, wrapInfo map[string]string) bool
}
func (err *ServerError) Error() string {
return fmt.Sprintf("SDK.ServerError\nErrorCode: %s\nRecommend: %s\nRequestId: %s\nMessage: %s",
err.errorCode, err.comment+err.recommend, err.requestId, err.message)
}
func NewServerError(httpStatus int, responseContent, comment string) Error {
result := &ServerError{
httpStatus: httpStatus,
message: responseContent,
comment: comment,
}
var data interface{}
err := json.Unmarshal([]byte(responseContent), &data)
if err == nil {
requestId, _ := jmespath.Search("RequestId", data)
hostId, _ := jmespath.Search("HostId", data)
errorCode, _ := jmespath.Search("Code", data)
recommend, _ := jmespath.Search("Recommend", data)
message, _ := jmespath.Search("Message", data)
if requestId != nil {
result.requestId = requestId.(string)
}
if hostId != nil {
result.hostId = hostId.(string)
}
if errorCode != nil {
result.errorCode = errorCode.(string)
}
if recommend != nil {
result.recommend = recommend.(string)
}
if message != nil {
result.message = message.(string)
}
}
return result
}
func WrapServerError(originError *ServerError, wrapInfo map[string]string) *ServerError {
for _, wrapper := range wrapperList {
ok := wrapper.tryWrap(originError, wrapInfo)
if ok {
return originError
}
}
return originError
}
func (err *ServerError) HttpStatus() int {
return err.httpStatus
}
func (err *ServerError) ErrorCode() string {
return err.errorCode
}
func (err *ServerError) Message() string {
return err.message
}
func (err *ServerError) OriginError() error {
return nil
}
func (err *ServerError) HostId() string {
return err.hostId
}
func (err *ServerError) RequestId() string {
return err.requestId
}
func (err *ServerError) Recommend() string {
return err.recommend
}
func (err *ServerError) Comment() string {
return err.comment
}

View File

@ -0,0 +1,45 @@
package errors
import (
"strings"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/utils"
)
const SignatureDostNotMatchErrorCode = "SignatureDoesNotMatch"
const IncompleteSignatureErrorCode = "IncompleteSignature"
const MessageContain = "server string to sign is:"
var debug utils.Debug
func init() {
debug = utils.Init("sdk")
}
type SignatureDostNotMatchWrapper struct {
}
func (*SignatureDostNotMatchWrapper) tryWrap(error *ServerError, wrapInfo map[string]string) (ok bool) {
clientStringToSign := wrapInfo["StringToSign"]
if (error.errorCode == SignatureDostNotMatchErrorCode || error.errorCode == IncompleteSignatureErrorCode) && clientStringToSign != "" {
message := error.message
if strings.Contains(message, MessageContain) {
str := strings.Split(message, MessageContain)
serverStringToSign := str[1]
if clientStringToSign == serverStringToSign {
// user secret is error
error.recommend = "InvalidAccessKeySecret: Please check you AccessKeySecret"
} else {
debug("Client StringToSign: %s", clientStringToSign)
debug("Server StringToSign: %s", serverStringToSign)
error.recommend = "This may be a bug with the SDK and we hope you can submit this question in the " +
"github issue(https://github.com/aliyun/alibaba-cloud-sdk-go/issues), thanks very much"
}
}
ok = true
return
}
ok = false
return
}

View File

@ -0,0 +1,116 @@
package sdk
import (
"encoding/json"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/utils"
"io"
"log"
"os"
"strings"
"time"
)
var logChannel string
var defaultChannel = "AlibabaCloud"
type Logger struct {
*log.Logger
formatTemplate string
isOpen bool
lastLogMsg string
}
var defaultLoggerTemplate = `{time} {channel}: "{method} {uri} HTTP/{version}" {code} {cost} {hostname}`
var loggerParam = []string{"{time}", "{start_time}", "{ts}", "{channel}", "{pid}", "{host}", "{method}", "{uri}", "{version}", "{target}", "{hostname}", "{code}", "{error}", "{req_headers}", "{res_body}", "{res_headers}", "{cost}"}
func initLogMsg(fieldMap map[string]string) {
for _, value := range loggerParam {
fieldMap[value] = ""
}
}
func (client *Client) GetLogger() *Logger {
return client.logger
}
func (client *Client) GetLoggerMsg() string {
if client.logger == nil {
client.SetLogger("", "", os.Stdout, "")
}
return client.logger.lastLogMsg
}
func (client *Client) SetLogger(level string, channel string, out io.Writer, template string) {
if level == "" {
level = "info"
}
logChannel = "AlibabaCloud"
if channel != "" {
logChannel = channel
}
log := log.New(out, "["+strings.ToUpper(level)+"]", log.Lshortfile)
if template == "" {
template = defaultLoggerTemplate
}
client.logger = &Logger{
Logger: log,
formatTemplate: template,
isOpen: true,
}
}
func (client *Client) OpenLogger() {
if client.logger == nil {
client.SetLogger("", "", os.Stdout, "")
}
client.logger.isOpen = true
}
func (client *Client) CloseLogger() {
if client.logger != nil {
client.logger.isOpen = false
}
}
func (client *Client) SetTemplate(template string) {
if client.logger == nil {
client.SetLogger("", "", os.Stdout, "")
}
client.logger.formatTemplate = template
}
func (client *Client) GetTemplate() string {
if client.logger == nil {
client.SetLogger("", "", os.Stdout, "")
}
return client.logger.formatTemplate
}
func TransToString(object interface{}) string {
byt, err := json.Marshal(object)
if err != nil {
return ""
}
return string(byt)
}
func (client *Client) printLog(fieldMap map[string]string, err error) {
if err != nil {
fieldMap["{error}"] = err.Error()
}
fieldMap["{time}"] = time.Now().Format("2006-01-02 15:04:05")
fieldMap["{ts}"] = utils.GetTimeInFormatISO8601()
fieldMap["{channel}"] = logChannel
if client.logger != nil {
logMsg := client.logger.formatTemplate
for key, value := range fieldMap {
logMsg = strings.Replace(logMsg, key, value, -1)
}
client.logger.lastLogMsg = logMsg
if client.logger.isOpen == true {
client.logger.Output(2, logMsg)
}
}
}

View File

@ -0,0 +1,19 @@
load("@io_bazel_rules_go//go:def.bzl", "go_library")
go_library(
name = "go_default_library",
srcs = [
"acs_request.go",
"common_request.go",
"roa_request.go",
"rpc_request.go",
"types.go",
],
importmap = "k8s.io/kops/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests",
importpath = "github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests",
visibility = ["//visibility:public"],
deps = [
"//vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/errors:go_default_library",
"//vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/utils:go_default_library",
],
)

View File

@ -0,0 +1,443 @@
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package requests
import (
"encoding/json"
"fmt"
"io"
"reflect"
"strconv"
"strings"
"time"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/errors"
)
const (
RPC = "RPC"
ROA = "ROA"
HTTP = "HTTP"
HTTPS = "HTTPS"
DefaultHttpPort = "80"
GET = "GET"
PUT = "PUT"
POST = "POST"
DELETE = "DELETE"
PATCH = "PATCH"
HEAD = "HEAD"
OPTIONS = "OPTIONS"
Json = "application/json"
Xml = "application/xml"
Raw = "application/octet-stream"
Form = "application/x-www-form-urlencoded"
Header = "Header"
Query = "Query"
Body = "Body"
Path = "Path"
HeaderSeparator = "\n"
)
// interface
type AcsRequest interface {
GetScheme() string
GetMethod() string
GetDomain() string
GetPort() string
GetRegionId() string
GetHeaders() map[string]string
GetQueryParams() map[string]string
GetFormParams() map[string]string
GetContent() []byte
GetBodyReader() io.Reader
GetStyle() string
GetProduct() string
GetVersion() string
SetVersion(version string)
GetActionName() string
GetAcceptFormat() string
GetLocationServiceCode() string
GetLocationEndpointType() string
GetReadTimeout() time.Duration
GetConnectTimeout() time.Duration
SetReadTimeout(readTimeout time.Duration)
SetConnectTimeout(connectTimeout time.Duration)
SetHTTPSInsecure(isInsecure bool)
GetHTTPSInsecure() *bool
GetUserAgent() map[string]string
SetStringToSign(stringToSign string)
GetStringToSign() string
SetDomain(domain string)
SetContent(content []byte)
SetScheme(scheme string)
BuildUrl() string
BuildQueries() string
addHeaderParam(key, value string)
addQueryParam(key, value string)
addFormParam(key, value string)
addPathParam(key, value string)
}
// base class
type baseRequest struct {
Scheme string
Method string
Domain string
Port string
RegionId string
ReadTimeout time.Duration
ConnectTimeout time.Duration
isInsecure *bool
userAgent map[string]string
product string
version string
actionName string
AcceptFormat string
QueryParams map[string]string
Headers map[string]string
FormParams map[string]string
Content []byte
locationServiceCode string
locationEndpointType string
queries string
stringToSign string
}
func (request *baseRequest) GetQueryParams() map[string]string {
return request.QueryParams
}
func (request *baseRequest) GetFormParams() map[string]string {
return request.FormParams
}
func (request *baseRequest) GetReadTimeout() time.Duration {
return request.ReadTimeout
}
func (request *baseRequest) GetConnectTimeout() time.Duration {
return request.ConnectTimeout
}
func (request *baseRequest) SetReadTimeout(readTimeout time.Duration) {
request.ReadTimeout = readTimeout
}
func (request *baseRequest) SetConnectTimeout(connectTimeout time.Duration) {
request.ConnectTimeout = connectTimeout
}
func (request *baseRequest) GetHTTPSInsecure() *bool {
return request.isInsecure
}
func (request *baseRequest) SetHTTPSInsecure(isInsecure bool) {
request.isInsecure = &isInsecure
}
func (request *baseRequest) GetContent() []byte {
return request.Content
}
func (request *baseRequest) SetVersion(version string) {
request.version = version
}
func (request *baseRequest) GetVersion() string {
return request.version
}
func (request *baseRequest) GetActionName() string {
return request.actionName
}
func (request *baseRequest) SetContent(content []byte) {
request.Content = content
}
func (request *baseRequest) GetUserAgent() map[string]string {
return request.userAgent
}
func (request *baseRequest) AppendUserAgent(key, value string) {
newkey := true
if request.userAgent == nil {
request.userAgent = make(map[string]string)
}
if strings.ToLower(key) != "core" && strings.ToLower(key) != "go" {
for tag, _ := range request.userAgent {
if tag == key {
request.userAgent[tag] = value
newkey = false
}
}
if newkey {
request.userAgent[key] = value
}
}
}
func (request *baseRequest) addHeaderParam(key, value string) {
request.Headers[key] = value
}
func (request *baseRequest) addQueryParam(key, value string) {
request.QueryParams[key] = value
}
func (request *baseRequest) addFormParam(key, value string) {
request.FormParams[key] = value
}
func (request *baseRequest) GetAcceptFormat() string {
return request.AcceptFormat
}
func (request *baseRequest) GetLocationServiceCode() string {
return request.locationServiceCode
}
func (request *baseRequest) GetLocationEndpointType() string {
return request.locationEndpointType
}
func (request *baseRequest) GetProduct() string {
return request.product
}
func (request *baseRequest) GetScheme() string {
return request.Scheme
}
func (request *baseRequest) SetScheme(scheme string) {
request.Scheme = scheme
}
func (request *baseRequest) GetMethod() string {
return request.Method
}
func (request *baseRequest) GetDomain() string {
return request.Domain
}
func (request *baseRequest) SetDomain(host string) {
request.Domain = host
}
func (request *baseRequest) GetPort() string {
return request.Port
}
func (request *baseRequest) GetRegionId() string {
return request.RegionId
}
func (request *baseRequest) GetHeaders() map[string]string {
return request.Headers
}
func (request *baseRequest) SetContentType(contentType string) {
request.addHeaderParam("Content-Type", contentType)
}
func (request *baseRequest) GetContentType() (contentType string, contains bool) {
contentType, contains = request.Headers["Content-Type"]
return
}
func (request *baseRequest) SetStringToSign(stringToSign string) {
request.stringToSign = stringToSign
}
func (request *baseRequest) GetStringToSign() string {
return request.stringToSign
}
func defaultBaseRequest() (request *baseRequest) {
request = &baseRequest{
Scheme: "",
AcceptFormat: "JSON",
Method: GET,
QueryParams: make(map[string]string),
Headers: map[string]string{
"x-sdk-client": "golang/1.0.0",
"x-sdk-invoke-type": "normal",
"Accept-Encoding": "identity",
},
FormParams: make(map[string]string),
}
return
}
func InitParams(request AcsRequest) (err error) {
requestValue := reflect.ValueOf(request).Elem()
err = flatRepeatedList(requestValue, request, "", "")
return
}
func flatRepeatedList(dataValue reflect.Value, request AcsRequest, position, prefix string) (err error) {
dataType := dataValue.Type()
for i := 0; i < dataType.NumField(); i++ {
field := dataType.Field(i)
name, containsNameTag := field.Tag.Lookup("name")
fieldPosition := position
if fieldPosition == "" {
fieldPosition, _ = field.Tag.Lookup("position")
}
typeTag, containsTypeTag := field.Tag.Lookup("type")
if containsNameTag {
if !containsTypeTag {
// simple param
key := prefix + name
value := dataValue.Field(i).String()
if dataValue.Field(i).Kind().String() == "map" {
byt, _ := json.Marshal(dataValue.Field(i).Interface())
value = string(byt)
if value == "null" {
value = ""
}
}
err = addParam(request, fieldPosition, key, value)
if err != nil {
return
}
} else if typeTag == "Repeated" {
// repeated param
err = handleRepeatedParams(request, dataValue, prefix, name, fieldPosition, i)
if err != nil {
return
}
} else if typeTag == "Struct" {
err = handleStruct(request, dataValue, prefix, name, fieldPosition, i)
if err != nil {
return
}
}
}
}
return
}
func handleRepeatedParams(request AcsRequest, dataValue reflect.Value, prefix, name, fieldPosition string, index int) (err error) {
repeatedFieldValue := dataValue.Field(index)
if repeatedFieldValue.Kind() != reflect.Slice {
// possible value: {"[]string", "*[]struct"}, we must call Elem() in the last condition
repeatedFieldValue = repeatedFieldValue.Elem()
}
if repeatedFieldValue.IsValid() && !repeatedFieldValue.IsNil() {
for m := 0; m < repeatedFieldValue.Len(); m++ {
elementValue := repeatedFieldValue.Index(m)
key := prefix + name + "." + strconv.Itoa(m+1)
if elementValue.Type().Kind().String() == "string" {
value := elementValue.String()
err = addParam(request, fieldPosition, key, value)
if err != nil {
return
}
} else {
err = flatRepeatedList(elementValue, request, fieldPosition, key+".")
if err != nil {
return
}
}
}
}
return nil
}
func handleStruct(request AcsRequest, dataValue reflect.Value, prefix, name, fieldPosition string, index int) (err error) {
valueField := dataValue.Field(index)
if valueField.IsValid() && valueField.String() != "" {
valueFieldType := valueField.Type()
for m := 0; m < valueFieldType.NumField(); m++ {
fieldName := valueFieldType.Field(m).Name
elementValue := valueField.FieldByName(fieldName)
key := prefix + name + "." + fieldName
if elementValue.Type().String() == "[]string" {
if elementValue.IsNil() {
continue
}
for j := 0; j < elementValue.Len(); j++ {
err = addParam(request, fieldPosition, key+"."+strconv.Itoa(j+1), elementValue.Index(j).String())
if err != nil {
return
}
}
} else {
if elementValue.Type().Kind().String() == "string" {
value := elementValue.String()
err = addParam(request, fieldPosition, key, value)
if err != nil {
return
}
} else if elementValue.Type().Kind().String() == "struct" {
err = flatRepeatedList(elementValue, request, fieldPosition, key+".")
if err != nil {
return
}
} else if !elementValue.IsNil() {
repeatedFieldValue := elementValue.Elem()
if repeatedFieldValue.IsValid() && !repeatedFieldValue.IsNil() {
for m := 0; m < repeatedFieldValue.Len(); m++ {
elementValue := repeatedFieldValue.Index(m)
err = flatRepeatedList(elementValue, request, fieldPosition, key+"."+strconv.Itoa(m+1)+".")
if err != nil {
return
}
}
}
}
}
}
}
return nil
}
func addParam(request AcsRequest, position, name, value string) (err error) {
if len(value) > 0 {
switch position {
case Header:
request.addHeaderParam(name, value)
case Query:
request.addQueryParam(name, value)
case Path:
request.addPathParam(name, value)
case Body:
request.addFormParam(name, value)
default:
errMsg := fmt.Sprintf(errors.UnsupportedParamPositionErrorMessage, position)
err = errors.NewClientError(errors.UnsupportedParamPositionErrorCode, errMsg, nil)
}
}
return
}

View File

@ -0,0 +1,108 @@
package requests
import (
"bytes"
"fmt"
"io"
"sort"
"strings"
)
type CommonRequest struct {
*baseRequest
Version string
ApiName string
Product string
ServiceCode string
// roa params
PathPattern string
PathParams map[string]string
Ontology AcsRequest
}
func NewCommonRequest() (request *CommonRequest) {
request = &CommonRequest{
baseRequest: defaultBaseRequest(),
}
request.Headers["x-sdk-invoke-type"] = "common"
request.PathParams = make(map[string]string)
return
}
func (request *CommonRequest) String() string {
request.TransToAcsRequest()
resultBuilder := bytes.Buffer{}
mapOutput := func(m map[string]string) {
if len(m) > 0 {
sortedKeys := make([]string, 0)
for k := range m {
sortedKeys = append(sortedKeys, k)
}
// sort 'string' key in increasing order
sort.Strings(sortedKeys)
for _, key := range sortedKeys {
resultBuilder.WriteString(key + ": " + m[key] + "\n")
}
}
}
// Request Line
resultBuilder.WriteString(fmt.Sprintf("%s %s %s/1.1\n", request.Method, request.BuildQueries(), strings.ToUpper(request.Scheme)))
// Headers
resultBuilder.WriteString("Host" + ": " + request.Domain + "\n")
mapOutput(request.Headers)
resultBuilder.WriteString("\n")
// Body
if len(request.Content) > 0 {
resultBuilder.WriteString(string(request.Content) + "\n")
} else {
mapOutput(request.FormParams)
}
return resultBuilder.String()
}
func (request *CommonRequest) TransToAcsRequest() {
if len(request.PathPattern) > 0 {
roaRequest := &RoaRequest{}
roaRequest.initWithCommonRequest(request)
request.Ontology = roaRequest
} else {
rpcRequest := &RpcRequest{}
rpcRequest.baseRequest = request.baseRequest
rpcRequest.product = request.Product
rpcRequest.version = request.Version
rpcRequest.locationServiceCode = request.ServiceCode
rpcRequest.actionName = request.ApiName
request.Ontology = rpcRequest
}
}
func (request *CommonRequest) BuildUrl() string {
return request.Ontology.BuildUrl()
}
func (request *CommonRequest) BuildQueries() string {
return request.Ontology.BuildQueries()
}
func (request *CommonRequest) GetBodyReader() io.Reader {
return request.Ontology.GetBodyReader()
}
func (request *CommonRequest) GetStyle() string {
return request.Ontology.GetStyle()
}
func (request *CommonRequest) addPathParam(key, value string) {
request.PathParams[key] = value
}

View File

@ -0,0 +1,144 @@
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package requests
import (
"bytes"
"fmt"
"io"
"net/url"
"sort"
"strings"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/utils"
)
type RoaRequest struct {
*baseRequest
pathPattern string
PathParams map[string]string
}
func (*RoaRequest) GetStyle() string {
return ROA
}
func (request *RoaRequest) GetBodyReader() io.Reader {
if request.FormParams != nil && len(request.FormParams) > 0 {
formString := utils.GetUrlFormedMap(request.FormParams)
return strings.NewReader(formString)
} else if len(request.Content) > 0 {
return bytes.NewReader(request.Content)
} else {
return nil
}
}
// for sign method, need not url encoded
func (request *RoaRequest) BuildQueries() string {
return request.buildQueries()
}
func (request *RoaRequest) buildPath() string {
path := request.pathPattern
for key, value := range request.PathParams {
path = strings.Replace(path, "["+key+"]", value, 1)
}
return path
}
func (request *RoaRequest) buildQueries() string {
// replace path params with value
path := request.buildPath()
queryParams := request.QueryParams
// sort QueryParams by key
var queryKeys []string
for key := range queryParams {
queryKeys = append(queryKeys, key)
}
sort.Strings(queryKeys)
// append urlBuilder
urlBuilder := bytes.Buffer{}
urlBuilder.WriteString(path)
if len(queryKeys) > 0 {
urlBuilder.WriteString("?")
}
for i := 0; i < len(queryKeys); i++ {
queryKey := queryKeys[i]
urlBuilder.WriteString(queryKey)
if value := queryParams[queryKey]; len(value) > 0 {
urlBuilder.WriteString("=")
urlBuilder.WriteString(value)
}
if i < len(queryKeys)-1 {
urlBuilder.WriteString("&")
}
}
result := urlBuilder.String()
return result
}
func (request *RoaRequest) buildQueryString() string {
queryParams := request.QueryParams
// sort QueryParams by key
q := url.Values{}
for key, value := range queryParams {
q.Add(key, value)
}
return q.Encode()
}
func (request *RoaRequest) BuildUrl() string {
// for network trans, need url encoded
scheme := strings.ToLower(request.Scheme)
domain := request.Domain
port := request.Port
path := request.buildPath()
url := fmt.Sprintf("%s://%s:%s%s", scheme, domain, port, path)
querystring := request.buildQueryString()
if len(querystring) > 0 {
url = fmt.Sprintf("%s?%s", url, querystring)
}
return url
}
func (request *RoaRequest) addPathParam(key, value string) {
request.PathParams[key] = value
}
func (request *RoaRequest) InitWithApiInfo(product, version, action, uriPattern, serviceCode, endpointType string) {
request.baseRequest = defaultBaseRequest()
request.PathParams = make(map[string]string)
request.Headers["x-acs-version"] = version
request.pathPattern = uriPattern
request.locationServiceCode = serviceCode
request.locationEndpointType = endpointType
request.product = product
//request.version = version
request.actionName = action
}
func (request *RoaRequest) initWithCommonRequest(commonRequest *CommonRequest) {
request.baseRequest = commonRequest.baseRequest
request.PathParams = commonRequest.PathParams
request.product = commonRequest.Product
//request.version = commonRequest.Version
request.Headers["x-acs-version"] = commonRequest.Version
request.actionName = commonRequest.ApiName
request.pathPattern = commonRequest.PathPattern
request.locationServiceCode = commonRequest.ServiceCode
request.locationEndpointType = ""
}

View File

@ -0,0 +1,79 @@
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package requests
import (
"fmt"
"io"
"strings"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/utils"
)
type RpcRequest struct {
*baseRequest
}
func (request *RpcRequest) init() {
request.baseRequest = defaultBaseRequest()
request.Method = POST
}
func (*RpcRequest) GetStyle() string {
return RPC
}
func (request *RpcRequest) GetBodyReader() io.Reader {
if request.FormParams != nil && len(request.FormParams) > 0 {
formString := utils.GetUrlFormedMap(request.FormParams)
return strings.NewReader(formString)
} else {
return strings.NewReader("")
}
}
func (request *RpcRequest) BuildQueries() string {
request.queries = "/?" + utils.GetUrlFormedMap(request.QueryParams)
return request.queries
}
func (request *RpcRequest) BuildUrl() string {
url := fmt.Sprintf("%s://%s", strings.ToLower(request.Scheme), request.Domain)
if len(request.Port) > 0 {
url = fmt.Sprintf("%s:%s", url, request.Port)
}
return url + request.BuildQueries()
}
func (request *RpcRequest) GetVersion() string {
return request.version
}
func (request *RpcRequest) GetActionName() string {
return request.actionName
}
func (request *RpcRequest) addPathParam(key, value string) {
panic("not support")
}
func (request *RpcRequest) InitWithApiInfo(product, version, action, serviceCode, endpointType string) {
request.init()
request.product = product
request.version = version
request.actionName = action
request.locationServiceCode = serviceCode
request.locationEndpointType = endpointType
}

View File

@ -0,0 +1,53 @@
package requests
import "strconv"
type Integer string
func NewInteger(integer int) Integer {
return Integer(strconv.Itoa(integer))
}
func (integer Integer) HasValue() bool {
return integer != ""
}
func (integer Integer) GetValue() (int, error) {
return strconv.Atoi(string(integer))
}
func NewInteger64(integer int64) Integer {
return Integer(strconv.FormatInt(integer, 10))
}
func (integer Integer) GetValue64() (int64, error) {
return strconv.ParseInt(string(integer), 10, 0)
}
type Boolean string
func NewBoolean(bool bool) Boolean {
return Boolean(strconv.FormatBool(bool))
}
func (boolean Boolean) HasValue() bool {
return boolean != ""
}
func (boolean Boolean) GetValue() (bool, error) {
return strconv.ParseBool(string(boolean))
}
type Float string
func NewFloat(f float64) Float {
return Float(strconv.FormatFloat(f, 'f', 6, 64))
}
func (float Float) HasValue() bool {
return float != ""
}
func (float Float) GetValue() (float64, error) {
return strconv.ParseFloat(string(float), 64)
}

View File

@ -0,0 +1,17 @@
load("@io_bazel_rules_go//go:def.bzl", "go_library")
go_library(
name = "go_default_library",
srcs = [
"json_parser.go",
"response.go",
],
importmap = "k8s.io/kops/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses",
importpath = "github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses",
visibility = ["//visibility:public"],
deps = [
"//vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/errors:go_default_library",
"//vendor/github.com/json-iterator/go:go_default_library",
"//vendor/github.com/modern-go/reflect2:go_default_library",
],
)

View File

@ -0,0 +1,333 @@
package responses
import (
"encoding/json"
"io"
"math"
"reflect"
"strconv"
"strings"
"unsafe"
jsoniter "github.com/json-iterator/go"
"github.com/modern-go/reflect2"
)
const maxUint = ^uint(0)
const maxInt = int(maxUint >> 1)
const minInt = -maxInt - 1
var jsonParser jsoniter.API
func init() {
jsonParser = jsoniter.Config{
EscapeHTML: true,
SortMapKeys: true,
ValidateJsonRawMessage: true,
CaseSensitive: true,
}.Froze()
jsonParser.RegisterExtension(newBetterFuzzyExtension())
}
func newBetterFuzzyExtension() jsoniter.DecoderExtension {
return jsoniter.DecoderExtension{
reflect2.DefaultTypeOfKind(reflect.String): &nullableFuzzyStringDecoder{},
reflect2.DefaultTypeOfKind(reflect.Bool): &fuzzyBoolDecoder{},
reflect2.DefaultTypeOfKind(reflect.Float32): &nullableFuzzyFloat32Decoder{},
reflect2.DefaultTypeOfKind(reflect.Float64): &nullableFuzzyFloat64Decoder{},
reflect2.DefaultTypeOfKind(reflect.Int): &nullableFuzzyIntegerDecoder{func(isFloat bool, ptr unsafe.Pointer, iter *jsoniter.Iterator) {
if isFloat {
val := iter.ReadFloat64()
if val > float64(maxInt) || val < float64(minInt) {
iter.ReportError("fuzzy decode int", "exceed range")
return
}
*((*int)(ptr)) = int(val)
} else {
*((*int)(ptr)) = iter.ReadInt()
}
}},
reflect2.DefaultTypeOfKind(reflect.Uint): &nullableFuzzyIntegerDecoder{func(isFloat bool, ptr unsafe.Pointer, iter *jsoniter.Iterator) {
if isFloat {
val := iter.ReadFloat64()
if val > float64(maxUint) || val < 0 {
iter.ReportError("fuzzy decode uint", "exceed range")
return
}
*((*uint)(ptr)) = uint(val)
} else {
*((*uint)(ptr)) = iter.ReadUint()
}
}},
reflect2.DefaultTypeOfKind(reflect.Int8): &nullableFuzzyIntegerDecoder{func(isFloat bool, ptr unsafe.Pointer, iter *jsoniter.Iterator) {
if isFloat {
val := iter.ReadFloat64()
if val > float64(math.MaxInt8) || val < float64(math.MinInt8) {
iter.ReportError("fuzzy decode int8", "exceed range")
return
}
*((*int8)(ptr)) = int8(val)
} else {
*((*int8)(ptr)) = iter.ReadInt8()
}
}},
reflect2.DefaultTypeOfKind(reflect.Uint8): &nullableFuzzyIntegerDecoder{func(isFloat bool, ptr unsafe.Pointer, iter *jsoniter.Iterator) {
if isFloat {
val := iter.ReadFloat64()
if val > float64(math.MaxUint8) || val < 0 {
iter.ReportError("fuzzy decode uint8", "exceed range")
return
}
*((*uint8)(ptr)) = uint8(val)
} else {
*((*uint8)(ptr)) = iter.ReadUint8()
}
}},
reflect2.DefaultTypeOfKind(reflect.Int16): &nullableFuzzyIntegerDecoder{func(isFloat bool, ptr unsafe.Pointer, iter *jsoniter.Iterator) {
if isFloat {
val := iter.ReadFloat64()
if val > float64(math.MaxInt16) || val < float64(math.MinInt16) {
iter.ReportError("fuzzy decode int16", "exceed range")
return
}
*((*int16)(ptr)) = int16(val)
} else {
*((*int16)(ptr)) = iter.ReadInt16()
}
}},
reflect2.DefaultTypeOfKind(reflect.Uint16): &nullableFuzzyIntegerDecoder{func(isFloat bool, ptr unsafe.Pointer, iter *jsoniter.Iterator) {
if isFloat {
val := iter.ReadFloat64()
if val > float64(math.MaxUint16) || val < 0 {
iter.ReportError("fuzzy decode uint16", "exceed range")
return
}
*((*uint16)(ptr)) = uint16(val)
} else {
*((*uint16)(ptr)) = iter.ReadUint16()
}
}},
reflect2.DefaultTypeOfKind(reflect.Int32): &nullableFuzzyIntegerDecoder{func(isFloat bool, ptr unsafe.Pointer, iter *jsoniter.Iterator) {
if isFloat {
val := iter.ReadFloat64()
if val > float64(math.MaxInt32) || val < float64(math.MinInt32) {
iter.ReportError("fuzzy decode int32", "exceed range")
return
}
*((*int32)(ptr)) = int32(val)
} else {
*((*int32)(ptr)) = iter.ReadInt32()
}
}},
reflect2.DefaultTypeOfKind(reflect.Uint32): &nullableFuzzyIntegerDecoder{func(isFloat bool, ptr unsafe.Pointer, iter *jsoniter.Iterator) {
if isFloat {
val := iter.ReadFloat64()
if val > float64(math.MaxUint32) || val < 0 {
iter.ReportError("fuzzy decode uint32", "exceed range")
return
}
*((*uint32)(ptr)) = uint32(val)
} else {
*((*uint32)(ptr)) = iter.ReadUint32()
}
}},
reflect2.DefaultTypeOfKind(reflect.Int64): &nullableFuzzyIntegerDecoder{func(isFloat bool, ptr unsafe.Pointer, iter *jsoniter.Iterator) {
if isFloat {
val := iter.ReadFloat64()
if val > float64(math.MaxInt64) || val < float64(math.MinInt64) {
iter.ReportError("fuzzy decode int64", "exceed range")
return
}
*((*int64)(ptr)) = int64(val)
} else {
*((*int64)(ptr)) = iter.ReadInt64()
}
}},
reflect2.DefaultTypeOfKind(reflect.Uint64): &nullableFuzzyIntegerDecoder{func(isFloat bool, ptr unsafe.Pointer, iter *jsoniter.Iterator) {
if isFloat {
val := iter.ReadFloat64()
if val > float64(math.MaxUint64) || val < 0 {
iter.ReportError("fuzzy decode uint64", "exceed range")
return
}
*((*uint64)(ptr)) = uint64(val)
} else {
*((*uint64)(ptr)) = iter.ReadUint64()
}
}},
}
}
type nullableFuzzyStringDecoder struct {
}
func (decoder *nullableFuzzyStringDecoder) Decode(ptr unsafe.Pointer, iter *jsoniter.Iterator) {
valueType := iter.WhatIsNext()
switch valueType {
case jsoniter.NumberValue:
var number json.Number
iter.ReadVal(&number)
*((*string)(ptr)) = string(number)
case jsoniter.StringValue:
*((*string)(ptr)) = iter.ReadString()
case jsoniter.BoolValue:
*((*string)(ptr)) = strconv.FormatBool(iter.ReadBool())
case jsoniter.NilValue:
iter.ReadNil()
*((*string)(ptr)) = ""
default:
iter.ReportError("fuzzyStringDecoder", "not number or string or bool")
}
}
type fuzzyBoolDecoder struct {
}
func (decoder *fuzzyBoolDecoder) Decode(ptr unsafe.Pointer, iter *jsoniter.Iterator) {
valueType := iter.WhatIsNext()
switch valueType {
case jsoniter.BoolValue:
*((*bool)(ptr)) = iter.ReadBool()
case jsoniter.NumberValue:
var number json.Number
iter.ReadVal(&number)
num, err := number.Int64()
if err != nil {
iter.ReportError("fuzzyBoolDecoder", "get value from json.number failed")
}
if num == 0 {
*((*bool)(ptr)) = false
} else {
*((*bool)(ptr)) = true
}
case jsoniter.StringValue:
strValue := strings.ToLower(iter.ReadString())
if strValue == "true" {
*((*bool)(ptr)) = true
} else if strValue == "false" || strValue == "" {
*((*bool)(ptr)) = false
} else {
iter.ReportError("fuzzyBoolDecoder", "unsupported bool value: "+strValue)
}
case jsoniter.NilValue:
iter.ReadNil()
*((*bool)(ptr)) = false
default:
iter.ReportError("fuzzyBoolDecoder", "not number or string or nil")
}
}
type nullableFuzzyIntegerDecoder struct {
fun func(isFloat bool, ptr unsafe.Pointer, iter *jsoniter.Iterator)
}
func (decoder *nullableFuzzyIntegerDecoder) Decode(ptr unsafe.Pointer, iter *jsoniter.Iterator) {
valueType := iter.WhatIsNext()
var str string
switch valueType {
case jsoniter.NumberValue:
var number json.Number
iter.ReadVal(&number)
str = string(number)
case jsoniter.StringValue:
str = iter.ReadString()
// support empty string
if str == "" {
str = "0"
}
case jsoniter.BoolValue:
if iter.ReadBool() {
str = "1"
} else {
str = "0"
}
case jsoniter.NilValue:
iter.ReadNil()
str = "0"
default:
iter.ReportError("fuzzyIntegerDecoder", "not number or string")
}
newIter := iter.Pool().BorrowIterator([]byte(str))
defer iter.Pool().ReturnIterator(newIter)
isFloat := strings.IndexByte(str, '.') != -1
decoder.fun(isFloat, ptr, newIter)
if newIter.Error != nil && newIter.Error != io.EOF {
iter.Error = newIter.Error
}
}
type nullableFuzzyFloat32Decoder struct {
}
func (decoder *nullableFuzzyFloat32Decoder) Decode(ptr unsafe.Pointer, iter *jsoniter.Iterator) {
valueType := iter.WhatIsNext()
var str string
switch valueType {
case jsoniter.NumberValue:
*((*float32)(ptr)) = iter.ReadFloat32()
case jsoniter.StringValue:
str = iter.ReadString()
// support empty string
if str == "" {
*((*float32)(ptr)) = 0
return
}
newIter := iter.Pool().BorrowIterator([]byte(str))
defer iter.Pool().ReturnIterator(newIter)
*((*float32)(ptr)) = newIter.ReadFloat32()
if newIter.Error != nil && newIter.Error != io.EOF {
iter.Error = newIter.Error
}
case jsoniter.BoolValue:
// support bool to float32
if iter.ReadBool() {
*((*float32)(ptr)) = 1
} else {
*((*float32)(ptr)) = 0
}
case jsoniter.NilValue:
iter.ReadNil()
*((*float32)(ptr)) = 0
default:
iter.ReportError("nullableFuzzyFloat32Decoder", "not number or string")
}
}
type nullableFuzzyFloat64Decoder struct {
}
func (decoder *nullableFuzzyFloat64Decoder) Decode(ptr unsafe.Pointer, iter *jsoniter.Iterator) {
valueType := iter.WhatIsNext()
var str string
switch valueType {
case jsoniter.NumberValue:
*((*float64)(ptr)) = iter.ReadFloat64()
case jsoniter.StringValue:
str = iter.ReadString()
// support empty string
if str == "" {
*((*float64)(ptr)) = 0
return
}
newIter := iter.Pool().BorrowIterator([]byte(str))
defer iter.Pool().ReturnIterator(newIter)
*((*float64)(ptr)) = newIter.ReadFloat64()
if newIter.Error != nil && newIter.Error != io.EOF {
iter.Error = newIter.Error
}
case jsoniter.BoolValue:
// support bool to float64
if iter.ReadBool() {
*((*float64)(ptr)) = 1
} else {
*((*float64)(ptr)) = 0
}
case jsoniter.NilValue:
// support empty string
iter.ReadNil()
*((*float64)(ptr)) = 0
default:
iter.ReportError("nullableFuzzyFloat64Decoder", "not number or string")
}
}

View File

@ -0,0 +1,144 @@
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package responses
import (
"bytes"
"encoding/xml"
"fmt"
"io/ioutil"
"net/http"
"strings"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/errors"
)
type AcsResponse interface {
IsSuccess() bool
GetHttpStatus() int
GetHttpHeaders() map[string][]string
GetHttpContentString() string
GetHttpContentBytes() []byte
GetOriginHttpResponse() *http.Response
parseFromHttpResponse(httpResponse *http.Response) error
}
// Unmarshal object from http response body to target Response
func Unmarshal(response AcsResponse, httpResponse *http.Response, format string) (err error) {
err = response.parseFromHttpResponse(httpResponse)
if err != nil {
return
}
if !response.IsSuccess() {
err = errors.NewServerError(response.GetHttpStatus(), response.GetHttpContentString(), "")
return
}
if _, isCommonResponse := response.(*CommonResponse); isCommonResponse {
// common response need not unmarshal
return
}
if len(response.GetHttpContentBytes()) == 0 {
return
}
if strings.ToUpper(format) == "JSON" {
err = jsonParser.Unmarshal(response.GetHttpContentBytes(), response)
if err != nil {
err = errors.NewClientError(errors.JsonUnmarshalErrorCode, errors.JsonUnmarshalErrorMessage, err)
}
} else if strings.ToUpper(format) == "XML" {
err = xml.Unmarshal(response.GetHttpContentBytes(), response)
}
return
}
type BaseResponse struct {
httpStatus int
httpHeaders map[string][]string
httpContentString string
httpContentBytes []byte
originHttpResponse *http.Response
}
func (baseResponse *BaseResponse) GetHttpStatus() int {
return baseResponse.httpStatus
}
func (baseResponse *BaseResponse) GetHttpHeaders() map[string][]string {
return baseResponse.httpHeaders
}
func (baseResponse *BaseResponse) GetHttpContentString() string {
return baseResponse.httpContentString
}
func (baseResponse *BaseResponse) GetHttpContentBytes() []byte {
return baseResponse.httpContentBytes
}
func (baseResponse *BaseResponse) GetOriginHttpResponse() *http.Response {
return baseResponse.originHttpResponse
}
func (baseResponse *BaseResponse) IsSuccess() bool {
if baseResponse.GetHttpStatus() >= 200 && baseResponse.GetHttpStatus() < 300 {
return true
}
return false
}
func (baseResponse *BaseResponse) parseFromHttpResponse(httpResponse *http.Response) (err error) {
defer httpResponse.Body.Close()
body, err := ioutil.ReadAll(httpResponse.Body)
if err != nil {
return
}
baseResponse.httpStatus = httpResponse.StatusCode
baseResponse.httpHeaders = httpResponse.Header
baseResponse.httpContentBytes = body
baseResponse.httpContentString = string(body)
baseResponse.originHttpResponse = httpResponse
return
}
func (baseResponse *BaseResponse) String() string {
resultBuilder := bytes.Buffer{}
// statusCode
// resultBuilder.WriteString("\n")
resultBuilder.WriteString(fmt.Sprintf("%s %s\n", baseResponse.originHttpResponse.Proto, baseResponse.originHttpResponse.Status))
// httpHeaders
//resultBuilder.WriteString("Headers:\n")
for key, value := range baseResponse.httpHeaders {
resultBuilder.WriteString(key + ": " + strings.Join(value, ";") + "\n")
}
resultBuilder.WriteString("\n")
// content
//resultBuilder.WriteString("Content:\n")
resultBuilder.WriteString(baseResponse.httpContentString + "\n")
return resultBuilder.String()
}
type CommonResponse struct {
*BaseResponse
}
func NewCommonResponse() (response *CommonResponse) {
return &CommonResponse{
BaseResponse: &BaseResponse{},
}
}

View File

@ -0,0 +1,12 @@
load("@io_bazel_rules_go//go:def.bzl", "go_library")
go_library(
name = "go_default_library",
srcs = [
"debug.go",
"utils.go",
],
importmap = "k8s.io/kops/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/utils",
importpath = "github.com/aliyun/alibaba-cloud-sdk-go/sdk/utils",
visibility = ["//visibility:public"],
)

View File

@ -0,0 +1,36 @@
package utils
import (
"fmt"
"os"
"strings"
)
type Debug func(format string, v ...interface{})
var hookGetEnv = func() string {
return os.Getenv("DEBUG")
}
var hookPrint = func(input string) {
fmt.Println(input)
}
func Init(flag string) Debug {
enable := false
env := hookGetEnv()
parts := strings.Split(env, ",")
for _, part := range parts {
if part == flag {
enable = true
break
}
}
return func(format string, v ...interface{}) {
if enable {
hookPrint(fmt.Sprintf(format, v...))
}
}
}

View File

@ -0,0 +1,141 @@
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package utils
import (
"crypto/md5"
"crypto/rand"
"encoding/base64"
"encoding/hex"
"hash"
rand2 "math/rand"
"net/url"
"reflect"
"strconv"
"time"
)
type UUID [16]byte
const letterBytes = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
func GetUUID() (uuidHex string) {
uuid := NewUUID()
uuidHex = hex.EncodeToString(uuid[:])
return
}
func RandStringBytes(n int) string {
b := make([]byte, n)
for i := range b {
b[i] = letterBytes[rand2.Intn(len(letterBytes))]
}
return string(b)
}
func GetMD5Base64(bytes []byte) (base64Value string) {
md5Ctx := md5.New()
md5Ctx.Write(bytes)
md5Value := md5Ctx.Sum(nil)
base64Value = base64.StdEncoding.EncodeToString(md5Value)
return
}
func GetTimeInFormatISO8601() (timeStr string) {
gmt := time.FixedZone("GMT", 0)
return time.Now().In(gmt).Format("2006-01-02T15:04:05Z")
}
func GetTimeInFormatRFC2616() (timeStr string) {
gmt := time.FixedZone("GMT", 0)
return time.Now().In(gmt).Format("Mon, 02 Jan 2006 15:04:05 GMT")
}
func GetUrlFormedMap(source map[string]string) (urlEncoded string) {
urlEncoder := url.Values{}
for key, value := range source {
urlEncoder.Add(key, value)
}
urlEncoded = urlEncoder.Encode()
return
}
func InitStructWithDefaultTag(bean interface{}) {
configType := reflect.TypeOf(bean)
for i := 0; i < configType.Elem().NumField(); i++ {
field := configType.Elem().Field(i)
defaultValue := field.Tag.Get("default")
if defaultValue == "" {
continue
}
setter := reflect.ValueOf(bean).Elem().Field(i)
switch field.Type.String() {
case "int":
intValue, _ := strconv.ParseInt(defaultValue, 10, 64)
setter.SetInt(intValue)
case "time.Duration":
intValue, _ := strconv.ParseInt(defaultValue, 10, 64)
setter.SetInt(intValue)
case "string":
setter.SetString(defaultValue)
case "bool":
boolValue, _ := strconv.ParseBool(defaultValue)
setter.SetBool(boolValue)
}
}
}
func NewUUID() UUID {
ns := UUID{}
safeRandom(ns[:])
u := newFromHash(md5.New(), ns, RandStringBytes(16))
u[6] = (u[6] & 0x0f) | (byte(2) << 4)
u[8] = (u[8]&(0xff>>2) | (0x02 << 6))
return u
}
func newFromHash(h hash.Hash, ns UUID, name string) UUID {
u := UUID{}
h.Write(ns[:])
h.Write([]byte(name))
copy(u[:], h.Sum(nil))
return u
}
func safeRandom(dest []byte) {
if _, err := rand.Read(dest); err != nil {
panic(err)
}
}
func (u UUID) String() string {
buf := make([]byte, 36)
hex.Encode(buf[0:8], u[0:4])
buf[8] = '-'
hex.Encode(buf[9:13], u[4:6])
buf[13] = '-'
hex.Encode(buf[14:18], u[6:8])
buf[18] = '-'
hex.Encode(buf[19:23], u[8:10])
buf[23] = '-'
hex.Encode(buf[24:], u[10:])
return string(buf)
}

View File

@ -0,0 +1,183 @@
load("@io_bazel_rules_go//go:def.bzl", "go_library")
go_library(
name = "go_default_library",
srcs = [
"add_access_control_list_entry.go",
"add_backend_servers.go",
"add_listener_white_list_item.go",
"add_tags.go",
"add_v_server_group_backend_servers.go",
"client.go",
"create_access_control_list.go",
"create_domain_extension.go",
"create_load_balancer.go",
"create_load_balancer_http_listener.go",
"create_load_balancer_https_listener.go",
"create_load_balancer_tcp_listener.go",
"create_load_balancer_udp_listener.go",
"create_master_slave_server_group.go",
"create_rules.go",
"create_v_server_group.go",
"delete_access_control_list.go",
"delete_ca_certificate.go",
"delete_domain_extension.go",
"delete_load_balancer.go",
"delete_load_balancer_listener.go",
"delete_master_slave_server_group.go",
"delete_rules.go",
"delete_server_certificate.go",
"delete_v_server_group.go",
"describe_access_control_list_attribute.go",
"describe_access_control_lists.go",
"describe_available_resource.go",
"describe_ca_certificates.go",
"describe_domain_extension_attribute.go",
"describe_domain_extensions.go",
"describe_health_status.go",
"describe_listener_access_control_attribute.go",
"describe_load_balancer_attribute.go",
"describe_load_balancer_http_listener_attribute.go",
"describe_load_balancer_https_listener_attribute.go",
"describe_load_balancer_tcp_listener_attribute.go",
"describe_load_balancer_udp_listener_attribute.go",
"describe_load_balancers.go",
"describe_master_slave_server_group_attribute.go",
"describe_master_slave_server_groups.go",
"describe_regions.go",
"describe_rule_attribute.go",
"describe_rules.go",
"describe_server_certificates.go",
"describe_tags.go",
"describe_v_server_group_attribute.go",
"describe_v_server_groups.go",
"describe_zones.go",
"endpoint.go",
"list_tag_resources.go",
"modify_load_balancer_instance_spec.go",
"modify_load_balancer_internet_spec.go",
"modify_load_balancer_pay_type.go",
"modify_v_server_group_backend_servers.go",
"remove_access_control_list_entry.go",
"remove_backend_servers.go",
"remove_listener_white_list_item.go",
"remove_tags.go",
"remove_v_server_group_backend_servers.go",
"set_access_control_list_attribute.go",
"set_backend_servers.go",
"set_ca_certificate_name.go",
"set_domain_extension_attribute.go",
"set_listener_access_control_status.go",
"set_load_balancer_delete_protection.go",
"set_load_balancer_http_listener_attribute.go",
"set_load_balancer_https_listener_attribute.go",
"set_load_balancer_name.go",
"set_load_balancer_status.go",
"set_load_balancer_tcp_listener_attribute.go",
"set_load_balancer_udp_listener_attribute.go",
"set_rule.go",
"set_server_certificate_name.go",
"set_v_server_group_attribute.go",
"start_load_balancer_listener.go",
"stop_load_balancer_listener.go",
"struct_acl.go",
"struct_acl_entry.go",
"struct_acl_entrys.go",
"struct_acl_ids_in_describe_load_balancer_http_listener_attribute.go",
"struct_acl_ids_in_describe_load_balancer_https_listener_attribute.go",
"struct_acl_ids_in_describe_load_balancer_tcp_listener_attribute.go",
"struct_acl_ids_in_describe_load_balancer_udp_listener_attribute.go",
"struct_acls.go",
"struct_associated_objects.go",
"struct_available_resource.go",
"struct_available_resources.go",
"struct_backend_server.go",
"struct_backend_server_in_add_v_server_group_backend_servers.go",
"struct_backend_server_in_create_v_server_group.go",
"struct_backend_server_in_describe_load_balancer_attribute.go",
"struct_backend_server_in_describe_v_server_group_attribute.go",
"struct_backend_server_in_modify_v_server_group_backend_servers.go",
"struct_backend_server_in_remove_backend_servers.go",
"struct_backend_server_in_remove_v_server_group_backend_servers.go",
"struct_backend_server_in_set_v_server_group_attribute.go",
"struct_backend_servers_in_add_backend_servers.go",
"struct_backend_servers_in_add_v_server_group_backend_servers.go",
"struct_backend_servers_in_create_v_server_group.go",
"struct_backend_servers_in_describe_health_status.go",
"struct_backend_servers_in_describe_load_balancer_attribute.go",
"struct_backend_servers_in_describe_v_server_group_attribute.go",
"struct_backend_servers_in_modify_v_server_group_backend_servers.go",
"struct_backend_servers_in_remove_backend_servers.go",
"struct_backend_servers_in_remove_v_server_group_backend_servers.go",
"struct_backend_servers_in_set_backend_servers.go",
"struct_backend_servers_in_set_v_server_group_attribute.go",
"struct_ca_certificate.go",
"struct_ca_certificates.go",
"struct_domain_extension.go",
"struct_domain_extensions_in_describe_domain_extensions.go",
"struct_domain_extensions_in_describe_load_balancer_https_listener_attribute.go",
"struct_listener.go",
"struct_listener_port_and_protocal.go",
"struct_listener_port_and_protocol.go",
"struct_listener_ports.go",
"struct_listener_ports_and_protocal.go",
"struct_listener_ports_and_protocol.go",
"struct_listeners_in_describe_master_slave_server_groups.go",
"struct_listeners_in_describe_v_server_groups.go",
"struct_load_balancer.go",
"struct_load_balancers.go",
"struct_master_slave_backend_server.go",
"struct_master_slave_backend_servers_in_create_master_slave_server_group.go",
"struct_master_slave_backend_servers_in_describe_master_slave_server_group_attribute.go",
"struct_master_slave_server_group.go",
"struct_master_slave_server_groups.go",
"struct_port_range.go",
"struct_port_ranges_in_describe_load_balancer_tcp_listener_attribute.go",
"struct_port_ranges_in_describe_load_balancer_udp_listener_attribute.go",
"struct_region.go",
"struct_regions.go",
"struct_related_listener.go",
"struct_related_listeners.go",
"struct_rule.go",
"struct_rules_in_create_rules.go",
"struct_rules_in_describe_load_balancer_http_listener_attribute.go",
"struct_rules_in_describe_load_balancer_https_listener_attribute.go",
"struct_rules_in_describe_rules.go",
"struct_rules_in_describe_v_server_groups.go",
"struct_server_certificate.go",
"struct_server_certificates.go",
"struct_slave_zone.go",
"struct_slave_zones.go",
"struct_subject_alternative_names_in_describe_server_certificates.go",
"struct_subject_alternative_names_in_upload_server_certificate.go",
"struct_support_resource.go",
"struct_support_resources.go",
"struct_tag.go",
"struct_tag_resource.go",
"struct_tag_resources.go",
"struct_tag_set.go",
"struct_tag_sets.go",
"struct_tags_in_describe_access_control_lists.go",
"struct_tags_in_describe_ca_certificates.go",
"struct_tags_in_describe_load_balancers.go",
"struct_tags_in_describe_server_certificates.go",
"struct_v_server_group.go",
"struct_v_server_groups.go",
"struct_zone.go",
"struct_zones.go",
"tag_resources.go",
"untag_resources.go",
"upload_ca_certificate.go",
"upload_server_certificate.go",
],
importmap = "k8s.io/kops/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/slb",
importpath = "github.com/aliyun/alibaba-cloud-sdk-go/services/slb",
visibility = ["//visibility:public"],
deps = [
"//vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk:go_default_library",
"//vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth:go_default_library",
"//vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credentials/provider:go_default_library",
"//vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests:go_default_library",
"//vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses:go_default_library",
],
)

View File

@ -0,0 +1,110 @@
package slb
//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
//
//http://www.apache.org/licenses/LICENSE-2.0
//
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.
//
// Code generated by Alibaba Cloud SDK Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
import (
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses"
)
// AddAccessControlListEntry invokes the slb.AddAccessControlListEntry API synchronously
// api document: https://help.aliyun.com/api/slb/addaccesscontrollistentry.html
func (client *Client) AddAccessControlListEntry(request *AddAccessControlListEntryRequest) (response *AddAccessControlListEntryResponse, err error) {
response = CreateAddAccessControlListEntryResponse()
err = client.DoAction(request, response)
return
}
// AddAccessControlListEntryWithChan invokes the slb.AddAccessControlListEntry API asynchronously
// api document: https://help.aliyun.com/api/slb/addaccesscontrollistentry.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) AddAccessControlListEntryWithChan(request *AddAccessControlListEntryRequest) (<-chan *AddAccessControlListEntryResponse, <-chan error) {
responseChan := make(chan *AddAccessControlListEntryResponse, 1)
errChan := make(chan error, 1)
err := client.AddAsyncTask(func() {
defer close(responseChan)
defer close(errChan)
response, err := client.AddAccessControlListEntry(request)
if err != nil {
errChan <- err
} else {
responseChan <- response
}
})
if err != nil {
errChan <- err
close(responseChan)
close(errChan)
}
return responseChan, errChan
}
// AddAccessControlListEntryWithCallback invokes the slb.AddAccessControlListEntry API asynchronously
// api document: https://help.aliyun.com/api/slb/addaccesscontrollistentry.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) AddAccessControlListEntryWithCallback(request *AddAccessControlListEntryRequest, callback func(response *AddAccessControlListEntryResponse, err error)) <-chan int {
result := make(chan int, 1)
err := client.AddAsyncTask(func() {
var response *AddAccessControlListEntryResponse
var err error
defer close(result)
response, err = client.AddAccessControlListEntry(request)
callback(response, err)
result <- 1
})
if err != nil {
defer close(result)
callback(nil, err)
result <- 0
}
return result
}
// AddAccessControlListEntryRequest is the request struct for api AddAccessControlListEntry
type AddAccessControlListEntryRequest struct {
*requests.RpcRequest
AccessKeyId string `position:"Query" name:"access_key_id"`
ResourceOwnerId requests.Integer `position:"Query" name:"ResourceOwnerId"`
AclEntrys string `position:"Query" name:"AclEntrys"`
AclId string `position:"Query" name:"AclId"`
ResourceOwnerAccount string `position:"Query" name:"ResourceOwnerAccount"`
OwnerAccount string `position:"Query" name:"OwnerAccount"`
OwnerId requests.Integer `position:"Query" name:"OwnerId"`
Tags string `position:"Query" name:"Tags"`
}
// AddAccessControlListEntryResponse is the response struct for api AddAccessControlListEntry
type AddAccessControlListEntryResponse struct {
*responses.BaseResponse
RequestId string `json:"RequestId" xml:"RequestId"`
}
// CreateAddAccessControlListEntryRequest creates a request to invoke AddAccessControlListEntry API
func CreateAddAccessControlListEntryRequest() (request *AddAccessControlListEntryRequest) {
request = &AddAccessControlListEntryRequest{
RpcRequest: &requests.RpcRequest{},
}
request.InitWithApiInfo("Slb", "2014-05-15", "AddAccessControlListEntry", "slb", "openAPI")
return
}
// CreateAddAccessControlListEntryResponse creates a response to parse from AddAccessControlListEntry response
func CreateAddAccessControlListEntryResponse() (response *AddAccessControlListEntryResponse) {
response = &AddAccessControlListEntryResponse{
BaseResponse: &responses.BaseResponse{},
}
return
}

View File

@ -0,0 +1,112 @@
package slb
//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
//
//http://www.apache.org/licenses/LICENSE-2.0
//
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.
//
// Code generated by Alibaba Cloud SDK Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
import (
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses"
)
// AddBackendServers invokes the slb.AddBackendServers API synchronously
// api document: https://help.aliyun.com/api/slb/addbackendservers.html
func (client *Client) AddBackendServers(request *AddBackendServersRequest) (response *AddBackendServersResponse, err error) {
response = CreateAddBackendServersResponse()
err = client.DoAction(request, response)
return
}
// AddBackendServersWithChan invokes the slb.AddBackendServers API asynchronously
// api document: https://help.aliyun.com/api/slb/addbackendservers.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) AddBackendServersWithChan(request *AddBackendServersRequest) (<-chan *AddBackendServersResponse, <-chan error) {
responseChan := make(chan *AddBackendServersResponse, 1)
errChan := make(chan error, 1)
err := client.AddAsyncTask(func() {
defer close(responseChan)
defer close(errChan)
response, err := client.AddBackendServers(request)
if err != nil {
errChan <- err
} else {
responseChan <- response
}
})
if err != nil {
errChan <- err
close(responseChan)
close(errChan)
}
return responseChan, errChan
}
// AddBackendServersWithCallback invokes the slb.AddBackendServers API asynchronously
// api document: https://help.aliyun.com/api/slb/addbackendservers.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) AddBackendServersWithCallback(request *AddBackendServersRequest, callback func(response *AddBackendServersResponse, err error)) <-chan int {
result := make(chan int, 1)
err := client.AddAsyncTask(func() {
var response *AddBackendServersResponse
var err error
defer close(result)
response, err = client.AddBackendServers(request)
callback(response, err)
result <- 1
})
if err != nil {
defer close(result)
callback(nil, err)
result <- 0
}
return result
}
// AddBackendServersRequest is the request struct for api AddBackendServers
type AddBackendServersRequest struct {
*requests.RpcRequest
AccessKeyId string `position:"Query" name:"access_key_id"`
ResourceOwnerId requests.Integer `position:"Query" name:"ResourceOwnerId"`
BackendServers string `position:"Query" name:"BackendServers"`
ResourceOwnerAccount string `position:"Query" name:"ResourceOwnerAccount"`
OwnerAccount string `position:"Query" name:"OwnerAccount"`
OwnerId requests.Integer `position:"Query" name:"OwnerId"`
Tags string `position:"Query" name:"Tags"`
LoadBalancerId string `position:"Query" name:"LoadBalancerId"`
}
// AddBackendServersResponse is the response struct for api AddBackendServers
type AddBackendServersResponse struct {
*responses.BaseResponse
RequestId string `json:"RequestId" xml:"RequestId"`
LoadBalancerId string `json:"LoadBalancerId" xml:"LoadBalancerId"`
BackendServers BackendServersInAddBackendServers `json:"BackendServers" xml:"BackendServers"`
}
// CreateAddBackendServersRequest creates a request to invoke AddBackendServers API
func CreateAddBackendServersRequest() (request *AddBackendServersRequest) {
request = &AddBackendServersRequest{
RpcRequest: &requests.RpcRequest{},
}
request.InitWithApiInfo("Slb", "2014-05-15", "AddBackendServers", "slb", "openAPI")
return
}
// CreateAddBackendServersResponse creates a response to parse from AddBackendServers response
func CreateAddBackendServersResponse() (response *AddBackendServersResponse) {
response = &AddBackendServersResponse{
BaseResponse: &responses.BaseResponse{},
}
return
}

View File

@ -0,0 +1,112 @@
package slb
//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
//
//http://www.apache.org/licenses/LICENSE-2.0
//
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.
//
// Code generated by Alibaba Cloud SDK Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
import (
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses"
)
// AddListenerWhiteListItem invokes the slb.AddListenerWhiteListItem API synchronously
// api document: https://help.aliyun.com/api/slb/addlistenerwhitelistitem.html
func (client *Client) AddListenerWhiteListItem(request *AddListenerWhiteListItemRequest) (response *AddListenerWhiteListItemResponse, err error) {
response = CreateAddListenerWhiteListItemResponse()
err = client.DoAction(request, response)
return
}
// AddListenerWhiteListItemWithChan invokes the slb.AddListenerWhiteListItem API asynchronously
// api document: https://help.aliyun.com/api/slb/addlistenerwhitelistitem.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) AddListenerWhiteListItemWithChan(request *AddListenerWhiteListItemRequest) (<-chan *AddListenerWhiteListItemResponse, <-chan error) {
responseChan := make(chan *AddListenerWhiteListItemResponse, 1)
errChan := make(chan error, 1)
err := client.AddAsyncTask(func() {
defer close(responseChan)
defer close(errChan)
response, err := client.AddListenerWhiteListItem(request)
if err != nil {
errChan <- err
} else {
responseChan <- response
}
})
if err != nil {
errChan <- err
close(responseChan)
close(errChan)
}
return responseChan, errChan
}
// AddListenerWhiteListItemWithCallback invokes the slb.AddListenerWhiteListItem API asynchronously
// api document: https://help.aliyun.com/api/slb/addlistenerwhitelistitem.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) AddListenerWhiteListItemWithCallback(request *AddListenerWhiteListItemRequest, callback func(response *AddListenerWhiteListItemResponse, err error)) <-chan int {
result := make(chan int, 1)
err := client.AddAsyncTask(func() {
var response *AddListenerWhiteListItemResponse
var err error
defer close(result)
response, err = client.AddListenerWhiteListItem(request)
callback(response, err)
result <- 1
})
if err != nil {
defer close(result)
callback(nil, err)
result <- 0
}
return result
}
// AddListenerWhiteListItemRequest is the request struct for api AddListenerWhiteListItem
type AddListenerWhiteListItemRequest struct {
*requests.RpcRequest
AccessKeyId string `position:"Query" name:"access_key_id"`
ResourceOwnerId requests.Integer `position:"Query" name:"ResourceOwnerId"`
SourceItems string `position:"Query" name:"SourceItems"`
ListenerPort requests.Integer `position:"Query" name:"ListenerPort"`
ResourceOwnerAccount string `position:"Query" name:"ResourceOwnerAccount"`
OwnerAccount string `position:"Query" name:"OwnerAccount"`
OwnerId requests.Integer `position:"Query" name:"OwnerId"`
ListenerProtocol string `position:"Query" name:"ListenerProtocol"`
Tags string `position:"Query" name:"Tags"`
LoadBalancerId string `position:"Query" name:"LoadBalancerId"`
}
// AddListenerWhiteListItemResponse is the response struct for api AddListenerWhiteListItem
type AddListenerWhiteListItemResponse struct {
*responses.BaseResponse
RequestId string `json:"RequestId" xml:"RequestId"`
}
// CreateAddListenerWhiteListItemRequest creates a request to invoke AddListenerWhiteListItem API
func CreateAddListenerWhiteListItemRequest() (request *AddListenerWhiteListItemRequest) {
request = &AddListenerWhiteListItemRequest{
RpcRequest: &requests.RpcRequest{},
}
request.InitWithApiInfo("Slb", "2014-05-15", "AddListenerWhiteListItem", "slb", "openAPI")
return
}
// CreateAddListenerWhiteListItemResponse creates a response to parse from AddListenerWhiteListItem response
func CreateAddListenerWhiteListItemResponse() (response *AddListenerWhiteListItemResponse) {
response = &AddListenerWhiteListItemResponse{
BaseResponse: &responses.BaseResponse{},
}
return
}

View File

@ -0,0 +1,109 @@
package slb
//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
//
//http://www.apache.org/licenses/LICENSE-2.0
//
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.
//
// Code generated by Alibaba Cloud SDK Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
import (
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses"
)
// AddTags invokes the slb.AddTags API synchronously
// api document: https://help.aliyun.com/api/slb/addtags.html
func (client *Client) AddTags(request *AddTagsRequest) (response *AddTagsResponse, err error) {
response = CreateAddTagsResponse()
err = client.DoAction(request, response)
return
}
// AddTagsWithChan invokes the slb.AddTags API asynchronously
// api document: https://help.aliyun.com/api/slb/addtags.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) AddTagsWithChan(request *AddTagsRequest) (<-chan *AddTagsResponse, <-chan error) {
responseChan := make(chan *AddTagsResponse, 1)
errChan := make(chan error, 1)
err := client.AddAsyncTask(func() {
defer close(responseChan)
defer close(errChan)
response, err := client.AddTags(request)
if err != nil {
errChan <- err
} else {
responseChan <- response
}
})
if err != nil {
errChan <- err
close(responseChan)
close(errChan)
}
return responseChan, errChan
}
// AddTagsWithCallback invokes the slb.AddTags API asynchronously
// api document: https://help.aliyun.com/api/slb/addtags.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) AddTagsWithCallback(request *AddTagsRequest, callback func(response *AddTagsResponse, err error)) <-chan int {
result := make(chan int, 1)
err := client.AddAsyncTask(func() {
var response *AddTagsResponse
var err error
defer close(result)
response, err = client.AddTags(request)
callback(response, err)
result <- 1
})
if err != nil {
defer close(result)
callback(nil, err)
result <- 0
}
return result
}
// AddTagsRequest is the request struct for api AddTags
type AddTagsRequest struct {
*requests.RpcRequest
AccessKeyId string `position:"Query" name:"access_key_id"`
ResourceOwnerId requests.Integer `position:"Query" name:"ResourceOwnerId"`
ResourceOwnerAccount string `position:"Query" name:"ResourceOwnerAccount"`
OwnerAccount string `position:"Query" name:"OwnerAccount"`
OwnerId requests.Integer `position:"Query" name:"OwnerId"`
Tags string `position:"Query" name:"Tags"`
LoadBalancerId string `position:"Query" name:"LoadBalancerId"`
}
// AddTagsResponse is the response struct for api AddTags
type AddTagsResponse struct {
*responses.BaseResponse
RequestId string `json:"RequestId" xml:"RequestId"`
}
// CreateAddTagsRequest creates a request to invoke AddTags API
func CreateAddTagsRequest() (request *AddTagsRequest) {
request = &AddTagsRequest{
RpcRequest: &requests.RpcRequest{},
}
request.InitWithApiInfo("Slb", "2014-05-15", "AddTags", "slb", "openAPI")
return
}
// CreateAddTagsResponse creates a response to parse from AddTags response
func CreateAddTagsResponse() (response *AddTagsResponse) {
response = &AddTagsResponse{
BaseResponse: &responses.BaseResponse{},
}
return
}

View File

@ -0,0 +1,112 @@
package slb
//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
//
//http://www.apache.org/licenses/LICENSE-2.0
//
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.
//
// Code generated by Alibaba Cloud SDK Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
import (
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses"
)
// AddVServerGroupBackendServers invokes the slb.AddVServerGroupBackendServers API synchronously
// api document: https://help.aliyun.com/api/slb/addvservergroupbackendservers.html
func (client *Client) AddVServerGroupBackendServers(request *AddVServerGroupBackendServersRequest) (response *AddVServerGroupBackendServersResponse, err error) {
response = CreateAddVServerGroupBackendServersResponse()
err = client.DoAction(request, response)
return
}
// AddVServerGroupBackendServersWithChan invokes the slb.AddVServerGroupBackendServers API asynchronously
// api document: https://help.aliyun.com/api/slb/addvservergroupbackendservers.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) AddVServerGroupBackendServersWithChan(request *AddVServerGroupBackendServersRequest) (<-chan *AddVServerGroupBackendServersResponse, <-chan error) {
responseChan := make(chan *AddVServerGroupBackendServersResponse, 1)
errChan := make(chan error, 1)
err := client.AddAsyncTask(func() {
defer close(responseChan)
defer close(errChan)
response, err := client.AddVServerGroupBackendServers(request)
if err != nil {
errChan <- err
} else {
responseChan <- response
}
})
if err != nil {
errChan <- err
close(responseChan)
close(errChan)
}
return responseChan, errChan
}
// AddVServerGroupBackendServersWithCallback invokes the slb.AddVServerGroupBackendServers API asynchronously
// api document: https://help.aliyun.com/api/slb/addvservergroupbackendservers.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) AddVServerGroupBackendServersWithCallback(request *AddVServerGroupBackendServersRequest, callback func(response *AddVServerGroupBackendServersResponse, err error)) <-chan int {
result := make(chan int, 1)
err := client.AddAsyncTask(func() {
var response *AddVServerGroupBackendServersResponse
var err error
defer close(result)
response, err = client.AddVServerGroupBackendServers(request)
callback(response, err)
result <- 1
})
if err != nil {
defer close(result)
callback(nil, err)
result <- 0
}
return result
}
// AddVServerGroupBackendServersRequest is the request struct for api AddVServerGroupBackendServers
type AddVServerGroupBackendServersRequest struct {
*requests.RpcRequest
AccessKeyId string `position:"Query" name:"access_key_id"`
ResourceOwnerId requests.Integer `position:"Query" name:"ResourceOwnerId"`
BackendServers string `position:"Query" name:"BackendServers"`
VServerGroupId string `position:"Query" name:"VServerGroupId"`
ResourceOwnerAccount string `position:"Query" name:"ResourceOwnerAccount"`
OwnerAccount string `position:"Query" name:"OwnerAccount"`
OwnerId requests.Integer `position:"Query" name:"OwnerId"`
Tags string `position:"Query" name:"Tags"`
}
// AddVServerGroupBackendServersResponse is the response struct for api AddVServerGroupBackendServers
type AddVServerGroupBackendServersResponse struct {
*responses.BaseResponse
RequestId string `json:"RequestId" xml:"RequestId"`
VServerGroupId string `json:"VServerGroupId" xml:"VServerGroupId"`
BackendServers BackendServersInAddVServerGroupBackendServers `json:"BackendServers" xml:"BackendServers"`
}
// CreateAddVServerGroupBackendServersRequest creates a request to invoke AddVServerGroupBackendServers API
func CreateAddVServerGroupBackendServersRequest() (request *AddVServerGroupBackendServersRequest) {
request = &AddVServerGroupBackendServersRequest{
RpcRequest: &requests.RpcRequest{},
}
request.InitWithApiInfo("Slb", "2014-05-15", "AddVServerGroupBackendServers", "slb", "openAPI")
return
}
// CreateAddVServerGroupBackendServersResponse creates a response to parse from AddVServerGroupBackendServers response
func CreateAddVServerGroupBackendServersResponse() (response *AddVServerGroupBackendServersResponse) {
response = &AddVServerGroupBackendServersResponse{
BaseResponse: &responses.BaseResponse{},
}
return
}

View File

@ -0,0 +1,129 @@
package slb
//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
//
//http://www.apache.org/licenses/LICENSE-2.0
//
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.
//
// Code generated by Alibaba Cloud SDK Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
import (
"reflect"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credentials/provider"
)
// Client is the sdk client struct, each func corresponds to an OpenAPI
type Client struct {
sdk.Client
}
// SetClientProperty Set Property by Reflect
func SetClientProperty(client *Client, propertyName string, propertyValue interface{}) {
v := reflect.ValueOf(client).Elem()
if v.FieldByName(propertyName).IsValid() && v.FieldByName(propertyName).CanSet() {
v.FieldByName(propertyName).Set(reflect.ValueOf(propertyValue))
}
}
// SetEndpointDataToClient Set EndpointMap and ENdpointType
func SetEndpointDataToClient(client *Client) {
SetClientProperty(client, "EndpointMap", GetEndpointMap())
SetClientProperty(client, "EndpointType", GetEndpointType())
}
// NewClient creates a sdk client with environment variables
func NewClient() (client *Client, err error) {
client = &Client{}
err = client.Init()
SetEndpointDataToClient(client)
return
}
// NewClientWithProvider creates a sdk client with providers
// usage: https://github.com/aliyun/alibaba-cloud-sdk-go/blob/master/docs/2-Client-EN.md
func NewClientWithProvider(regionId string, providers ...provider.Provider) (client *Client, err error) {
client = &Client{}
var pc provider.Provider
if len(providers) == 0 {
pc = provider.DefaultChain
} else {
pc = provider.NewProviderChain(providers)
}
err = client.InitWithProviderChain(regionId, pc)
SetEndpointDataToClient(client)
return
}
// NewClientWithOptions creates a sdk client with regionId/sdkConfig/credential
// this is the common api to create a sdk client
func NewClientWithOptions(regionId string, config *sdk.Config, credential auth.Credential) (client *Client, err error) {
client = &Client{}
err = client.InitWithOptions(regionId, config, credential)
SetEndpointDataToClient(client)
return
}
// NewClientWithAccessKey is a shortcut to create sdk client with accesskey
// usage: https://github.com/aliyun/alibaba-cloud-sdk-go/blob/master/docs/2-Client-EN.md
func NewClientWithAccessKey(regionId, accessKeyId, accessKeySecret string) (client *Client, err error) {
client = &Client{}
err = client.InitWithAccessKey(regionId, accessKeyId, accessKeySecret)
SetEndpointDataToClient(client)
return
}
// NewClientWithStsToken is a shortcut to create sdk client with sts token
// usage: https://github.com/aliyun/alibaba-cloud-sdk-go/blob/master/docs/2-Client-EN.md
func NewClientWithStsToken(regionId, stsAccessKeyId, stsAccessKeySecret, stsToken string) (client *Client, err error) {
client = &Client{}
err = client.InitWithStsToken(regionId, stsAccessKeyId, stsAccessKeySecret, stsToken)
SetEndpointDataToClient(client)
return
}
// NewClientWithRamRoleArn is a shortcut to create sdk client with ram roleArn
// usage: https://github.com/aliyun/alibaba-cloud-sdk-go/blob/master/docs/2-Client-EN.md
func NewClientWithRamRoleArn(regionId string, accessKeyId, accessKeySecret, roleArn, roleSessionName string) (client *Client, err error) {
client = &Client{}
err = client.InitWithRamRoleArn(regionId, accessKeyId, accessKeySecret, roleArn, roleSessionName)
SetEndpointDataToClient(client)
return
}
// NewClientWithRamRoleArn is a shortcut to create sdk client with ram roleArn and policy
// usage: https://github.com/aliyun/alibaba-cloud-sdk-go/blob/master/docs/2-Client-EN.md
func NewClientWithRamRoleArnAndPolicy(regionId string, accessKeyId, accessKeySecret, roleArn, roleSessionName, policy string) (client *Client, err error) {
client = &Client{}
err = client.InitWithRamRoleArnAndPolicy(regionId, accessKeyId, accessKeySecret, roleArn, roleSessionName, policy)
SetEndpointDataToClient(client)
return
}
// NewClientWithEcsRamRole is a shortcut to create sdk client with ecs ram role
// usage: https://github.com/aliyun/alibaba-cloud-sdk-go/blob/master/docs/2-Client-EN.md
func NewClientWithEcsRamRole(regionId string, roleName string) (client *Client, err error) {
client = &Client{}
err = client.InitWithEcsRamRole(regionId, roleName)
SetEndpointDataToClient(client)
return
}
// NewClientWithRsaKeyPair is a shortcut to create sdk client with rsa key pair
// usage: https://github.com/aliyun/alibaba-cloud-sdk-go/blob/master/docs/2-Client-EN.md
func NewClientWithRsaKeyPair(regionId string, publicKeyId, privateKey string, sessionExpiration int) (client *Client, err error) {
client = &Client{}
err = client.InitWithRsaKeyPair(regionId, publicKeyId, privateKey, sessionExpiration)
SetEndpointDataToClient(client)
return
}

View File

@ -0,0 +1,112 @@
package slb
//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
//
//http://www.apache.org/licenses/LICENSE-2.0
//
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.
//
// Code generated by Alibaba Cloud SDK Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
import (
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses"
)
// CreateAccessControlList invokes the slb.CreateAccessControlList API synchronously
// api document: https://help.aliyun.com/api/slb/createaccesscontrollist.html
func (client *Client) CreateAccessControlList(request *CreateAccessControlListRequest) (response *CreateAccessControlListResponse, err error) {
response = CreateCreateAccessControlListResponse()
err = client.DoAction(request, response)
return
}
// CreateAccessControlListWithChan invokes the slb.CreateAccessControlList API asynchronously
// api document: https://help.aliyun.com/api/slb/createaccesscontrollist.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) CreateAccessControlListWithChan(request *CreateAccessControlListRequest) (<-chan *CreateAccessControlListResponse, <-chan error) {
responseChan := make(chan *CreateAccessControlListResponse, 1)
errChan := make(chan error, 1)
err := client.AddAsyncTask(func() {
defer close(responseChan)
defer close(errChan)
response, err := client.CreateAccessControlList(request)
if err != nil {
errChan <- err
} else {
responseChan <- response
}
})
if err != nil {
errChan <- err
close(responseChan)
close(errChan)
}
return responseChan, errChan
}
// CreateAccessControlListWithCallback invokes the slb.CreateAccessControlList API asynchronously
// api document: https://help.aliyun.com/api/slb/createaccesscontrollist.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) CreateAccessControlListWithCallback(request *CreateAccessControlListRequest, callback func(response *CreateAccessControlListResponse, err error)) <-chan int {
result := make(chan int, 1)
err := client.AddAsyncTask(func() {
var response *CreateAccessControlListResponse
var err error
defer close(result)
response, err = client.CreateAccessControlList(request)
callback(response, err)
result <- 1
})
if err != nil {
defer close(result)
callback(nil, err)
result <- 0
}
return result
}
// CreateAccessControlListRequest is the request struct for api CreateAccessControlList
type CreateAccessControlListRequest struct {
*requests.RpcRequest
AccessKeyId string `position:"Query" name:"access_key_id"`
ResourceOwnerId requests.Integer `position:"Query" name:"ResourceOwnerId"`
AclName string `position:"Query" name:"AclName"`
AddressIPVersion string `position:"Query" name:"AddressIPVersion"`
ResourceGroupId string `position:"Query" name:"ResourceGroupId"`
ResourceOwnerAccount string `position:"Query" name:"ResourceOwnerAccount"`
OwnerAccount string `position:"Query" name:"OwnerAccount"`
OwnerId requests.Integer `position:"Query" name:"OwnerId"`
Tags string `position:"Query" name:"Tags"`
}
// CreateAccessControlListResponse is the response struct for api CreateAccessControlList
type CreateAccessControlListResponse struct {
*responses.BaseResponse
RequestId string `json:"RequestId" xml:"RequestId"`
AclId string `json:"AclId" xml:"AclId"`
}
// CreateCreateAccessControlListRequest creates a request to invoke CreateAccessControlList API
func CreateCreateAccessControlListRequest() (request *CreateAccessControlListRequest) {
request = &CreateAccessControlListRequest{
RpcRequest: &requests.RpcRequest{},
}
request.InitWithApiInfo("Slb", "2014-05-15", "CreateAccessControlList", "slb", "openAPI")
return
}
// CreateCreateAccessControlListResponse creates a response to parse from CreateAccessControlList response
func CreateCreateAccessControlListResponse() (response *CreateAccessControlListResponse) {
response = &CreateAccessControlListResponse{
BaseResponse: &responses.BaseResponse{},
}
return
}

View File

@ -0,0 +1,114 @@
package slb
//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
//
//http://www.apache.org/licenses/LICENSE-2.0
//
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.
//
// Code generated by Alibaba Cloud SDK Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
import (
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses"
)
// CreateDomainExtension invokes the slb.CreateDomainExtension API synchronously
// api document: https://help.aliyun.com/api/slb/createdomainextension.html
func (client *Client) CreateDomainExtension(request *CreateDomainExtensionRequest) (response *CreateDomainExtensionResponse, err error) {
response = CreateCreateDomainExtensionResponse()
err = client.DoAction(request, response)
return
}
// CreateDomainExtensionWithChan invokes the slb.CreateDomainExtension API asynchronously
// api document: https://help.aliyun.com/api/slb/createdomainextension.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) CreateDomainExtensionWithChan(request *CreateDomainExtensionRequest) (<-chan *CreateDomainExtensionResponse, <-chan error) {
responseChan := make(chan *CreateDomainExtensionResponse, 1)
errChan := make(chan error, 1)
err := client.AddAsyncTask(func() {
defer close(responseChan)
defer close(errChan)
response, err := client.CreateDomainExtension(request)
if err != nil {
errChan <- err
} else {
responseChan <- response
}
})
if err != nil {
errChan <- err
close(responseChan)
close(errChan)
}
return responseChan, errChan
}
// CreateDomainExtensionWithCallback invokes the slb.CreateDomainExtension API asynchronously
// api document: https://help.aliyun.com/api/slb/createdomainextension.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) CreateDomainExtensionWithCallback(request *CreateDomainExtensionRequest, callback func(response *CreateDomainExtensionResponse, err error)) <-chan int {
result := make(chan int, 1)
err := client.AddAsyncTask(func() {
var response *CreateDomainExtensionResponse
var err error
defer close(result)
response, err = client.CreateDomainExtension(request)
callback(response, err)
result <- 1
})
if err != nil {
defer close(result)
callback(nil, err)
result <- 0
}
return result
}
// CreateDomainExtensionRequest is the request struct for api CreateDomainExtension
type CreateDomainExtensionRequest struct {
*requests.RpcRequest
AccessKeyId string `position:"Query" name:"access_key_id"`
ResourceOwnerId requests.Integer `position:"Query" name:"ResourceOwnerId"`
ListenerPort requests.Integer `position:"Query" name:"ListenerPort"`
ResourceOwnerAccount string `position:"Query" name:"ResourceOwnerAccount"`
OwnerAccount string `position:"Query" name:"OwnerAccount"`
OwnerId requests.Integer `position:"Query" name:"OwnerId"`
ServerCertificateId string `position:"Query" name:"ServerCertificateId"`
Tags string `position:"Query" name:"Tags"`
LoadBalancerId string `position:"Query" name:"LoadBalancerId"`
Domain string `position:"Query" name:"Domain"`
}
// CreateDomainExtensionResponse is the response struct for api CreateDomainExtension
type CreateDomainExtensionResponse struct {
*responses.BaseResponse
RequestId string `json:"RequestId" xml:"RequestId"`
ListenerPort int `json:"ListenerPort" xml:"ListenerPort"`
DomainExtensionId string `json:"DomainExtensionId" xml:"DomainExtensionId"`
}
// CreateCreateDomainExtensionRequest creates a request to invoke CreateDomainExtension API
func CreateCreateDomainExtensionRequest() (request *CreateDomainExtensionRequest) {
request = &CreateDomainExtensionRequest{
RpcRequest: &requests.RpcRequest{},
}
request.InitWithApiInfo("Slb", "2014-05-15", "CreateDomainExtension", "slb", "openAPI")
return
}
// CreateCreateDomainExtensionResponse creates a response to parse from CreateDomainExtension response
func CreateCreateDomainExtensionResponse() (response *CreateDomainExtensionResponse) {
response = &CreateDomainExtensionResponse{
BaseResponse: &responses.BaseResponse{},
}
return
}

View File

@ -0,0 +1,139 @@
package slb
//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
//
//http://www.apache.org/licenses/LICENSE-2.0
//
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.
//
// Code generated by Alibaba Cloud SDK Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
import (
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses"
)
// CreateLoadBalancer invokes the slb.CreateLoadBalancer API synchronously
// api document: https://help.aliyun.com/api/slb/createloadbalancer.html
func (client *Client) CreateLoadBalancer(request *CreateLoadBalancerRequest) (response *CreateLoadBalancerResponse, err error) {
response = CreateCreateLoadBalancerResponse()
err = client.DoAction(request, response)
return
}
// CreateLoadBalancerWithChan invokes the slb.CreateLoadBalancer API asynchronously
// api document: https://help.aliyun.com/api/slb/createloadbalancer.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) CreateLoadBalancerWithChan(request *CreateLoadBalancerRequest) (<-chan *CreateLoadBalancerResponse, <-chan error) {
responseChan := make(chan *CreateLoadBalancerResponse, 1)
errChan := make(chan error, 1)
err := client.AddAsyncTask(func() {
defer close(responseChan)
defer close(errChan)
response, err := client.CreateLoadBalancer(request)
if err != nil {
errChan <- err
} else {
responseChan <- response
}
})
if err != nil {
errChan <- err
close(responseChan)
close(errChan)
}
return responseChan, errChan
}
// CreateLoadBalancerWithCallback invokes the slb.CreateLoadBalancer API asynchronously
// api document: https://help.aliyun.com/api/slb/createloadbalancer.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) CreateLoadBalancerWithCallback(request *CreateLoadBalancerRequest, callback func(response *CreateLoadBalancerResponse, err error)) <-chan int {
result := make(chan int, 1)
err := client.AddAsyncTask(func() {
var response *CreateLoadBalancerResponse
var err error
defer close(result)
response, err = client.CreateLoadBalancer(request)
callback(response, err)
result <- 1
})
if err != nil {
defer close(result)
callback(nil, err)
result <- 0
}
return result
}
// CreateLoadBalancerRequest is the request struct for api CreateLoadBalancer
type CreateLoadBalancerRequest struct {
*requests.RpcRequest
AccessKeyId string `position:"Query" name:"access_key_id"`
ResourceOwnerId requests.Integer `position:"Query" name:"ResourceOwnerId"`
SupportPrivateLink requests.Boolean `position:"Query" name:"SupportPrivateLink"`
ClientToken string `position:"Query" name:"ClientToken"`
CloudType string `position:"Query" name:"CloudType"`
AddressIPVersion string `position:"Query" name:"AddressIPVersion"`
MasterZoneId string `position:"Query" name:"MasterZoneId"`
Duration requests.Integer `position:"Query" name:"Duration"`
ResourceGroupId string `position:"Query" name:"ResourceGroupId"`
LoadBalancerName string `position:"Query" name:"LoadBalancerName"`
AddressType string `position:"Query" name:"AddressType"`
SlaveZoneId string `position:"Query" name:"SlaveZoneId"`
DeleteProtection string `position:"Query" name:"DeleteProtection"`
LoadBalancerSpec string `position:"Query" name:"LoadBalancerSpec"`
AutoPay requests.Boolean `position:"Query" name:"AutoPay"`
Address string `position:"Query" name:"Address"`
ResourceOwnerAccount string `position:"Query" name:"ResourceOwnerAccount"`
Bandwidth requests.Integer `position:"Query" name:"Bandwidth"`
OwnerAccount string `position:"Query" name:"OwnerAccount"`
OwnerId requests.Integer `position:"Query" name:"OwnerId"`
Tags string `position:"Query" name:"Tags"`
VSwitchId string `position:"Query" name:"VSwitchId"`
EnableVpcVipFlow string `position:"Query" name:"EnableVpcVipFlow"`
InternetChargeType string `position:"Query" name:"InternetChargeType"`
VpcId string `position:"Query" name:"VpcId"`
PayType string `position:"Query" name:"PayType"`
PricingCycle string `position:"Query" name:"PricingCycle"`
Ratio requests.Integer `position:"Query" name:"Ratio"`
}
// CreateLoadBalancerResponse is the response struct for api CreateLoadBalancer
type CreateLoadBalancerResponse struct {
*responses.BaseResponse
RequestId string `json:"RequestId" xml:"RequestId"`
LoadBalancerId string `json:"LoadBalancerId" xml:"LoadBalancerId"`
ResourceGroupId string `json:"ResourceGroupId" xml:"ResourceGroupId"`
Address string `json:"Address" xml:"Address"`
LoadBalancerName string `json:"LoadBalancerName" xml:"LoadBalancerName"`
VpcId string `json:"VpcId" xml:"VpcId"`
VSwitchId string `json:"VSwitchId" xml:"VSwitchId"`
NetworkType string `json:"NetworkType" xml:"NetworkType"`
OrderId int64 `json:"OrderId" xml:"OrderId"`
AddressIPVersion string `json:"AddressIPVersion" xml:"AddressIPVersion"`
}
// CreateCreateLoadBalancerRequest creates a request to invoke CreateLoadBalancer API
func CreateCreateLoadBalancerRequest() (request *CreateLoadBalancerRequest) {
request = &CreateLoadBalancerRequest{
RpcRequest: &requests.RpcRequest{},
}
request.InitWithApiInfo("Slb", "2014-05-15", "CreateLoadBalancer", "slb", "openAPI")
return
}
// CreateCreateLoadBalancerResponse creates a response to parse from CreateLoadBalancer response
func CreateCreateLoadBalancerResponse() (response *CreateLoadBalancerResponse) {
response = &CreateLoadBalancerResponse{
BaseResponse: &responses.BaseResponse{},
}
return
}

View File

@ -0,0 +1,145 @@
package slb
//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
//
//http://www.apache.org/licenses/LICENSE-2.0
//
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.
//
// Code generated by Alibaba Cloud SDK Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
import (
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses"
)
// CreateLoadBalancerHTTPListener invokes the slb.CreateLoadBalancerHTTPListener API synchronously
// api document: https://help.aliyun.com/api/slb/createloadbalancerhttplistener.html
func (client *Client) CreateLoadBalancerHTTPListener(request *CreateLoadBalancerHTTPListenerRequest) (response *CreateLoadBalancerHTTPListenerResponse, err error) {
response = CreateCreateLoadBalancerHTTPListenerResponse()
err = client.DoAction(request, response)
return
}
// CreateLoadBalancerHTTPListenerWithChan invokes the slb.CreateLoadBalancerHTTPListener API asynchronously
// api document: https://help.aliyun.com/api/slb/createloadbalancerhttplistener.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) CreateLoadBalancerHTTPListenerWithChan(request *CreateLoadBalancerHTTPListenerRequest) (<-chan *CreateLoadBalancerHTTPListenerResponse, <-chan error) {
responseChan := make(chan *CreateLoadBalancerHTTPListenerResponse, 1)
errChan := make(chan error, 1)
err := client.AddAsyncTask(func() {
defer close(responseChan)
defer close(errChan)
response, err := client.CreateLoadBalancerHTTPListener(request)
if err != nil {
errChan <- err
} else {
responseChan <- response
}
})
if err != nil {
errChan <- err
close(responseChan)
close(errChan)
}
return responseChan, errChan
}
// CreateLoadBalancerHTTPListenerWithCallback invokes the slb.CreateLoadBalancerHTTPListener API asynchronously
// api document: https://help.aliyun.com/api/slb/createloadbalancerhttplistener.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) CreateLoadBalancerHTTPListenerWithCallback(request *CreateLoadBalancerHTTPListenerRequest, callback func(response *CreateLoadBalancerHTTPListenerResponse, err error)) <-chan int {
result := make(chan int, 1)
err := client.AddAsyncTask(func() {
var response *CreateLoadBalancerHTTPListenerResponse
var err error
defer close(result)
response, err = client.CreateLoadBalancerHTTPListener(request)
callback(response, err)
result <- 1
})
if err != nil {
defer close(result)
callback(nil, err)
result <- 0
}
return result
}
// CreateLoadBalancerHTTPListenerRequest is the request struct for api CreateLoadBalancerHTTPListener
type CreateLoadBalancerHTTPListenerRequest struct {
*requests.RpcRequest
ResourceOwnerId requests.Integer `position:"Query" name:"ResourceOwnerId"`
HealthCheckTimeout requests.Integer `position:"Query" name:"HealthCheckTimeout"`
ListenerForward string `position:"Query" name:"ListenerForward"`
XForwardedFor string `position:"Query" name:"XForwardedFor"`
HealthCheckURI string `position:"Query" name:"HealthCheckURI"`
AclStatus string `position:"Query" name:"AclStatus"`
AclType string `position:"Query" name:"AclType"`
HealthCheck string `position:"Query" name:"HealthCheck"`
VpcIds string `position:"Query" name:"VpcIds"`
VServerGroupId string `position:"Query" name:"VServerGroupId"`
AclId string `position:"Query" name:"AclId"`
Cookie string `position:"Query" name:"Cookie"`
HealthCheckMethod string `position:"Query" name:"HealthCheckMethod"`
HealthCheckDomain string `position:"Query" name:"HealthCheckDomain"`
RequestTimeout requests.Integer `position:"Query" name:"RequestTimeout"`
OwnerId requests.Integer `position:"Query" name:"OwnerId"`
Tags string `position:"Query" name:"Tags"`
LoadBalancerId string `position:"Query" name:"LoadBalancerId"`
XForwardedForSLBIP string `position:"Query" name:"XForwardedFor_SLBIP"`
BackendServerPort requests.Integer `position:"Query" name:"BackendServerPort"`
HealthCheckInterval requests.Integer `position:"Query" name:"HealthCheckInterval"`
XForwardedForSLBID string `position:"Query" name:"XForwardedFor_SLBID"`
HealthCheckHttpVersion string `position:"Query" name:"HealthCheckHttpVersion"`
AccessKeyId string `position:"Query" name:"access_key_id"`
Description string `position:"Query" name:"Description"`
UnhealthyThreshold requests.Integer `position:"Query" name:"UnhealthyThreshold"`
HealthyThreshold requests.Integer `position:"Query" name:"HealthyThreshold"`
Scheduler string `position:"Query" name:"Scheduler"`
ForwardPort requests.Integer `position:"Query" name:"ForwardPort"`
MaxConnection requests.Integer `position:"Query" name:"MaxConnection"`
CookieTimeout requests.Integer `position:"Query" name:"CookieTimeout"`
StickySessionType string `position:"Query" name:"StickySessionType"`
ListenerPort requests.Integer `position:"Query" name:"ListenerPort"`
HealthCheckType string `position:"Query" name:"HealthCheckType"`
ResourceOwnerAccount string `position:"Query" name:"ResourceOwnerAccount"`
Bandwidth requests.Integer `position:"Query" name:"Bandwidth"`
StickySession string `position:"Query" name:"StickySession"`
OwnerAccount string `position:"Query" name:"OwnerAccount"`
Gzip string `position:"Query" name:"Gzip"`
IdleTimeout requests.Integer `position:"Query" name:"IdleTimeout"`
XForwardedForProto string `position:"Query" name:"XForwardedFor_proto"`
HealthCheckConnectPort requests.Integer `position:"Query" name:"HealthCheckConnectPort"`
HealthCheckHttpCode string `position:"Query" name:"HealthCheckHttpCode"`
}
// CreateLoadBalancerHTTPListenerResponse is the response struct for api CreateLoadBalancerHTTPListener
type CreateLoadBalancerHTTPListenerResponse struct {
*responses.BaseResponse
RequestId string `json:"RequestId" xml:"RequestId"`
}
// CreateCreateLoadBalancerHTTPListenerRequest creates a request to invoke CreateLoadBalancerHTTPListener API
func CreateCreateLoadBalancerHTTPListenerRequest() (request *CreateLoadBalancerHTTPListenerRequest) {
request = &CreateLoadBalancerHTTPListenerRequest{
RpcRequest: &requests.RpcRequest{},
}
request.InitWithApiInfo("Slb", "2014-05-15", "CreateLoadBalancerHTTPListener", "slb", "openAPI")
return
}
// CreateCreateLoadBalancerHTTPListenerResponse creates a response to parse from CreateLoadBalancerHTTPListener response
func CreateCreateLoadBalancerHTTPListenerResponse() (response *CreateLoadBalancerHTTPListenerResponse) {
response = &CreateLoadBalancerHTTPListenerResponse{
BaseResponse: &responses.BaseResponse{},
}
return
}

View File

@ -0,0 +1,148 @@
package slb
//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
//
//http://www.apache.org/licenses/LICENSE-2.0
//
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.
//
// Code generated by Alibaba Cloud SDK Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
import (
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses"
)
// CreateLoadBalancerHTTPSListener invokes the slb.CreateLoadBalancerHTTPSListener API synchronously
// api document: https://help.aliyun.com/api/slb/createloadbalancerhttpslistener.html
func (client *Client) CreateLoadBalancerHTTPSListener(request *CreateLoadBalancerHTTPSListenerRequest) (response *CreateLoadBalancerHTTPSListenerResponse, err error) {
response = CreateCreateLoadBalancerHTTPSListenerResponse()
err = client.DoAction(request, response)
return
}
// CreateLoadBalancerHTTPSListenerWithChan invokes the slb.CreateLoadBalancerHTTPSListener API asynchronously
// api document: https://help.aliyun.com/api/slb/createloadbalancerhttpslistener.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) CreateLoadBalancerHTTPSListenerWithChan(request *CreateLoadBalancerHTTPSListenerRequest) (<-chan *CreateLoadBalancerHTTPSListenerResponse, <-chan error) {
responseChan := make(chan *CreateLoadBalancerHTTPSListenerResponse, 1)
errChan := make(chan error, 1)
err := client.AddAsyncTask(func() {
defer close(responseChan)
defer close(errChan)
response, err := client.CreateLoadBalancerHTTPSListener(request)
if err != nil {
errChan <- err
} else {
responseChan <- response
}
})
if err != nil {
errChan <- err
close(responseChan)
close(errChan)
}
return responseChan, errChan
}
// CreateLoadBalancerHTTPSListenerWithCallback invokes the slb.CreateLoadBalancerHTTPSListener API asynchronously
// api document: https://help.aliyun.com/api/slb/createloadbalancerhttpslistener.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) CreateLoadBalancerHTTPSListenerWithCallback(request *CreateLoadBalancerHTTPSListenerRequest, callback func(response *CreateLoadBalancerHTTPSListenerResponse, err error)) <-chan int {
result := make(chan int, 1)
err := client.AddAsyncTask(func() {
var response *CreateLoadBalancerHTTPSListenerResponse
var err error
defer close(result)
response, err = client.CreateLoadBalancerHTTPSListener(request)
callback(response, err)
result <- 1
})
if err != nil {
defer close(result)
callback(nil, err)
result <- 0
}
return result
}
// CreateLoadBalancerHTTPSListenerRequest is the request struct for api CreateLoadBalancerHTTPSListener
type CreateLoadBalancerHTTPSListenerRequest struct {
*requests.RpcRequest
ResourceOwnerId requests.Integer `position:"Query" name:"ResourceOwnerId"`
HealthCheckTimeout requests.Integer `position:"Query" name:"HealthCheckTimeout"`
XForwardedFor string `position:"Query" name:"XForwardedFor"`
HealthCheckURI string `position:"Query" name:"HealthCheckURI"`
AclStatus string `position:"Query" name:"AclStatus"`
AclType string `position:"Query" name:"AclType"`
HealthCheck string `position:"Query" name:"HealthCheck"`
VpcIds string `position:"Query" name:"VpcIds"`
VServerGroupId string `position:"Query" name:"VServerGroupId"`
AclId string `position:"Query" name:"AclId"`
Cookie string `position:"Query" name:"Cookie"`
HealthCheckMethod string `position:"Query" name:"HealthCheckMethod"`
HealthCheckDomain string `position:"Query" name:"HealthCheckDomain"`
RequestTimeout requests.Integer `position:"Query" name:"RequestTimeout"`
OwnerId requests.Integer `position:"Query" name:"OwnerId"`
CACertificateId string `position:"Query" name:"CACertificateId"`
BackendProtocol string `position:"Query" name:"BackendProtocol"`
Tags string `position:"Query" name:"Tags"`
LoadBalancerId string `position:"Query" name:"LoadBalancerId"`
XForwardedForSLBIP string `position:"Query" name:"XForwardedFor_SLBIP"`
BackendServerPort requests.Integer `position:"Query" name:"BackendServerPort"`
HealthCheckInterval requests.Integer `position:"Query" name:"HealthCheckInterval"`
XForwardedForSLBID string `position:"Query" name:"XForwardedFor_SLBID"`
HealthCheckHttpVersion string `position:"Query" name:"HealthCheckHttpVersion"`
AccessKeyId string `position:"Query" name:"access_key_id"`
Description string `position:"Query" name:"Description"`
UnhealthyThreshold requests.Integer `position:"Query" name:"UnhealthyThreshold"`
HealthyThreshold requests.Integer `position:"Query" name:"HealthyThreshold"`
Scheduler string `position:"Query" name:"Scheduler"`
MaxConnection requests.Integer `position:"Query" name:"MaxConnection"`
EnableHttp2 string `position:"Query" name:"EnableHttp2"`
CookieTimeout requests.Integer `position:"Query" name:"CookieTimeout"`
StickySessionType string `position:"Query" name:"StickySessionType"`
ListenerPort requests.Integer `position:"Query" name:"ListenerPort"`
HealthCheckType string `position:"Query" name:"HealthCheckType"`
ResourceOwnerAccount string `position:"Query" name:"ResourceOwnerAccount"`
Bandwidth requests.Integer `position:"Query" name:"Bandwidth"`
StickySession string `position:"Query" name:"StickySession"`
OwnerAccount string `position:"Query" name:"OwnerAccount"`
Gzip string `position:"Query" name:"Gzip"`
TLSCipherPolicy string `position:"Query" name:"TLSCipherPolicy"`
ServerCertificateId string `position:"Query" name:"ServerCertificateId"`
IdleTimeout requests.Integer `position:"Query" name:"IdleTimeout"`
XForwardedForProto string `position:"Query" name:"XForwardedFor_proto"`
HealthCheckConnectPort requests.Integer `position:"Query" name:"HealthCheckConnectPort"`
HealthCheckHttpCode string `position:"Query" name:"HealthCheckHttpCode"`
}
// CreateLoadBalancerHTTPSListenerResponse is the response struct for api CreateLoadBalancerHTTPSListener
type CreateLoadBalancerHTTPSListenerResponse struct {
*responses.BaseResponse
RequestId string `json:"RequestId" xml:"RequestId"`
}
// CreateCreateLoadBalancerHTTPSListenerRequest creates a request to invoke CreateLoadBalancerHTTPSListener API
func CreateCreateLoadBalancerHTTPSListenerRequest() (request *CreateLoadBalancerHTTPSListenerRequest) {
request = &CreateLoadBalancerHTTPSListenerRequest{
RpcRequest: &requests.RpcRequest{},
}
request.InitWithApiInfo("Slb", "2014-05-15", "CreateLoadBalancerHTTPSListener", "slb", "openAPI")
return
}
// CreateCreateLoadBalancerHTTPSListenerResponse creates a response to parse from CreateLoadBalancerHTTPSListener response
func CreateCreateLoadBalancerHTTPSListenerResponse() (response *CreateLoadBalancerHTTPSListenerResponse) {
response = &CreateLoadBalancerHTTPSListenerResponse{
BaseResponse: &responses.BaseResponse{},
}
return
}

View File

@ -0,0 +1,142 @@
package slb
//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
//
//http://www.apache.org/licenses/LICENSE-2.0
//
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.
//
// Code generated by Alibaba Cloud SDK Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
import (
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses"
)
// CreateLoadBalancerTCPListener invokes the slb.CreateLoadBalancerTCPListener API synchronously
// api document: https://help.aliyun.com/api/slb/createloadbalancertcplistener.html
func (client *Client) CreateLoadBalancerTCPListener(request *CreateLoadBalancerTCPListenerRequest) (response *CreateLoadBalancerTCPListenerResponse, err error) {
response = CreateCreateLoadBalancerTCPListenerResponse()
err = client.DoAction(request, response)
return
}
// CreateLoadBalancerTCPListenerWithChan invokes the slb.CreateLoadBalancerTCPListener API asynchronously
// api document: https://help.aliyun.com/api/slb/createloadbalancertcplistener.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) CreateLoadBalancerTCPListenerWithChan(request *CreateLoadBalancerTCPListenerRequest) (<-chan *CreateLoadBalancerTCPListenerResponse, <-chan error) {
responseChan := make(chan *CreateLoadBalancerTCPListenerResponse, 1)
errChan := make(chan error, 1)
err := client.AddAsyncTask(func() {
defer close(responseChan)
defer close(errChan)
response, err := client.CreateLoadBalancerTCPListener(request)
if err != nil {
errChan <- err
} else {
responseChan <- response
}
})
if err != nil {
errChan <- err
close(responseChan)
close(errChan)
}
return responseChan, errChan
}
// CreateLoadBalancerTCPListenerWithCallback invokes the slb.CreateLoadBalancerTCPListener API asynchronously
// api document: https://help.aliyun.com/api/slb/createloadbalancertcplistener.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) CreateLoadBalancerTCPListenerWithCallback(request *CreateLoadBalancerTCPListenerRequest, callback func(response *CreateLoadBalancerTCPListenerResponse, err error)) <-chan int {
result := make(chan int, 1)
err := client.AddAsyncTask(func() {
var response *CreateLoadBalancerTCPListenerResponse
var err error
defer close(result)
response, err = client.CreateLoadBalancerTCPListener(request)
callback(response, err)
result <- 1
})
if err != nil {
defer close(result)
callback(nil, err)
result <- 0
}
return result
}
// CreateLoadBalancerTCPListenerRequest is the request struct for api CreateLoadBalancerTCPListener
type CreateLoadBalancerTCPListenerRequest struct {
*requests.RpcRequest
ResourceOwnerId requests.Integer `position:"Query" name:"ResourceOwnerId"`
HealthCheckURI string `position:"Query" name:"HealthCheckURI"`
AclStatus string `position:"Query" name:"AclStatus"`
AclType string `position:"Query" name:"AclType"`
EstablishedTimeout requests.Integer `position:"Query" name:"EstablishedTimeout"`
PersistenceTimeout requests.Integer `position:"Query" name:"PersistenceTimeout"`
VpcIds string `position:"Query" name:"VpcIds"`
VServerGroupId string `position:"Query" name:"VServerGroupId"`
AclId string `position:"Query" name:"AclId"`
PortRange *[]CreateLoadBalancerTCPListenerPortRange `position:"Query" name:"PortRange" type:"Repeated"`
HealthCheckMethod string `position:"Query" name:"HealthCheckMethod"`
HealthCheckDomain string `position:"Query" name:"HealthCheckDomain"`
OwnerId requests.Integer `position:"Query" name:"OwnerId"`
Tags string `position:"Query" name:"Tags"`
LoadBalancerId string `position:"Query" name:"LoadBalancerId"`
MasterSlaveServerGroupId string `position:"Query" name:"MasterSlaveServerGroupId"`
BackendServerPort requests.Integer `position:"Query" name:"BackendServerPort"`
HealthCheckInterval requests.Integer `position:"Query" name:"healthCheckInterval"`
ConnectionDrain string `position:"Query" name:"ConnectionDrain"`
AccessKeyId string `position:"Query" name:"access_key_id"`
HealthCheckConnectTimeout requests.Integer `position:"Query" name:"HealthCheckConnectTimeout"`
Description string `position:"Query" name:"Description"`
UnhealthyThreshold requests.Integer `position:"Query" name:"UnhealthyThreshold"`
HealthyThreshold requests.Integer `position:"Query" name:"HealthyThreshold"`
Scheduler string `position:"Query" name:"Scheduler"`
MaxConnection requests.Integer `position:"Query" name:"MaxConnection"`
ListenerPort requests.Integer `position:"Query" name:"ListenerPort"`
HealthCheckType string `position:"Query" name:"HealthCheckType"`
ResourceOwnerAccount string `position:"Query" name:"ResourceOwnerAccount"`
Bandwidth requests.Integer `position:"Query" name:"Bandwidth"`
OwnerAccount string `position:"Query" name:"OwnerAccount"`
ConnectionDrainTimeout requests.Integer `position:"Query" name:"ConnectionDrainTimeout"`
HealthCheckConnectPort requests.Integer `position:"Query" name:"HealthCheckConnectPort"`
HealthCheckHttpCode string `position:"Query" name:"HealthCheckHttpCode"`
}
// CreateLoadBalancerTCPListenerPortRange is a repeated param struct in CreateLoadBalancerTCPListenerRequest
type CreateLoadBalancerTCPListenerPortRange struct {
StartPort string `name:"StartPort"`
EndPort string `name:"EndPort"`
}
// CreateLoadBalancerTCPListenerResponse is the response struct for api CreateLoadBalancerTCPListener
type CreateLoadBalancerTCPListenerResponse struct {
*responses.BaseResponse
RequestId string `json:"RequestId" xml:"RequestId"`
}
// CreateCreateLoadBalancerTCPListenerRequest creates a request to invoke CreateLoadBalancerTCPListener API
func CreateCreateLoadBalancerTCPListenerRequest() (request *CreateLoadBalancerTCPListenerRequest) {
request = &CreateLoadBalancerTCPListenerRequest{
RpcRequest: &requests.RpcRequest{},
}
request.InitWithApiInfo("Slb", "2014-05-15", "CreateLoadBalancerTCPListener", "slb", "openAPI")
return
}
// CreateCreateLoadBalancerTCPListenerResponse creates a response to parse from CreateLoadBalancerTCPListener response
func CreateCreateLoadBalancerTCPListenerResponse() (response *CreateLoadBalancerTCPListenerResponse) {
response = &CreateLoadBalancerTCPListenerResponse{
BaseResponse: &responses.BaseResponse{},
}
return
}

View File

@ -0,0 +1,138 @@
package slb
//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
//
//http://www.apache.org/licenses/LICENSE-2.0
//
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.
//
// Code generated by Alibaba Cloud SDK Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
import (
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses"
)
// CreateLoadBalancerUDPListener invokes the slb.CreateLoadBalancerUDPListener API synchronously
// api document: https://help.aliyun.com/api/slb/createloadbalancerudplistener.html
func (client *Client) CreateLoadBalancerUDPListener(request *CreateLoadBalancerUDPListenerRequest) (response *CreateLoadBalancerUDPListenerResponse, err error) {
response = CreateCreateLoadBalancerUDPListenerResponse()
err = client.DoAction(request, response)
return
}
// CreateLoadBalancerUDPListenerWithChan invokes the slb.CreateLoadBalancerUDPListener API asynchronously
// api document: https://help.aliyun.com/api/slb/createloadbalancerudplistener.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) CreateLoadBalancerUDPListenerWithChan(request *CreateLoadBalancerUDPListenerRequest) (<-chan *CreateLoadBalancerUDPListenerResponse, <-chan error) {
responseChan := make(chan *CreateLoadBalancerUDPListenerResponse, 1)
errChan := make(chan error, 1)
err := client.AddAsyncTask(func() {
defer close(responseChan)
defer close(errChan)
response, err := client.CreateLoadBalancerUDPListener(request)
if err != nil {
errChan <- err
} else {
responseChan <- response
}
})
if err != nil {
errChan <- err
close(responseChan)
close(errChan)
}
return responseChan, errChan
}
// CreateLoadBalancerUDPListenerWithCallback invokes the slb.CreateLoadBalancerUDPListener API asynchronously
// api document: https://help.aliyun.com/api/slb/createloadbalancerudplistener.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) CreateLoadBalancerUDPListenerWithCallback(request *CreateLoadBalancerUDPListenerRequest, callback func(response *CreateLoadBalancerUDPListenerResponse, err error)) <-chan int {
result := make(chan int, 1)
err := client.AddAsyncTask(func() {
var response *CreateLoadBalancerUDPListenerResponse
var err error
defer close(result)
response, err = client.CreateLoadBalancerUDPListener(request)
callback(response, err)
result <- 1
})
if err != nil {
defer close(result)
callback(nil, err)
result <- 0
}
return result
}
// CreateLoadBalancerUDPListenerRequest is the request struct for api CreateLoadBalancerUDPListener
type CreateLoadBalancerUDPListenerRequest struct {
*requests.RpcRequest
ResourceOwnerId requests.Integer `position:"Query" name:"ResourceOwnerId"`
AclStatus string `position:"Query" name:"AclStatus"`
AclType string `position:"Query" name:"AclType"`
PersistenceTimeout requests.Integer `position:"Query" name:"PersistenceTimeout"`
VpcIds string `position:"Query" name:"VpcIds"`
VServerGroupId string `position:"Query" name:"VServerGroupId"`
AclId string `position:"Query" name:"AclId"`
PortRange *[]CreateLoadBalancerUDPListenerPortRange `position:"Query" name:"PortRange" type:"Repeated"`
OwnerId requests.Integer `position:"Query" name:"OwnerId"`
Tags string `position:"Query" name:"Tags"`
LoadBalancerId string `position:"Query" name:"LoadBalancerId"`
MasterSlaveServerGroupId string `position:"Query" name:"MasterSlaveServerGroupId"`
HealthCheckReq string `position:"Query" name:"healthCheckReq"`
BackendServerPort requests.Integer `position:"Query" name:"BackendServerPort"`
HealthCheckInterval requests.Integer `position:"Query" name:"healthCheckInterval"`
HealthCheckExp string `position:"Query" name:"healthCheckExp"`
ConnectionDrain string `position:"Query" name:"ConnectionDrain"`
AccessKeyId string `position:"Query" name:"access_key_id"`
HealthCheckConnectTimeout requests.Integer `position:"Query" name:"HealthCheckConnectTimeout"`
Description string `position:"Query" name:"Description"`
UnhealthyThreshold requests.Integer `position:"Query" name:"UnhealthyThreshold"`
HealthyThreshold requests.Integer `position:"Query" name:"HealthyThreshold"`
Scheduler string `position:"Query" name:"Scheduler"`
MaxConnection requests.Integer `position:"Query" name:"MaxConnection"`
ListenerPort requests.Integer `position:"Query" name:"ListenerPort"`
ResourceOwnerAccount string `position:"Query" name:"ResourceOwnerAccount"`
Bandwidth requests.Integer `position:"Query" name:"Bandwidth"`
OwnerAccount string `position:"Query" name:"OwnerAccount"`
ConnectionDrainTimeout requests.Integer `position:"Query" name:"ConnectionDrainTimeout"`
HealthCheckConnectPort requests.Integer `position:"Query" name:"HealthCheckConnectPort"`
}
// CreateLoadBalancerUDPListenerPortRange is a repeated param struct in CreateLoadBalancerUDPListenerRequest
type CreateLoadBalancerUDPListenerPortRange struct {
StartPort string `name:"StartPort"`
EndPort string `name:"EndPort"`
}
// CreateLoadBalancerUDPListenerResponse is the response struct for api CreateLoadBalancerUDPListener
type CreateLoadBalancerUDPListenerResponse struct {
*responses.BaseResponse
RequestId string `json:"RequestId" xml:"RequestId"`
}
// CreateCreateLoadBalancerUDPListenerRequest creates a request to invoke CreateLoadBalancerUDPListener API
func CreateCreateLoadBalancerUDPListenerRequest() (request *CreateLoadBalancerUDPListenerRequest) {
request = &CreateLoadBalancerUDPListenerRequest{
RpcRequest: &requests.RpcRequest{},
}
request.InitWithApiInfo("Slb", "2014-05-15", "CreateLoadBalancerUDPListener", "slb", "openAPI")
return
}
// CreateCreateLoadBalancerUDPListenerResponse creates a response to parse from CreateLoadBalancerUDPListener response
func CreateCreateLoadBalancerUDPListenerResponse() (response *CreateLoadBalancerUDPListenerResponse) {
response = &CreateLoadBalancerUDPListenerResponse{
BaseResponse: &responses.BaseResponse{},
}
return
}

View File

@ -0,0 +1,113 @@
package slb
//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
//
//http://www.apache.org/licenses/LICENSE-2.0
//
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.
//
// Code generated by Alibaba Cloud SDK Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
import (
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses"
)
// CreateMasterSlaveServerGroup invokes the slb.CreateMasterSlaveServerGroup API synchronously
// api document: https://help.aliyun.com/api/slb/createmasterslaveservergroup.html
func (client *Client) CreateMasterSlaveServerGroup(request *CreateMasterSlaveServerGroupRequest) (response *CreateMasterSlaveServerGroupResponse, err error) {
response = CreateCreateMasterSlaveServerGroupResponse()
err = client.DoAction(request, response)
return
}
// CreateMasterSlaveServerGroupWithChan invokes the slb.CreateMasterSlaveServerGroup API asynchronously
// api document: https://help.aliyun.com/api/slb/createmasterslaveservergroup.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) CreateMasterSlaveServerGroupWithChan(request *CreateMasterSlaveServerGroupRequest) (<-chan *CreateMasterSlaveServerGroupResponse, <-chan error) {
responseChan := make(chan *CreateMasterSlaveServerGroupResponse, 1)
errChan := make(chan error, 1)
err := client.AddAsyncTask(func() {
defer close(responseChan)
defer close(errChan)
response, err := client.CreateMasterSlaveServerGroup(request)
if err != nil {
errChan <- err
} else {
responseChan <- response
}
})
if err != nil {
errChan <- err
close(responseChan)
close(errChan)
}
return responseChan, errChan
}
// CreateMasterSlaveServerGroupWithCallback invokes the slb.CreateMasterSlaveServerGroup API asynchronously
// api document: https://help.aliyun.com/api/slb/createmasterslaveservergroup.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) CreateMasterSlaveServerGroupWithCallback(request *CreateMasterSlaveServerGroupRequest, callback func(response *CreateMasterSlaveServerGroupResponse, err error)) <-chan int {
result := make(chan int, 1)
err := client.AddAsyncTask(func() {
var response *CreateMasterSlaveServerGroupResponse
var err error
defer close(result)
response, err = client.CreateMasterSlaveServerGroup(request)
callback(response, err)
result <- 1
})
if err != nil {
defer close(result)
callback(nil, err)
result <- 0
}
return result
}
// CreateMasterSlaveServerGroupRequest is the request struct for api CreateMasterSlaveServerGroup
type CreateMasterSlaveServerGroupRequest struct {
*requests.RpcRequest
AccessKeyId string `position:"Query" name:"access_key_id"`
ResourceOwnerId requests.Integer `position:"Query" name:"ResourceOwnerId"`
MasterSlaveBackendServers string `position:"Query" name:"MasterSlaveBackendServers"`
ResourceOwnerAccount string `position:"Query" name:"ResourceOwnerAccount"`
OwnerAccount string `position:"Query" name:"OwnerAccount"`
MasterSlaveServerGroupName string `position:"Query" name:"MasterSlaveServerGroupName"`
OwnerId requests.Integer `position:"Query" name:"OwnerId"`
Tags string `position:"Query" name:"Tags"`
LoadBalancerId string `position:"Query" name:"LoadBalancerId"`
}
// CreateMasterSlaveServerGroupResponse is the response struct for api CreateMasterSlaveServerGroup
type CreateMasterSlaveServerGroupResponse struct {
*responses.BaseResponse
RequestId string `json:"RequestId" xml:"RequestId"`
MasterSlaveServerGroupId string `json:"MasterSlaveServerGroupId" xml:"MasterSlaveServerGroupId"`
MasterSlaveBackendServers MasterSlaveBackendServersInCreateMasterSlaveServerGroup `json:"MasterSlaveBackendServers" xml:"MasterSlaveBackendServers"`
}
// CreateCreateMasterSlaveServerGroupRequest creates a request to invoke CreateMasterSlaveServerGroup API
func CreateCreateMasterSlaveServerGroupRequest() (request *CreateMasterSlaveServerGroupRequest) {
request = &CreateMasterSlaveServerGroupRequest{
RpcRequest: &requests.RpcRequest{},
}
request.InitWithApiInfo("Slb", "2014-05-15", "CreateMasterSlaveServerGroup", "slb", "openAPI")
return
}
// CreateCreateMasterSlaveServerGroupResponse creates a response to parse from CreateMasterSlaveServerGroup response
func CreateCreateMasterSlaveServerGroupResponse() (response *CreateMasterSlaveServerGroupResponse) {
response = &CreateMasterSlaveServerGroupResponse{
BaseResponse: &responses.BaseResponse{},
}
return
}

View File

@ -0,0 +1,113 @@
package slb
//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
//
//http://www.apache.org/licenses/LICENSE-2.0
//
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.
//
// Code generated by Alibaba Cloud SDK Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
import (
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses"
)
// CreateRules invokes the slb.CreateRules API synchronously
// api document: https://help.aliyun.com/api/slb/createrules.html
func (client *Client) CreateRules(request *CreateRulesRequest) (response *CreateRulesResponse, err error) {
response = CreateCreateRulesResponse()
err = client.DoAction(request, response)
return
}
// CreateRulesWithChan invokes the slb.CreateRules API asynchronously
// api document: https://help.aliyun.com/api/slb/createrules.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) CreateRulesWithChan(request *CreateRulesRequest) (<-chan *CreateRulesResponse, <-chan error) {
responseChan := make(chan *CreateRulesResponse, 1)
errChan := make(chan error, 1)
err := client.AddAsyncTask(func() {
defer close(responseChan)
defer close(errChan)
response, err := client.CreateRules(request)
if err != nil {
errChan <- err
} else {
responseChan <- response
}
})
if err != nil {
errChan <- err
close(responseChan)
close(errChan)
}
return responseChan, errChan
}
// CreateRulesWithCallback invokes the slb.CreateRules API asynchronously
// api document: https://help.aliyun.com/api/slb/createrules.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) CreateRulesWithCallback(request *CreateRulesRequest, callback func(response *CreateRulesResponse, err error)) <-chan int {
result := make(chan int, 1)
err := client.AddAsyncTask(func() {
var response *CreateRulesResponse
var err error
defer close(result)
response, err = client.CreateRules(request)
callback(response, err)
result <- 1
})
if err != nil {
defer close(result)
callback(nil, err)
result <- 0
}
return result
}
// CreateRulesRequest is the request struct for api CreateRules
type CreateRulesRequest struct {
*requests.RpcRequest
AccessKeyId string `position:"Query" name:"access_key_id"`
ResourceOwnerId requests.Integer `position:"Query" name:"ResourceOwnerId"`
RuleList string `position:"Query" name:"RuleList"`
ListenerPort requests.Integer `position:"Query" name:"ListenerPort"`
ResourceOwnerAccount string `position:"Query" name:"ResourceOwnerAccount"`
OwnerAccount string `position:"Query" name:"OwnerAccount"`
OwnerId requests.Integer `position:"Query" name:"OwnerId"`
ListenerProtocol string `position:"Query" name:"ListenerProtocol"`
Tags string `position:"Query" name:"Tags"`
LoadBalancerId string `position:"Query" name:"LoadBalancerId"`
}
// CreateRulesResponse is the response struct for api CreateRules
type CreateRulesResponse struct {
*responses.BaseResponse
RequestId string `json:"RequestId" xml:"RequestId"`
Rules RulesInCreateRules `json:"Rules" xml:"Rules"`
}
// CreateCreateRulesRequest creates a request to invoke CreateRules API
func CreateCreateRulesRequest() (request *CreateRulesRequest) {
request = &CreateRulesRequest{
RpcRequest: &requests.RpcRequest{},
}
request.InitWithApiInfo("Slb", "2014-05-15", "CreateRules", "slb", "openAPI")
return
}
// CreateCreateRulesResponse creates a response to parse from CreateRules response
func CreateCreateRulesResponse() (response *CreateRulesResponse) {
response = &CreateRulesResponse{
BaseResponse: &responses.BaseResponse{},
}
return
}

View File

@ -0,0 +1,113 @@
package slb
//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
//
//http://www.apache.org/licenses/LICENSE-2.0
//
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.
//
// Code generated by Alibaba Cloud SDK Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
import (
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses"
)
// CreateVServerGroup invokes the slb.CreateVServerGroup API synchronously
// api document: https://help.aliyun.com/api/slb/createvservergroup.html
func (client *Client) CreateVServerGroup(request *CreateVServerGroupRequest) (response *CreateVServerGroupResponse, err error) {
response = CreateCreateVServerGroupResponse()
err = client.DoAction(request, response)
return
}
// CreateVServerGroupWithChan invokes the slb.CreateVServerGroup API asynchronously
// api document: https://help.aliyun.com/api/slb/createvservergroup.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) CreateVServerGroupWithChan(request *CreateVServerGroupRequest) (<-chan *CreateVServerGroupResponse, <-chan error) {
responseChan := make(chan *CreateVServerGroupResponse, 1)
errChan := make(chan error, 1)
err := client.AddAsyncTask(func() {
defer close(responseChan)
defer close(errChan)
response, err := client.CreateVServerGroup(request)
if err != nil {
errChan <- err
} else {
responseChan <- response
}
})
if err != nil {
errChan <- err
close(responseChan)
close(errChan)
}
return responseChan, errChan
}
// CreateVServerGroupWithCallback invokes the slb.CreateVServerGroup API asynchronously
// api document: https://help.aliyun.com/api/slb/createvservergroup.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) CreateVServerGroupWithCallback(request *CreateVServerGroupRequest, callback func(response *CreateVServerGroupResponse, err error)) <-chan int {
result := make(chan int, 1)
err := client.AddAsyncTask(func() {
var response *CreateVServerGroupResponse
var err error
defer close(result)
response, err = client.CreateVServerGroup(request)
callback(response, err)
result <- 1
})
if err != nil {
defer close(result)
callback(nil, err)
result <- 0
}
return result
}
// CreateVServerGroupRequest is the request struct for api CreateVServerGroup
type CreateVServerGroupRequest struct {
*requests.RpcRequest
AccessKeyId string `position:"Query" name:"access_key_id"`
ResourceOwnerId requests.Integer `position:"Query" name:"ResourceOwnerId"`
BackendServers string `position:"Query" name:"BackendServers"`
ResourceOwnerAccount string `position:"Query" name:"ResourceOwnerAccount"`
OwnerAccount string `position:"Query" name:"OwnerAccount"`
OwnerId requests.Integer `position:"Query" name:"OwnerId"`
Tags string `position:"Query" name:"Tags"`
VServerGroupName string `position:"Query" name:"VServerGroupName"`
LoadBalancerId string `position:"Query" name:"LoadBalancerId"`
}
// CreateVServerGroupResponse is the response struct for api CreateVServerGroup
type CreateVServerGroupResponse struct {
*responses.BaseResponse
RequestId string `json:"RequestId" xml:"RequestId"`
VServerGroupId string `json:"VServerGroupId" xml:"VServerGroupId"`
BackendServers BackendServersInCreateVServerGroup `json:"BackendServers" xml:"BackendServers"`
}
// CreateCreateVServerGroupRequest creates a request to invoke CreateVServerGroup API
func CreateCreateVServerGroupRequest() (request *CreateVServerGroupRequest) {
request = &CreateVServerGroupRequest{
RpcRequest: &requests.RpcRequest{},
}
request.InitWithApiInfo("Slb", "2014-05-15", "CreateVServerGroup", "slb", "openAPI")
return
}
// CreateCreateVServerGroupResponse creates a response to parse from CreateVServerGroup response
func CreateCreateVServerGroupResponse() (response *CreateVServerGroupResponse) {
response = &CreateVServerGroupResponse{
BaseResponse: &responses.BaseResponse{},
}
return
}

View File

@ -0,0 +1,109 @@
package slb
//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
//
//http://www.apache.org/licenses/LICENSE-2.0
//
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.
//
// Code generated by Alibaba Cloud SDK Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
import (
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses"
)
// DeleteAccessControlList invokes the slb.DeleteAccessControlList API synchronously
// api document: https://help.aliyun.com/api/slb/deleteaccesscontrollist.html
func (client *Client) DeleteAccessControlList(request *DeleteAccessControlListRequest) (response *DeleteAccessControlListResponse, err error) {
response = CreateDeleteAccessControlListResponse()
err = client.DoAction(request, response)
return
}
// DeleteAccessControlListWithChan invokes the slb.DeleteAccessControlList API asynchronously
// api document: https://help.aliyun.com/api/slb/deleteaccesscontrollist.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) DeleteAccessControlListWithChan(request *DeleteAccessControlListRequest) (<-chan *DeleteAccessControlListResponse, <-chan error) {
responseChan := make(chan *DeleteAccessControlListResponse, 1)
errChan := make(chan error, 1)
err := client.AddAsyncTask(func() {
defer close(responseChan)
defer close(errChan)
response, err := client.DeleteAccessControlList(request)
if err != nil {
errChan <- err
} else {
responseChan <- response
}
})
if err != nil {
errChan <- err
close(responseChan)
close(errChan)
}
return responseChan, errChan
}
// DeleteAccessControlListWithCallback invokes the slb.DeleteAccessControlList API asynchronously
// api document: https://help.aliyun.com/api/slb/deleteaccesscontrollist.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) DeleteAccessControlListWithCallback(request *DeleteAccessControlListRequest, callback func(response *DeleteAccessControlListResponse, err error)) <-chan int {
result := make(chan int, 1)
err := client.AddAsyncTask(func() {
var response *DeleteAccessControlListResponse
var err error
defer close(result)
response, err = client.DeleteAccessControlList(request)
callback(response, err)
result <- 1
})
if err != nil {
defer close(result)
callback(nil, err)
result <- 0
}
return result
}
// DeleteAccessControlListRequest is the request struct for api DeleteAccessControlList
type DeleteAccessControlListRequest struct {
*requests.RpcRequest
AccessKeyId string `position:"Query" name:"access_key_id"`
ResourceOwnerId requests.Integer `position:"Query" name:"ResourceOwnerId"`
AclId string `position:"Query" name:"AclId"`
ResourceOwnerAccount string `position:"Query" name:"ResourceOwnerAccount"`
OwnerAccount string `position:"Query" name:"OwnerAccount"`
OwnerId requests.Integer `position:"Query" name:"OwnerId"`
Tags string `position:"Query" name:"Tags"`
}
// DeleteAccessControlListResponse is the response struct for api DeleteAccessControlList
type DeleteAccessControlListResponse struct {
*responses.BaseResponse
RequestId string `json:"RequestId" xml:"RequestId"`
}
// CreateDeleteAccessControlListRequest creates a request to invoke DeleteAccessControlList API
func CreateDeleteAccessControlListRequest() (request *DeleteAccessControlListRequest) {
request = &DeleteAccessControlListRequest{
RpcRequest: &requests.RpcRequest{},
}
request.InitWithApiInfo("Slb", "2014-05-15", "DeleteAccessControlList", "slb", "openAPI")
return
}
// CreateDeleteAccessControlListResponse creates a response to parse from DeleteAccessControlList response
func CreateDeleteAccessControlListResponse() (response *DeleteAccessControlListResponse) {
response = &DeleteAccessControlListResponse{
BaseResponse: &responses.BaseResponse{},
}
return
}

View File

@ -0,0 +1,108 @@
package slb
//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
//
//http://www.apache.org/licenses/LICENSE-2.0
//
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.
//
// Code generated by Alibaba Cloud SDK Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
import (
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses"
)
// DeleteCACertificate invokes the slb.DeleteCACertificate API synchronously
// api document: https://help.aliyun.com/api/slb/deletecacertificate.html
func (client *Client) DeleteCACertificate(request *DeleteCACertificateRequest) (response *DeleteCACertificateResponse, err error) {
response = CreateDeleteCACertificateResponse()
err = client.DoAction(request, response)
return
}
// DeleteCACertificateWithChan invokes the slb.DeleteCACertificate API asynchronously
// api document: https://help.aliyun.com/api/slb/deletecacertificate.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) DeleteCACertificateWithChan(request *DeleteCACertificateRequest) (<-chan *DeleteCACertificateResponse, <-chan error) {
responseChan := make(chan *DeleteCACertificateResponse, 1)
errChan := make(chan error, 1)
err := client.AddAsyncTask(func() {
defer close(responseChan)
defer close(errChan)
response, err := client.DeleteCACertificate(request)
if err != nil {
errChan <- err
} else {
responseChan <- response
}
})
if err != nil {
errChan <- err
close(responseChan)
close(errChan)
}
return responseChan, errChan
}
// DeleteCACertificateWithCallback invokes the slb.DeleteCACertificate API asynchronously
// api document: https://help.aliyun.com/api/slb/deletecacertificate.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) DeleteCACertificateWithCallback(request *DeleteCACertificateRequest, callback func(response *DeleteCACertificateResponse, err error)) <-chan int {
result := make(chan int, 1)
err := client.AddAsyncTask(func() {
var response *DeleteCACertificateResponse
var err error
defer close(result)
response, err = client.DeleteCACertificate(request)
callback(response, err)
result <- 1
})
if err != nil {
defer close(result)
callback(nil, err)
result <- 0
}
return result
}
// DeleteCACertificateRequest is the request struct for api DeleteCACertificate
type DeleteCACertificateRequest struct {
*requests.RpcRequest
AccessKeyId string `position:"Query" name:"access_key_id"`
ResourceOwnerId requests.Integer `position:"Query" name:"ResourceOwnerId"`
ResourceOwnerAccount string `position:"Query" name:"ResourceOwnerAccount"`
OwnerAccount string `position:"Query" name:"OwnerAccount"`
OwnerId requests.Integer `position:"Query" name:"OwnerId"`
CACertificateId string `position:"Query" name:"CACertificateId"`
}
// DeleteCACertificateResponse is the response struct for api DeleteCACertificate
type DeleteCACertificateResponse struct {
*responses.BaseResponse
RequestId string `json:"RequestId" xml:"RequestId"`
}
// CreateDeleteCACertificateRequest creates a request to invoke DeleteCACertificate API
func CreateDeleteCACertificateRequest() (request *DeleteCACertificateRequest) {
request = &DeleteCACertificateRequest{
RpcRequest: &requests.RpcRequest{},
}
request.InitWithApiInfo("Slb", "2014-05-15", "DeleteCACertificate", "slb", "openAPI")
return
}
// CreateDeleteCACertificateResponse creates a response to parse from DeleteCACertificate response
func CreateDeleteCACertificateResponse() (response *DeleteCACertificateResponse) {
response = &DeleteCACertificateResponse{
BaseResponse: &responses.BaseResponse{},
}
return
}

View File

@ -0,0 +1,109 @@
package slb
//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
//
//http://www.apache.org/licenses/LICENSE-2.0
//
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.
//
// Code generated by Alibaba Cloud SDK Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
import (
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses"
)
// DeleteDomainExtension invokes the slb.DeleteDomainExtension API synchronously
// api document: https://help.aliyun.com/api/slb/deletedomainextension.html
func (client *Client) DeleteDomainExtension(request *DeleteDomainExtensionRequest) (response *DeleteDomainExtensionResponse, err error) {
response = CreateDeleteDomainExtensionResponse()
err = client.DoAction(request, response)
return
}
// DeleteDomainExtensionWithChan invokes the slb.DeleteDomainExtension API asynchronously
// api document: https://help.aliyun.com/api/slb/deletedomainextension.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) DeleteDomainExtensionWithChan(request *DeleteDomainExtensionRequest) (<-chan *DeleteDomainExtensionResponse, <-chan error) {
responseChan := make(chan *DeleteDomainExtensionResponse, 1)
errChan := make(chan error, 1)
err := client.AddAsyncTask(func() {
defer close(responseChan)
defer close(errChan)
response, err := client.DeleteDomainExtension(request)
if err != nil {
errChan <- err
} else {
responseChan <- response
}
})
if err != nil {
errChan <- err
close(responseChan)
close(errChan)
}
return responseChan, errChan
}
// DeleteDomainExtensionWithCallback invokes the slb.DeleteDomainExtension API asynchronously
// api document: https://help.aliyun.com/api/slb/deletedomainextension.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) DeleteDomainExtensionWithCallback(request *DeleteDomainExtensionRequest, callback func(response *DeleteDomainExtensionResponse, err error)) <-chan int {
result := make(chan int, 1)
err := client.AddAsyncTask(func() {
var response *DeleteDomainExtensionResponse
var err error
defer close(result)
response, err = client.DeleteDomainExtension(request)
callback(response, err)
result <- 1
})
if err != nil {
defer close(result)
callback(nil, err)
result <- 0
}
return result
}
// DeleteDomainExtensionRequest is the request struct for api DeleteDomainExtension
type DeleteDomainExtensionRequest struct {
*requests.RpcRequest
AccessKeyId string `position:"Query" name:"access_key_id"`
ResourceOwnerId requests.Integer `position:"Query" name:"ResourceOwnerId"`
DomainExtensionId string `position:"Query" name:"DomainExtensionId"`
ResourceOwnerAccount string `position:"Query" name:"ResourceOwnerAccount"`
OwnerAccount string `position:"Query" name:"OwnerAccount"`
OwnerId requests.Integer `position:"Query" name:"OwnerId"`
Tags string `position:"Query" name:"Tags"`
}
// DeleteDomainExtensionResponse is the response struct for api DeleteDomainExtension
type DeleteDomainExtensionResponse struct {
*responses.BaseResponse
RequestId string `json:"RequestId" xml:"RequestId"`
}
// CreateDeleteDomainExtensionRequest creates a request to invoke DeleteDomainExtension API
func CreateDeleteDomainExtensionRequest() (request *DeleteDomainExtensionRequest) {
request = &DeleteDomainExtensionRequest{
RpcRequest: &requests.RpcRequest{},
}
request.InitWithApiInfo("Slb", "2014-05-15", "DeleteDomainExtension", "slb", "openAPI")
return
}
// CreateDeleteDomainExtensionResponse creates a response to parse from DeleteDomainExtension response
func CreateDeleteDomainExtensionResponse() (response *DeleteDomainExtensionResponse) {
response = &DeleteDomainExtensionResponse{
BaseResponse: &responses.BaseResponse{},
}
return
}

View File

@ -0,0 +1,109 @@
package slb
//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
//
//http://www.apache.org/licenses/LICENSE-2.0
//
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.
//
// Code generated by Alibaba Cloud SDK Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
import (
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses"
)
// DeleteLoadBalancer invokes the slb.DeleteLoadBalancer API synchronously
// api document: https://help.aliyun.com/api/slb/deleteloadbalancer.html
func (client *Client) DeleteLoadBalancer(request *DeleteLoadBalancerRequest) (response *DeleteLoadBalancerResponse, err error) {
response = CreateDeleteLoadBalancerResponse()
err = client.DoAction(request, response)
return
}
// DeleteLoadBalancerWithChan invokes the slb.DeleteLoadBalancer API asynchronously
// api document: https://help.aliyun.com/api/slb/deleteloadbalancer.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) DeleteLoadBalancerWithChan(request *DeleteLoadBalancerRequest) (<-chan *DeleteLoadBalancerResponse, <-chan error) {
responseChan := make(chan *DeleteLoadBalancerResponse, 1)
errChan := make(chan error, 1)
err := client.AddAsyncTask(func() {
defer close(responseChan)
defer close(errChan)
response, err := client.DeleteLoadBalancer(request)
if err != nil {
errChan <- err
} else {
responseChan <- response
}
})
if err != nil {
errChan <- err
close(responseChan)
close(errChan)
}
return responseChan, errChan
}
// DeleteLoadBalancerWithCallback invokes the slb.DeleteLoadBalancer API asynchronously
// api document: https://help.aliyun.com/api/slb/deleteloadbalancer.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) DeleteLoadBalancerWithCallback(request *DeleteLoadBalancerRequest, callback func(response *DeleteLoadBalancerResponse, err error)) <-chan int {
result := make(chan int, 1)
err := client.AddAsyncTask(func() {
var response *DeleteLoadBalancerResponse
var err error
defer close(result)
response, err = client.DeleteLoadBalancer(request)
callback(response, err)
result <- 1
})
if err != nil {
defer close(result)
callback(nil, err)
result <- 0
}
return result
}
// DeleteLoadBalancerRequest is the request struct for api DeleteLoadBalancer
type DeleteLoadBalancerRequest struct {
*requests.RpcRequest
AccessKeyId string `position:"Query" name:"access_key_id"`
ResourceOwnerId requests.Integer `position:"Query" name:"ResourceOwnerId"`
ResourceOwnerAccount string `position:"Query" name:"ResourceOwnerAccount"`
OwnerAccount string `position:"Query" name:"OwnerAccount"`
OwnerId requests.Integer `position:"Query" name:"OwnerId"`
Tags string `position:"Query" name:"Tags"`
LoadBalancerId string `position:"Query" name:"LoadBalancerId"`
}
// DeleteLoadBalancerResponse is the response struct for api DeleteLoadBalancer
type DeleteLoadBalancerResponse struct {
*responses.BaseResponse
RequestId string `json:"RequestId" xml:"RequestId"`
}
// CreateDeleteLoadBalancerRequest creates a request to invoke DeleteLoadBalancer API
func CreateDeleteLoadBalancerRequest() (request *DeleteLoadBalancerRequest) {
request = &DeleteLoadBalancerRequest{
RpcRequest: &requests.RpcRequest{},
}
request.InitWithApiInfo("Slb", "2014-05-15", "DeleteLoadBalancer", "slb", "openAPI")
return
}
// CreateDeleteLoadBalancerResponse creates a response to parse from DeleteLoadBalancer response
func CreateDeleteLoadBalancerResponse() (response *DeleteLoadBalancerResponse) {
response = &DeleteLoadBalancerResponse{
BaseResponse: &responses.BaseResponse{},
}
return
}

View File

@ -0,0 +1,111 @@
package slb
//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
//
//http://www.apache.org/licenses/LICENSE-2.0
//
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.
//
// Code generated by Alibaba Cloud SDK Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
import (
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses"
)
// DeleteLoadBalancerListener invokes the slb.DeleteLoadBalancerListener API synchronously
// api document: https://help.aliyun.com/api/slb/deleteloadbalancerlistener.html
func (client *Client) DeleteLoadBalancerListener(request *DeleteLoadBalancerListenerRequest) (response *DeleteLoadBalancerListenerResponse, err error) {
response = CreateDeleteLoadBalancerListenerResponse()
err = client.DoAction(request, response)
return
}
// DeleteLoadBalancerListenerWithChan invokes the slb.DeleteLoadBalancerListener API asynchronously
// api document: https://help.aliyun.com/api/slb/deleteloadbalancerlistener.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) DeleteLoadBalancerListenerWithChan(request *DeleteLoadBalancerListenerRequest) (<-chan *DeleteLoadBalancerListenerResponse, <-chan error) {
responseChan := make(chan *DeleteLoadBalancerListenerResponse, 1)
errChan := make(chan error, 1)
err := client.AddAsyncTask(func() {
defer close(responseChan)
defer close(errChan)
response, err := client.DeleteLoadBalancerListener(request)
if err != nil {
errChan <- err
} else {
responseChan <- response
}
})
if err != nil {
errChan <- err
close(responseChan)
close(errChan)
}
return responseChan, errChan
}
// DeleteLoadBalancerListenerWithCallback invokes the slb.DeleteLoadBalancerListener API asynchronously
// api document: https://help.aliyun.com/api/slb/deleteloadbalancerlistener.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) DeleteLoadBalancerListenerWithCallback(request *DeleteLoadBalancerListenerRequest, callback func(response *DeleteLoadBalancerListenerResponse, err error)) <-chan int {
result := make(chan int, 1)
err := client.AddAsyncTask(func() {
var response *DeleteLoadBalancerListenerResponse
var err error
defer close(result)
response, err = client.DeleteLoadBalancerListener(request)
callback(response, err)
result <- 1
})
if err != nil {
defer close(result)
callback(nil, err)
result <- 0
}
return result
}
// DeleteLoadBalancerListenerRequest is the request struct for api DeleteLoadBalancerListener
type DeleteLoadBalancerListenerRequest struct {
*requests.RpcRequest
AccessKeyId string `position:"Query" name:"access_key_id"`
ResourceOwnerId requests.Integer `position:"Query" name:"ResourceOwnerId"`
ListenerPort requests.Integer `position:"Query" name:"ListenerPort"`
ResourceOwnerAccount string `position:"Query" name:"ResourceOwnerAccount"`
OwnerAccount string `position:"Query" name:"OwnerAccount"`
OwnerId requests.Integer `position:"Query" name:"OwnerId"`
ListenerProtocol string `position:"Query" name:"ListenerProtocol"`
Tags string `position:"Query" name:"Tags"`
LoadBalancerId string `position:"Query" name:"LoadBalancerId"`
}
// DeleteLoadBalancerListenerResponse is the response struct for api DeleteLoadBalancerListener
type DeleteLoadBalancerListenerResponse struct {
*responses.BaseResponse
RequestId string `json:"RequestId" xml:"RequestId"`
}
// CreateDeleteLoadBalancerListenerRequest creates a request to invoke DeleteLoadBalancerListener API
func CreateDeleteLoadBalancerListenerRequest() (request *DeleteLoadBalancerListenerRequest) {
request = &DeleteLoadBalancerListenerRequest{
RpcRequest: &requests.RpcRequest{},
}
request.InitWithApiInfo("Slb", "2014-05-15", "DeleteLoadBalancerListener", "slb", "openAPI")
return
}
// CreateDeleteLoadBalancerListenerResponse creates a response to parse from DeleteLoadBalancerListener response
func CreateDeleteLoadBalancerListenerResponse() (response *DeleteLoadBalancerListenerResponse) {
response = &DeleteLoadBalancerListenerResponse{
BaseResponse: &responses.BaseResponse{},
}
return
}

View File

@ -0,0 +1,109 @@
package slb
//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
//
//http://www.apache.org/licenses/LICENSE-2.0
//
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.
//
// Code generated by Alibaba Cloud SDK Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
import (
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses"
)
// DeleteMasterSlaveServerGroup invokes the slb.DeleteMasterSlaveServerGroup API synchronously
// api document: https://help.aliyun.com/api/slb/deletemasterslaveservergroup.html
func (client *Client) DeleteMasterSlaveServerGroup(request *DeleteMasterSlaveServerGroupRequest) (response *DeleteMasterSlaveServerGroupResponse, err error) {
response = CreateDeleteMasterSlaveServerGroupResponse()
err = client.DoAction(request, response)
return
}
// DeleteMasterSlaveServerGroupWithChan invokes the slb.DeleteMasterSlaveServerGroup API asynchronously
// api document: https://help.aliyun.com/api/slb/deletemasterslaveservergroup.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) DeleteMasterSlaveServerGroupWithChan(request *DeleteMasterSlaveServerGroupRequest) (<-chan *DeleteMasterSlaveServerGroupResponse, <-chan error) {
responseChan := make(chan *DeleteMasterSlaveServerGroupResponse, 1)
errChan := make(chan error, 1)
err := client.AddAsyncTask(func() {
defer close(responseChan)
defer close(errChan)
response, err := client.DeleteMasterSlaveServerGroup(request)
if err != nil {
errChan <- err
} else {
responseChan <- response
}
})
if err != nil {
errChan <- err
close(responseChan)
close(errChan)
}
return responseChan, errChan
}
// DeleteMasterSlaveServerGroupWithCallback invokes the slb.DeleteMasterSlaveServerGroup API asynchronously
// api document: https://help.aliyun.com/api/slb/deletemasterslaveservergroup.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) DeleteMasterSlaveServerGroupWithCallback(request *DeleteMasterSlaveServerGroupRequest, callback func(response *DeleteMasterSlaveServerGroupResponse, err error)) <-chan int {
result := make(chan int, 1)
err := client.AddAsyncTask(func() {
var response *DeleteMasterSlaveServerGroupResponse
var err error
defer close(result)
response, err = client.DeleteMasterSlaveServerGroup(request)
callback(response, err)
result <- 1
})
if err != nil {
defer close(result)
callback(nil, err)
result <- 0
}
return result
}
// DeleteMasterSlaveServerGroupRequest is the request struct for api DeleteMasterSlaveServerGroup
type DeleteMasterSlaveServerGroupRequest struct {
*requests.RpcRequest
AccessKeyId string `position:"Query" name:"access_key_id"`
ResourceOwnerId requests.Integer `position:"Query" name:"ResourceOwnerId"`
ResourceOwnerAccount string `position:"Query" name:"ResourceOwnerAccount"`
OwnerAccount string `position:"Query" name:"OwnerAccount"`
OwnerId requests.Integer `position:"Query" name:"OwnerId"`
Tags string `position:"Query" name:"Tags"`
MasterSlaveServerGroupId string `position:"Query" name:"MasterSlaveServerGroupId"`
}
// DeleteMasterSlaveServerGroupResponse is the response struct for api DeleteMasterSlaveServerGroup
type DeleteMasterSlaveServerGroupResponse struct {
*responses.BaseResponse
RequestId string `json:"RequestId" xml:"RequestId"`
}
// CreateDeleteMasterSlaveServerGroupRequest creates a request to invoke DeleteMasterSlaveServerGroup API
func CreateDeleteMasterSlaveServerGroupRequest() (request *DeleteMasterSlaveServerGroupRequest) {
request = &DeleteMasterSlaveServerGroupRequest{
RpcRequest: &requests.RpcRequest{},
}
request.InitWithApiInfo("Slb", "2014-05-15", "DeleteMasterSlaveServerGroup", "slb", "openAPI")
return
}
// CreateDeleteMasterSlaveServerGroupResponse creates a response to parse from DeleteMasterSlaveServerGroup response
func CreateDeleteMasterSlaveServerGroupResponse() (response *DeleteMasterSlaveServerGroupResponse) {
response = &DeleteMasterSlaveServerGroupResponse{
BaseResponse: &responses.BaseResponse{},
}
return
}

View File

@ -0,0 +1,109 @@
package slb
//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
//
//http://www.apache.org/licenses/LICENSE-2.0
//
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.
//
// Code generated by Alibaba Cloud SDK Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
import (
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses"
)
// DeleteRules invokes the slb.DeleteRules API synchronously
// api document: https://help.aliyun.com/api/slb/deleterules.html
func (client *Client) DeleteRules(request *DeleteRulesRequest) (response *DeleteRulesResponse, err error) {
response = CreateDeleteRulesResponse()
err = client.DoAction(request, response)
return
}
// DeleteRulesWithChan invokes the slb.DeleteRules API asynchronously
// api document: https://help.aliyun.com/api/slb/deleterules.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) DeleteRulesWithChan(request *DeleteRulesRequest) (<-chan *DeleteRulesResponse, <-chan error) {
responseChan := make(chan *DeleteRulesResponse, 1)
errChan := make(chan error, 1)
err := client.AddAsyncTask(func() {
defer close(responseChan)
defer close(errChan)
response, err := client.DeleteRules(request)
if err != nil {
errChan <- err
} else {
responseChan <- response
}
})
if err != nil {
errChan <- err
close(responseChan)
close(errChan)
}
return responseChan, errChan
}
// DeleteRulesWithCallback invokes the slb.DeleteRules API asynchronously
// api document: https://help.aliyun.com/api/slb/deleterules.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) DeleteRulesWithCallback(request *DeleteRulesRequest, callback func(response *DeleteRulesResponse, err error)) <-chan int {
result := make(chan int, 1)
err := client.AddAsyncTask(func() {
var response *DeleteRulesResponse
var err error
defer close(result)
response, err = client.DeleteRules(request)
callback(response, err)
result <- 1
})
if err != nil {
defer close(result)
callback(nil, err)
result <- 0
}
return result
}
// DeleteRulesRequest is the request struct for api DeleteRules
type DeleteRulesRequest struct {
*requests.RpcRequest
AccessKeyId string `position:"Query" name:"access_key_id"`
ResourceOwnerId requests.Integer `position:"Query" name:"ResourceOwnerId"`
ResourceOwnerAccount string `position:"Query" name:"ResourceOwnerAccount"`
OwnerAccount string `position:"Query" name:"OwnerAccount"`
OwnerId requests.Integer `position:"Query" name:"OwnerId"`
Tags string `position:"Query" name:"Tags"`
RuleIds string `position:"Query" name:"RuleIds"`
}
// DeleteRulesResponse is the response struct for api DeleteRules
type DeleteRulesResponse struct {
*responses.BaseResponse
RequestId string `json:"RequestId" xml:"RequestId"`
}
// CreateDeleteRulesRequest creates a request to invoke DeleteRules API
func CreateDeleteRulesRequest() (request *DeleteRulesRequest) {
request = &DeleteRulesRequest{
RpcRequest: &requests.RpcRequest{},
}
request.InitWithApiInfo("Slb", "2014-05-15", "DeleteRules", "slb", "openAPI")
return
}
// CreateDeleteRulesResponse creates a response to parse from DeleteRules response
func CreateDeleteRulesResponse() (response *DeleteRulesResponse) {
response = &DeleteRulesResponse{
BaseResponse: &responses.BaseResponse{},
}
return
}

View File

@ -0,0 +1,109 @@
package slb
//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
//
//http://www.apache.org/licenses/LICENSE-2.0
//
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.
//
// Code generated by Alibaba Cloud SDK Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
import (
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses"
)
// DeleteServerCertificate invokes the slb.DeleteServerCertificate API synchronously
// api document: https://help.aliyun.com/api/slb/deleteservercertificate.html
func (client *Client) DeleteServerCertificate(request *DeleteServerCertificateRequest) (response *DeleteServerCertificateResponse, err error) {
response = CreateDeleteServerCertificateResponse()
err = client.DoAction(request, response)
return
}
// DeleteServerCertificateWithChan invokes the slb.DeleteServerCertificate API asynchronously
// api document: https://help.aliyun.com/api/slb/deleteservercertificate.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) DeleteServerCertificateWithChan(request *DeleteServerCertificateRequest) (<-chan *DeleteServerCertificateResponse, <-chan error) {
responseChan := make(chan *DeleteServerCertificateResponse, 1)
errChan := make(chan error, 1)
err := client.AddAsyncTask(func() {
defer close(responseChan)
defer close(errChan)
response, err := client.DeleteServerCertificate(request)
if err != nil {
errChan <- err
} else {
responseChan <- response
}
})
if err != nil {
errChan <- err
close(responseChan)
close(errChan)
}
return responseChan, errChan
}
// DeleteServerCertificateWithCallback invokes the slb.DeleteServerCertificate API asynchronously
// api document: https://help.aliyun.com/api/slb/deleteservercertificate.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) DeleteServerCertificateWithCallback(request *DeleteServerCertificateRequest, callback func(response *DeleteServerCertificateResponse, err error)) <-chan int {
result := make(chan int, 1)
err := client.AddAsyncTask(func() {
var response *DeleteServerCertificateResponse
var err error
defer close(result)
response, err = client.DeleteServerCertificate(request)
callback(response, err)
result <- 1
})
if err != nil {
defer close(result)
callback(nil, err)
result <- 0
}
return result
}
// DeleteServerCertificateRequest is the request struct for api DeleteServerCertificate
type DeleteServerCertificateRequest struct {
*requests.RpcRequest
AccessKeyId string `position:"Query" name:"access_key_id"`
ResourceOwnerId requests.Integer `position:"Query" name:"ResourceOwnerId"`
ResourceOwnerAccount string `position:"Query" name:"ResourceOwnerAccount"`
OwnerAccount string `position:"Query" name:"OwnerAccount"`
OwnerId requests.Integer `position:"Query" name:"OwnerId"`
ServerCertificateId string `position:"Query" name:"ServerCertificateId"`
Tags string `position:"Query" name:"Tags"`
}
// DeleteServerCertificateResponse is the response struct for api DeleteServerCertificate
type DeleteServerCertificateResponse struct {
*responses.BaseResponse
RequestId string `json:"RequestId" xml:"RequestId"`
}
// CreateDeleteServerCertificateRequest creates a request to invoke DeleteServerCertificate API
func CreateDeleteServerCertificateRequest() (request *DeleteServerCertificateRequest) {
request = &DeleteServerCertificateRequest{
RpcRequest: &requests.RpcRequest{},
}
request.InitWithApiInfo("Slb", "2014-05-15", "DeleteServerCertificate", "slb", "openAPI")
return
}
// CreateDeleteServerCertificateResponse creates a response to parse from DeleteServerCertificate response
func CreateDeleteServerCertificateResponse() (response *DeleteServerCertificateResponse) {
response = &DeleteServerCertificateResponse{
BaseResponse: &responses.BaseResponse{},
}
return
}

View File

@ -0,0 +1,109 @@
package slb
//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
//
//http://www.apache.org/licenses/LICENSE-2.0
//
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.
//
// Code generated by Alibaba Cloud SDK Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
import (
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses"
)
// DeleteVServerGroup invokes the slb.DeleteVServerGroup API synchronously
// api document: https://help.aliyun.com/api/slb/deletevservergroup.html
func (client *Client) DeleteVServerGroup(request *DeleteVServerGroupRequest) (response *DeleteVServerGroupResponse, err error) {
response = CreateDeleteVServerGroupResponse()
err = client.DoAction(request, response)
return
}
// DeleteVServerGroupWithChan invokes the slb.DeleteVServerGroup API asynchronously
// api document: https://help.aliyun.com/api/slb/deletevservergroup.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) DeleteVServerGroupWithChan(request *DeleteVServerGroupRequest) (<-chan *DeleteVServerGroupResponse, <-chan error) {
responseChan := make(chan *DeleteVServerGroupResponse, 1)
errChan := make(chan error, 1)
err := client.AddAsyncTask(func() {
defer close(responseChan)
defer close(errChan)
response, err := client.DeleteVServerGroup(request)
if err != nil {
errChan <- err
} else {
responseChan <- response
}
})
if err != nil {
errChan <- err
close(responseChan)
close(errChan)
}
return responseChan, errChan
}
// DeleteVServerGroupWithCallback invokes the slb.DeleteVServerGroup API asynchronously
// api document: https://help.aliyun.com/api/slb/deletevservergroup.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) DeleteVServerGroupWithCallback(request *DeleteVServerGroupRequest, callback func(response *DeleteVServerGroupResponse, err error)) <-chan int {
result := make(chan int, 1)
err := client.AddAsyncTask(func() {
var response *DeleteVServerGroupResponse
var err error
defer close(result)
response, err = client.DeleteVServerGroup(request)
callback(response, err)
result <- 1
})
if err != nil {
defer close(result)
callback(nil, err)
result <- 0
}
return result
}
// DeleteVServerGroupRequest is the request struct for api DeleteVServerGroup
type DeleteVServerGroupRequest struct {
*requests.RpcRequest
AccessKeyId string `position:"Query" name:"access_key_id"`
ResourceOwnerId requests.Integer `position:"Query" name:"ResourceOwnerId"`
VServerGroupId string `position:"Query" name:"VServerGroupId"`
ResourceOwnerAccount string `position:"Query" name:"ResourceOwnerAccount"`
OwnerAccount string `position:"Query" name:"OwnerAccount"`
OwnerId requests.Integer `position:"Query" name:"OwnerId"`
Tags string `position:"Query" name:"Tags"`
}
// DeleteVServerGroupResponse is the response struct for api DeleteVServerGroup
type DeleteVServerGroupResponse struct {
*responses.BaseResponse
RequestId string `json:"RequestId" xml:"RequestId"`
}
// CreateDeleteVServerGroupRequest creates a request to invoke DeleteVServerGroup API
func CreateDeleteVServerGroupRequest() (request *DeleteVServerGroupRequest) {
request = &DeleteVServerGroupRequest{
RpcRequest: &requests.RpcRequest{},
}
request.InitWithApiInfo("Slb", "2014-05-15", "DeleteVServerGroup", "slb", "openAPI")
return
}
// CreateDeleteVServerGroupResponse creates a response to parse from DeleteVServerGroup response
func CreateDeleteVServerGroupResponse() (response *DeleteVServerGroupResponse) {
response = &DeleteVServerGroupResponse{
BaseResponse: &responses.BaseResponse{},
}
return
}

View File

@ -0,0 +1,116 @@
package slb
//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
//
//http://www.apache.org/licenses/LICENSE-2.0
//
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.
//
// Code generated by Alibaba Cloud SDK Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
import (
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses"
)
// DescribeAccessControlListAttribute invokes the slb.DescribeAccessControlListAttribute API synchronously
// api document: https://help.aliyun.com/api/slb/describeaccesscontrollistattribute.html
func (client *Client) DescribeAccessControlListAttribute(request *DescribeAccessControlListAttributeRequest) (response *DescribeAccessControlListAttributeResponse, err error) {
response = CreateDescribeAccessControlListAttributeResponse()
err = client.DoAction(request, response)
return
}
// DescribeAccessControlListAttributeWithChan invokes the slb.DescribeAccessControlListAttribute API asynchronously
// api document: https://help.aliyun.com/api/slb/describeaccesscontrollistattribute.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) DescribeAccessControlListAttributeWithChan(request *DescribeAccessControlListAttributeRequest) (<-chan *DescribeAccessControlListAttributeResponse, <-chan error) {
responseChan := make(chan *DescribeAccessControlListAttributeResponse, 1)
errChan := make(chan error, 1)
err := client.AddAsyncTask(func() {
defer close(responseChan)
defer close(errChan)
response, err := client.DescribeAccessControlListAttribute(request)
if err != nil {
errChan <- err
} else {
responseChan <- response
}
})
if err != nil {
errChan <- err
close(responseChan)
close(errChan)
}
return responseChan, errChan
}
// DescribeAccessControlListAttributeWithCallback invokes the slb.DescribeAccessControlListAttribute API asynchronously
// api document: https://help.aliyun.com/api/slb/describeaccesscontrollistattribute.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) DescribeAccessControlListAttributeWithCallback(request *DescribeAccessControlListAttributeRequest, callback func(response *DescribeAccessControlListAttributeResponse, err error)) <-chan int {
result := make(chan int, 1)
err := client.AddAsyncTask(func() {
var response *DescribeAccessControlListAttributeResponse
var err error
defer close(result)
response, err = client.DescribeAccessControlListAttribute(request)
callback(response, err)
result <- 1
})
if err != nil {
defer close(result)
callback(nil, err)
result <- 0
}
return result
}
// DescribeAccessControlListAttributeRequest is the request struct for api DescribeAccessControlListAttribute
type DescribeAccessControlListAttributeRequest struct {
*requests.RpcRequest
AccessKeyId string `position:"Query" name:"access_key_id"`
ResourceOwnerId requests.Integer `position:"Query" name:"ResourceOwnerId"`
AclId string `position:"Query" name:"AclId"`
ResourceOwnerAccount string `position:"Query" name:"ResourceOwnerAccount"`
OwnerAccount string `position:"Query" name:"OwnerAccount"`
AclEntryComment string `position:"Query" name:"AclEntryComment"`
OwnerId requests.Integer `position:"Query" name:"OwnerId"`
Tags string `position:"Query" name:"Tags"`
}
// DescribeAccessControlListAttributeResponse is the response struct for api DescribeAccessControlListAttribute
type DescribeAccessControlListAttributeResponse struct {
*responses.BaseResponse
RequestId string `json:"RequestId" xml:"RequestId"`
AclId string `json:"AclId" xml:"AclId"`
AclName string `json:"AclName" xml:"AclName"`
AddressIPVersion string `json:"AddressIPVersion" xml:"AddressIPVersion"`
ResourceGroupId string `json:"ResourceGroupId" xml:"ResourceGroupId"`
AclEntrys AclEntrys `json:"AclEntrys" xml:"AclEntrys"`
RelatedListeners RelatedListeners `json:"RelatedListeners" xml:"RelatedListeners"`
}
// CreateDescribeAccessControlListAttributeRequest creates a request to invoke DescribeAccessControlListAttribute API
func CreateDescribeAccessControlListAttributeRequest() (request *DescribeAccessControlListAttributeRequest) {
request = &DescribeAccessControlListAttributeRequest{
RpcRequest: &requests.RpcRequest{},
}
request.InitWithApiInfo("Slb", "2014-05-15", "DescribeAccessControlListAttribute", "slb", "openAPI")
return
}
// CreateDescribeAccessControlListAttributeResponse creates a response to parse from DescribeAccessControlListAttribute response
func CreateDescribeAccessControlListAttributeResponse() (response *DescribeAccessControlListAttributeResponse) {
response = &DescribeAccessControlListAttributeResponse{
BaseResponse: &responses.BaseResponse{},
}
return
}

View File

@ -0,0 +1,125 @@
package slb
//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
//
//http://www.apache.org/licenses/LICENSE-2.0
//
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.
//
// Code generated by Alibaba Cloud SDK Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
import (
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses"
)
// DescribeAccessControlLists invokes the slb.DescribeAccessControlLists API synchronously
// api document: https://help.aliyun.com/api/slb/describeaccesscontrollists.html
func (client *Client) DescribeAccessControlLists(request *DescribeAccessControlListsRequest) (response *DescribeAccessControlListsResponse, err error) {
response = CreateDescribeAccessControlListsResponse()
err = client.DoAction(request, response)
return
}
// DescribeAccessControlListsWithChan invokes the slb.DescribeAccessControlLists API asynchronously
// api document: https://help.aliyun.com/api/slb/describeaccesscontrollists.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) DescribeAccessControlListsWithChan(request *DescribeAccessControlListsRequest) (<-chan *DescribeAccessControlListsResponse, <-chan error) {
responseChan := make(chan *DescribeAccessControlListsResponse, 1)
errChan := make(chan error, 1)
err := client.AddAsyncTask(func() {
defer close(responseChan)
defer close(errChan)
response, err := client.DescribeAccessControlLists(request)
if err != nil {
errChan <- err
} else {
responseChan <- response
}
})
if err != nil {
errChan <- err
close(responseChan)
close(errChan)
}
return responseChan, errChan
}
// DescribeAccessControlListsWithCallback invokes the slb.DescribeAccessControlLists API asynchronously
// api document: https://help.aliyun.com/api/slb/describeaccesscontrollists.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) DescribeAccessControlListsWithCallback(request *DescribeAccessControlListsRequest, callback func(response *DescribeAccessControlListsResponse, err error)) <-chan int {
result := make(chan int, 1)
err := client.AddAsyncTask(func() {
var response *DescribeAccessControlListsResponse
var err error
defer close(result)
response, err = client.DescribeAccessControlLists(request)
callback(response, err)
result <- 1
})
if err != nil {
defer close(result)
callback(nil, err)
result <- 0
}
return result
}
// DescribeAccessControlListsRequest is the request struct for api DescribeAccessControlLists
type DescribeAccessControlListsRequest struct {
*requests.RpcRequest
AccessKeyId string `position:"Query" name:"access_key_id"`
ResourceOwnerId requests.Integer `position:"Query" name:"ResourceOwnerId"`
AclName string `position:"Query" name:"AclName"`
AddressIPVersion string `position:"Query" name:"AddressIPVersion"`
PageNumber requests.Integer `position:"Query" name:"PageNumber"`
ResourceGroupId string `position:"Query" name:"ResourceGroupId"`
PageSize requests.Integer `position:"Query" name:"PageSize"`
Tag *[]DescribeAccessControlListsTag `position:"Query" name:"Tag" type:"Repeated"`
ResourceOwnerAccount string `position:"Query" name:"ResourceOwnerAccount"`
OwnerAccount string `position:"Query" name:"OwnerAccount"`
OwnerId requests.Integer `position:"Query" name:"OwnerId"`
Tags string `position:"Query" name:"Tags"`
}
// DescribeAccessControlListsTag is a repeated param struct in DescribeAccessControlListsRequest
type DescribeAccessControlListsTag struct {
Value string `name:"Value"`
Key string `name:"Key"`
}
// DescribeAccessControlListsResponse is the response struct for api DescribeAccessControlLists
type DescribeAccessControlListsResponse struct {
*responses.BaseResponse
RequestId string `json:"RequestId" xml:"RequestId"`
TotalCount int `json:"TotalCount" xml:"TotalCount"`
PageSize int `json:"PageSize" xml:"PageSize"`
Count int `json:"Count" xml:"Count"`
PageNumber int `json:"PageNumber" xml:"PageNumber"`
Acls Acls `json:"Acls" xml:"Acls"`
}
// CreateDescribeAccessControlListsRequest creates a request to invoke DescribeAccessControlLists API
func CreateDescribeAccessControlListsRequest() (request *DescribeAccessControlListsRequest) {
request = &DescribeAccessControlListsRequest{
RpcRequest: &requests.RpcRequest{},
}
request.InitWithApiInfo("Slb", "2014-05-15", "DescribeAccessControlLists", "slb", "openAPI")
return
}
// CreateDescribeAccessControlListsResponse creates a response to parse from DescribeAccessControlLists response
func CreateDescribeAccessControlListsResponse() (response *DescribeAccessControlListsResponse) {
response = &DescribeAccessControlListsResponse{
BaseResponse: &responses.BaseResponse{},
}
return
}

View File

@ -0,0 +1,110 @@
package slb
//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
//
//http://www.apache.org/licenses/LICENSE-2.0
//
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.
//
// Code generated by Alibaba Cloud SDK Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
import (
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses"
)
// DescribeAvailableResource invokes the slb.DescribeAvailableResource API synchronously
// api document: https://help.aliyun.com/api/slb/describeavailableresource.html
func (client *Client) DescribeAvailableResource(request *DescribeAvailableResourceRequest) (response *DescribeAvailableResourceResponse, err error) {
response = CreateDescribeAvailableResourceResponse()
err = client.DoAction(request, response)
return
}
// DescribeAvailableResourceWithChan invokes the slb.DescribeAvailableResource API asynchronously
// api document: https://help.aliyun.com/api/slb/describeavailableresource.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) DescribeAvailableResourceWithChan(request *DescribeAvailableResourceRequest) (<-chan *DescribeAvailableResourceResponse, <-chan error) {
responseChan := make(chan *DescribeAvailableResourceResponse, 1)
errChan := make(chan error, 1)
err := client.AddAsyncTask(func() {
defer close(responseChan)
defer close(errChan)
response, err := client.DescribeAvailableResource(request)
if err != nil {
errChan <- err
} else {
responseChan <- response
}
})
if err != nil {
errChan <- err
close(responseChan)
close(errChan)
}
return responseChan, errChan
}
// DescribeAvailableResourceWithCallback invokes the slb.DescribeAvailableResource API asynchronously
// api document: https://help.aliyun.com/api/slb/describeavailableresource.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) DescribeAvailableResourceWithCallback(request *DescribeAvailableResourceRequest, callback func(response *DescribeAvailableResourceResponse, err error)) <-chan int {
result := make(chan int, 1)
err := client.AddAsyncTask(func() {
var response *DescribeAvailableResourceResponse
var err error
defer close(result)
response, err = client.DescribeAvailableResource(request)
callback(response, err)
result <- 1
})
if err != nil {
defer close(result)
callback(nil, err)
result <- 0
}
return result
}
// DescribeAvailableResourceRequest is the request struct for api DescribeAvailableResource
type DescribeAvailableResourceRequest struct {
*requests.RpcRequest
AccessKeyId string `position:"Query" name:"access_key_id"`
ResourceOwnerId requests.Integer `position:"Query" name:"ResourceOwnerId"`
AddressIPVersion string `position:"Query" name:"AddressIPVersion"`
AddressType string `position:"Query" name:"AddressType"`
ResourceOwnerAccount string `position:"Query" name:"ResourceOwnerAccount"`
OwnerAccount string `position:"Query" name:"OwnerAccount"`
OwnerId requests.Integer `position:"Query" name:"OwnerId"`
}
// DescribeAvailableResourceResponse is the response struct for api DescribeAvailableResource
type DescribeAvailableResourceResponse struct {
*responses.BaseResponse
RequestId string `json:"RequestId" xml:"RequestId"`
AvailableResources AvailableResources `json:"AvailableResources" xml:"AvailableResources"`
}
// CreateDescribeAvailableResourceRequest creates a request to invoke DescribeAvailableResource API
func CreateDescribeAvailableResourceRequest() (request *DescribeAvailableResourceRequest) {
request = &DescribeAvailableResourceRequest{
RpcRequest: &requests.RpcRequest{},
}
request.InitWithApiInfo("Slb", "2014-05-15", "DescribeAvailableResource", "slb", "openAPI")
return
}
// CreateDescribeAvailableResourceResponse creates a response to parse from DescribeAvailableResource response
func CreateDescribeAvailableResourceResponse() (response *DescribeAvailableResourceResponse) {
response = &DescribeAvailableResourceResponse{
BaseResponse: &responses.BaseResponse{},
}
return
}

Some files were not shown because too many files have changed in this diff Show More